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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package globals provides an AST visitor that calls the visit function for all
// global identifiers.
package globals
import (
"fmt"
"go/ast"
"go/token"
"path/filepath"
"strconv"
)
// globalsVisitor holds the state used while traversing the nodes of a file in
// search of globals.
//
// The visitor does two passes on the global declarations: the first one adds
// all globals to the global scope (since Go allows references to globals that
// haven't been declared yet), and the second one calls f() for the definition
// and uses of globals found in the first pass.
//
// The implementation correctly handles cases when globals are aliased by
// locals; in such cases, f() is not called.
type globalsVisitor struct {
// file is the file whose nodes are being visited.
file *ast.File
// fset is the file set the file being visited belongs to.
fset *token.FileSet
// f is the visit function to be called when a global symbol is reached.
f func(*ast.Ident, SymKind)
// scope is the current scope as nodes are visited.
scope *scope
}
// unexpected is called when an unexpected node appears in the AST. It dumps
// the location of the associated token and panics because this should only
// happen when there is a bug in the traversal code.
func (v *globalsVisitor) unexpected(p token.Pos) {
panic(fmt.Sprintf("Unable to parse at %v", v.fset.Position(p)))
}
// pushScope creates a new scope and pushes it to the top of the scope stack.
func (v *globalsVisitor) pushScope() {
v.scope = newScope(v.scope)
}
// popScope removes the scope created by the last call to pushScope.
func (v *globalsVisitor) popScope() {
v.scope = v.scope.outer
}
// visitType is called when an expression is known to be a type, for example,
// on the first argument of make(). It visits all children nodes and reports
// any globals.
func (v *globalsVisitor) visitType(ge ast.Expr) {
switch e := ge.(type) {
case *ast.Ident:
if s := v.scope.deepLookup(e.Name); s != nil && s.scope.isGlobal() {
v.f(e, s.kind)
}
case *ast.SelectorExpr:
id := GetIdent(e.X)
if id == nil {
v.unexpected(e.X.Pos())
}
case *ast.StarExpr:
v.visitType(e.X)
case *ast.ParenExpr:
v.visitType(e.X)
case *ast.ChanType:
v.visitType(e.Value)
case *ast.Ellipsis:
v.visitType(e.Elt)
case *ast.ArrayType:
v.visitExpr(e.Len)
v.visitType(e.Elt)
case *ast.MapType:
v.visitType(e.Key)
v.visitType(e.Value)
case *ast.StructType:
v.visitFields(e.Fields, KindUnknown)
case *ast.FuncType:
v.visitFields(e.Params, KindUnknown)
v.visitFields(e.Results, KindUnknown)
case *ast.InterfaceType:
v.visitFields(e.Methods, KindUnknown)
default:
v.unexpected(ge.Pos())
}
}
// visitFields visits all fields, and add symbols if kind isn't KindUnknown.
func (v *globalsVisitor) visitFields(l *ast.FieldList, kind SymKind) {
if l == nil {
return
}
for _, f := range l.List {
if kind != KindUnknown {
for _, n := range f.Names {
v.scope.add(n.Name, kind, n.Pos())
}
}
v.visitType(f.Type)
if f.Tag != nil {
tag := ast.NewIdent(f.Tag.Value)
v.f(tag, KindTag)
// Replace the tag if updated.
if tag.Name != f.Tag.Value {
f.Tag.Value = tag.Name
}
}
}
}
// visitGenDecl is called when a generic declation is encountered, for example,
// on variable, constant and type declarations. It adds all newly defined
// symbols to the current scope and reports them if the current scope is the
// global one.
func (v *globalsVisitor) visitGenDecl(d *ast.GenDecl) {
switch d.Tok {
case token.IMPORT:
case token.TYPE:
for _, gs := range d.Specs {
s := gs.(*ast.TypeSpec)
v.scope.add(s.Name.Name, KindType, s.Name.Pos())
if v.scope.isGlobal() {
v.f(s.Name, KindType)
}
v.visitType(s.Type)
}
case token.CONST, token.VAR:
kind := KindConst
if d.Tok == token.VAR {
kind = KindVar
}
for _, gs := range d.Specs {
s := gs.(*ast.ValueSpec)
if s.Type != nil {
v.visitType(s.Type)
}
for _, e := range s.Values {
v.visitExpr(e)
}
for _, n := range s.Names {
if v.scope.isGlobal() {
v.f(n, kind)
}
v.scope.add(n.Name, kind, n.Pos())
}
}
default:
v.unexpected(d.Pos())
}
}
// isViableType determines if the given expression is a viable type expression,
// that is, if it could be interpreted as a type, for example, sync.Mutex,
// myType, func(int)int, as opposed to -1, 2 * 2, a + b, etc.
func (v *globalsVisitor) isViableType(expr ast.Expr) bool {
switch e := expr.(type) {
case *ast.Ident:
// This covers the plain identifier case. When we see it, we
// have to check if it resolves to a type; if the symbol is not
// known, we'll claim it's viable as a type.
s := v.scope.deepLookup(e.Name)
return s == nil || s.kind == KindType
case *ast.ChanType, *ast.ArrayType, *ast.MapType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.Ellipsis:
// This covers the following cases:
// 1. ChanType:
// chan T
// <-chan T
// chan<- T
// 2. ArrayType:
// [Expr]T
// 3. MapType:
// map[T]U
// 4. StructType:
// struct { Fields }
// 5. FuncType:
// func(Fields)Returns
// 6. Interface:
// interface { Fields }
// 7. Ellipsis:
// ...T
return true
case *ast.SelectorExpr:
// The only case in which an expression involving a selector can
// be a type is if it has the following form X.T, where X is an
// import, and T is a type exported by X.
//
// There's no way to know whether T is a type because we don't
// parse imports. So we just claim that this is a viable type;
// it doesn't affect the general result because we don't visit
// imported symbols.
id := GetIdent(e.X)
if id == nil {
return false
}
s := v.scope.deepLookup(id.Name)
return s != nil && s.kind == KindImport
case *ast.StarExpr:
// This covers the *T case. The expression is a viable type if
// T is.
return v.isViableType(e.X)
case *ast.ParenExpr:
// This covers the (T) case. The expression is a viable type if
// T is.
return v.isViableType(e.X)
default:
return false
}
}
// visitCallExpr visits a "call expression" which can be either a
// function/method call (e.g., f(), pkg.f(), obj.f(), etc.) call or a type
// conversion (e.g., int32(1), (*sync.Mutex)(ptr), etc.).
func (v *globalsVisitor) visitCallExpr(e *ast.CallExpr) {
if v.isViableType(e.Fun) {
v.visitType(e.Fun)
} else {
v.visitExpr(e.Fun)
}
// If the function being called is new or make, the first argument is
// a type, so it needs to be visited as such.
first := 0
if id := GetIdent(e.Fun); id != nil && (id.Name == "make" || id.Name == "new") {
if len(e.Args) > 0 {
v.visitType(e.Args[0])
}
first = 1
}
for i := first; i < len(e.Args); i++ {
v.visitExpr(e.Args[i])
}
}
// visitExpr visits all nodes of an expression, and reports any globals that it
// finds.
func (v *globalsVisitor) visitExpr(ge ast.Expr) {
switch e := ge.(type) {
case nil:
case *ast.Ident:
if s := v.scope.deepLookup(e.Name); s != nil && s.scope.isGlobal() {
v.f(e, s.kind)
}
case *ast.BasicLit:
case *ast.CompositeLit:
v.visitType(e.Type)
for _, ne := range e.Elts {
v.visitExpr(ne)
}
case *ast.FuncLit:
v.pushScope()
v.visitFields(e.Type.Params, KindParameter)
v.visitFields(e.Type.Results, KindResult)
v.visitBlockStmt(e.Body)
v.popScope()
case *ast.BinaryExpr:
v.visitExpr(e.X)
v.visitExpr(e.Y)
case *ast.CallExpr:
v.visitCallExpr(e)
case *ast.IndexExpr:
v.visitExpr(e.X)
v.visitExpr(e.Index)
case *ast.KeyValueExpr:
v.visitExpr(e.Value)
case *ast.ParenExpr:
v.visitExpr(e.X)
case *ast.SelectorExpr:
v.visitExpr(e.X)
case *ast.SliceExpr:
v.visitExpr(e.X)
v.visitExpr(e.Low)
v.visitExpr(e.High)
v.visitExpr(e.Max)
case *ast.StarExpr:
v.visitExpr(e.X)
case *ast.TypeAssertExpr:
v.visitExpr(e.X)
if e.Type != nil {
v.visitType(e.Type)
}
case *ast.UnaryExpr:
v.visitExpr(e.X)
default:
v.unexpected(ge.Pos())
}
}
// GetIdent returns the identifier associated with the given expression by
// removing parentheses if needed.
func GetIdent(expr ast.Expr) *ast.Ident {
switch e := expr.(type) {
case *ast.Ident:
return e
case *ast.ParenExpr:
return GetIdent(e.X)
default:
return nil
}
}
// visitStmt visits all nodes of a statement, and reports any globals that it
// finds. It also adds to the current scope new symbols defined/declared.
func (v *globalsVisitor) visitStmt(gs ast.Stmt) {
switch s := gs.(type) {
case nil, *ast.BranchStmt, *ast.EmptyStmt:
case *ast.AssignStmt:
for _, e := range s.Rhs {
v.visitExpr(e)
}
// We visit the LHS after the RHS because the symbols we'll
// potentially add to the table aren't meant to be visible to
// the RHS.
for _, e := range s.Lhs {
if s.Tok == token.DEFINE {
if n := GetIdent(e); n != nil {
v.scope.add(n.Name, KindVar, n.Pos())
}
}
v.visitExpr(e)
}
case *ast.BlockStmt:
v.visitBlockStmt(s)
case *ast.DeclStmt:
v.visitGenDecl(s.Decl.(*ast.GenDecl))
case *ast.DeferStmt:
v.visitCallExpr(s.Call)
case *ast.ExprStmt:
v.visitExpr(s.X)
case *ast.ForStmt:
v.pushScope()
v.visitStmt(s.Init)
v.visitExpr(s.Cond)
v.visitStmt(s.Post)
v.visitBlockStmt(s.Body)
v.popScope()
case *ast.GoStmt:
v.visitCallExpr(s.Call)
case *ast.IfStmt:
v.pushScope()
v.visitStmt(s.Init)
v.visitExpr(s.Cond)
v.visitBlockStmt(s.Body)
v.visitStmt(s.Else)
v.popScope()
case *ast.IncDecStmt:
v.visitExpr(s.X)
case *ast.LabeledStmt:
v.visitStmt(s.Stmt)
case *ast.RangeStmt:
v.pushScope()
v.visitExpr(s.X)
if s.Tok == token.DEFINE {
if n := GetIdent(s.Key); n != nil {
v.scope.add(n.Name, KindVar, n.Pos())
}
if n := GetIdent(s.Value); n != nil {
v.scope.add(n.Name, KindVar, n.Pos())
}
}
v.visitExpr(s.Key)
v.visitExpr(s.Value)
v.visitBlockStmt(s.Body)
v.popScope()
case *ast.ReturnStmt:
for _, r := range s.Results {
v.visitExpr(r)
}
case *ast.SelectStmt:
for _, ns := range s.Body.List {
c := ns.(*ast.CommClause)
v.pushScope()
v.visitStmt(c.Comm)
for _, bs := range c.Body {
v.visitStmt(bs)
}
v.popScope()
}
case *ast.SendStmt:
v.visitExpr(s.Chan)
v.visitExpr(s.Value)
case *ast.SwitchStmt:
v.pushScope()
v.visitStmt(s.Init)
v.visitExpr(s.Tag)
for _, ns := range s.Body.List {
c := ns.(*ast.CaseClause)
v.pushScope()
for _, ce := range c.List {
v.visitExpr(ce)
}
for _, bs := range c.Body {
v.visitStmt(bs)
}
v.popScope()
}
v.popScope()
case *ast.TypeSwitchStmt:
v.pushScope()
v.visitStmt(s.Init)
v.visitStmt(s.Assign)
for _, ns := range s.Body.List {
c := ns.(*ast.CaseClause)
v.pushScope()
for _, ce := range c.List {
v.visitType(ce)
}
for _, bs := range c.Body {
v.visitStmt(bs)
}
v.popScope()
}
v.popScope()
default:
v.unexpected(gs.Pos())
}
}
// visitBlockStmt visits all statements in the block, adding symbols to a newly
// created scope.
func (v *globalsVisitor) visitBlockStmt(s *ast.BlockStmt) {
v.pushScope()
for _, c := range s.List {
v.visitStmt(c)
}
v.popScope()
}
// visitFuncDecl is called when a function or method declation is encountered.
// it creates a new scope for the function [optional] receiver, parameters and
// results, and visits all children nodes.
func (v *globalsVisitor) visitFuncDecl(d *ast.FuncDecl) {
// We don't report methods.
if d.Recv == nil {
v.f(d.Name, KindFunction)
}
v.pushScope()
v.visitFields(d.Recv, KindReceiver)
v.visitFields(d.Type.Params, KindParameter)
v.visitFields(d.Type.Results, KindResult)
if d.Body != nil {
v.visitBlockStmt(d.Body)
}
v.popScope()
}
// globalsFromDecl is called in the first, and adds symbols to global scope.
func (v *globalsVisitor) globalsFromGenDecl(d *ast.GenDecl) {
switch d.Tok {
case token.IMPORT:
for _, gs := range d.Specs {
s := gs.(*ast.ImportSpec)
if s.Name == nil {
str, _ := strconv.Unquote(s.Path.Value)
v.scope.add(filepath.Base(str), KindImport, s.Path.Pos())
} else if s.Name.Name != "_" {
v.scope.add(s.Name.Name, KindImport, s.Name.Pos())
}
}
case token.TYPE:
for _, gs := range d.Specs {
s := gs.(*ast.TypeSpec)
v.scope.add(s.Name.Name, KindType, s.Name.Pos())
}
case token.CONST, token.VAR:
kind := KindConst
if d.Tok == token.VAR {
kind = KindVar
}
for _, s := range d.Specs {
for _, n := range s.(*ast.ValueSpec).Names {
v.scope.add(n.Name, kind, n.Pos())
}
}
default:
v.unexpected(d.Pos())
}
}
// visit implements the visiting of globals. It does performs the two passes
// described in the description of the globalsVisitor struct.
func (v *globalsVisitor) visit() {
// Gather all symbols in the global scope. This excludes methods.
v.pushScope()
for _, gd := range v.file.Decls {
switch d := gd.(type) {
case *ast.GenDecl:
v.globalsFromGenDecl(d)
case *ast.FuncDecl:
if d.Recv == nil {
v.scope.add(d.Name.Name, KindFunction, d.Name.Pos())
}
default:
v.unexpected(gd.Pos())
}
}
// Go through the contents of the declarations.
for _, gd := range v.file.Decls {
switch d := gd.(type) {
case *ast.GenDecl:
v.visitGenDecl(d)
case *ast.FuncDecl:
v.visitFuncDecl(d)
}
}
}
// Visit traverses the provided AST and calls f() for each identifier that
// refers to global names. The global name must be defined in the file itself.
//
// The function f() is allowed to modify the identifier, for example, to rename
// uses of global references.
func Visit(fset *token.FileSet, file *ast.File, f func(*ast.Ident, SymKind)) {
v := globalsVisitor{
fset: fset,
file: file,
f: f,
}
v.visit()
}
|