-
-
Notifications
You must be signed in to change notification settings - Fork 377
/
unused.go
1716 lines (1601 loc) · 46.8 KB
/
unused.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
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package unused
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"io"
"reflect"
"strings"
"honnef.co/go/tools/analysis/code"
"honnef.co/go/tools/analysis/facts"
"honnef.co/go/tools/analysis/lint"
"honnef.co/go/tools/analysis/report"
"honnef.co/go/tools/go/ast/astutil"
"honnef.co/go/tools/go/ir"
"honnef.co/go/tools/go/types/typeutil"
"honnef.co/go/tools/internal/passes/buildir"
"honnef.co/go/tools/unused/typemap"
"golang.org/x/tools/go/analysis"
)
var Debug io.Writer
// The graph we construct omits nodes along a path that do not
// contribute any new information to the solution. For example, the
// full graph for a function with a receiver would be Func ->
// Signature -> Var -> Type. However, since signatures cannot be
// unused, and receivers are always considered used, we can compact
// the graph down to Func -> Type. This makes the graph smaller, but
// harder to debug.
// TODO(dh): conversions between structs mark fields as used, but the
// conversion itself isn't part of that subgraph. even if the function
// containing the conversion is unused, the fields will be marked as
// used.
// TODO(dh): we cannot observe function calls in assembly files.
/*
- packages use:
- (1.1) exported named types
- (1.2) exported functions
- (1.3) exported variables
- (1.4) exported constants
- (1.5) init functions
- (1.6) functions exported to cgo
- (1.7) the main function iff in the main package
- (1.8) symbols linked via go:linkname
- named types use:
- (2.1) exported methods
- (2.2) the type they're based on
- (2.3) all their aliases. we can't easily track uses of aliases
because go/types turns them into uses of the aliased types. assume
that if a type is used, so are all of its aliases.
- (2.4) the pointer type. this aids with eagerly implementing
interfaces. if a method that implements an interface is defined on
a pointer receiver, and the pointer type is never used, but the
named type is, then we still want to mark the method as used.
- variables and constants use:
- their types
- functions use:
- (4.1) all their arguments, return parameters and receivers
- (4.2) anonymous functions defined beneath them
- (4.3) closures and bound methods.
this implements a simplified model where a function is used merely by being referenced, even if it is never called.
that way we don't have to keep track of closures escaping functions.
- (4.4) functions they return. we assume that someone else will call the returned function
- (4.5) functions/interface methods they call
- types they instantiate or convert to
- (4.7) fields they access
- (4.8) types of all instructions
- (4.9) package-level variables they assign to iff in tests (sinks for benchmarks)
- conversions use:
- (5.1) when converting between two equivalent structs, the fields in
either struct use each other. the fields are relevant for the
conversion, but only if the fields are also accessed outside the
conversion.
- (5.2) when converting to or from unsafe.Pointer, mark all fields as used.
- structs use:
- (6.1) fields of type NoCopy sentinel
- (6.2) exported fields
- (6.3) embedded fields that help implement interfaces (either fully implements it, or contributes required methods) (recursively)
- (6.4) embedded fields that have exported methods (recursively)
- (6.5) embedded structs that have exported fields (recursively)
- (7.1) field accesses use fields
- (7.2) fields use their types
- (8.0) How we handle interfaces:
- (8.1) We do not technically care about interfaces that only consist of
exported methods. Exported methods on concrete types are always
marked as used.
- Any concrete type implements all known interfaces. Even if it isn't
assigned to any interfaces in our code, the user may receive a value
of the type and expect to pass it back to us through an interface.
Concrete types use their methods that implement interfaces. If the
type is used, it uses those methods. Otherwise, it doesn't. This
way, types aren't incorrectly marked reachable through the edge
from method to type.
- (8.3) All interface methods are marked as used, even if they never get
called. This is to accommodate sum types (unexported interface
method that must exist but never gets called.)
- (8.4) All embedded interfaces are marked as used. This is an
extension of 8.3, but we have to explicitly track embedded
interfaces because in a chain C->B->A, B wouldn't be marked as
used by 8.3 just because it contributes A's methods to C.
- Inherent uses:
- thunks and other generated wrappers call the real function
- (9.2) variables use their types
- (9.3) types use their underlying and element types
- (9.4) conversions use the type they convert to
- (9.5) instructions use their operands
- (9.6) instructions use their operands' types
- (9.7) variable _reads_ use variables, writes do not, except in tests
- (9.8) runtime functions that may be called from user code via the compiler
- const groups:
(10.1) if one constant out of a block of constants is used, mark all
of them used. a lot of the time, unused constants exist for the sake
of completeness. See also
https://github.com/dominikh/go-tools/issues/365
- (11.1) anonymous struct types use all their fields. we cannot
deduplicate struct types, as that leads to order-dependent
reports. we can't not deduplicate struct types while still
tracking fields, because then each instance of the unnamed type in
the data flow chain will get its own fields, causing false
positives. Thus, we only accurately track fields of named struct
types, and assume that unnamed struct types use all their fields.
*/
func assert(b bool) {
if !b {
panic("failed assertion")
}
}
// /usr/lib/go/src/runtime/proc.go:433:6: func badmorestackg0 is unused (U1000)
// Functions defined in the Go runtime that may be called through
// compiler magic or via assembly.
var runtimeFuncs = map[string]bool{
// The first part of the list is copied from
// cmd/compile/internal/gc/builtin.go, var runtimeDecls
"newobject": true,
"panicindex": true,
"panicslice": true,
"panicdivide": true,
"panicmakeslicelen": true,
"throwinit": true,
"panicwrap": true,
"gopanic": true,
"gorecover": true,
"goschedguarded": true,
"printbool": true,
"printfloat": true,
"printint": true,
"printhex": true,
"printuint": true,
"printcomplex": true,
"printstring": true,
"printpointer": true,
"printiface": true,
"printeface": true,
"printslice": true,
"printnl": true,
"printsp": true,
"printlock": true,
"printunlock": true,
"concatstring2": true,
"concatstring3": true,
"concatstring4": true,
"concatstring5": true,
"concatstrings": true,
"cmpstring": true,
"intstring": true,
"slicebytetostring": true,
"slicebytetostringtmp": true,
"slicerunetostring": true,
"stringtoslicebyte": true,
"stringtoslicerune": true,
"slicecopy": true,
"slicestringcopy": true,
"decoderune": true,
"countrunes": true,
"convI2I": true,
"convT16": true,
"convT32": true,
"convT64": true,
"convTstring": true,
"convTslice": true,
"convT2E": true,
"convT2Enoptr": true,
"convT2I": true,
"convT2Inoptr": true,
"assertE2I": true,
"assertE2I2": true,
"assertI2I": true,
"assertI2I2": true,
"panicdottypeE": true,
"panicdottypeI": true,
"panicnildottype": true,
"ifaceeq": true,
"efaceeq": true,
"fastrand": true,
"makemap64": true,
"makemap": true,
"makemap_small": true,
"mapaccess1": true,
"mapaccess1_fast32": true,
"mapaccess1_fast64": true,
"mapaccess1_faststr": true,
"mapaccess1_fat": true,
"mapaccess2": true,
"mapaccess2_fast32": true,
"mapaccess2_fast64": true,
"mapaccess2_faststr": true,
"mapaccess2_fat": true,
"mapassign": true,
"mapassign_fast32": true,
"mapassign_fast32ptr": true,
"mapassign_fast64": true,
"mapassign_fast64ptr": true,
"mapassign_faststr": true,
"mapiterinit": true,
"mapdelete": true,
"mapdelete_fast32": true,
"mapdelete_fast64": true,
"mapdelete_faststr": true,
"mapiternext": true,
"mapclear": true,
"makechan64": true,
"makechan": true,
"chanrecv1": true,
"chanrecv2": true,
"chansend1": true,
"closechan": true,
"writeBarrier": true,
"typedmemmove": true,
"typedmemclr": true,
"typedslicecopy": true,
"selectnbsend": true,
"selectnbrecv": true,
"selectnbrecv2": true,
"selectsetpc": true,
"selectgo": true,
"block": true,
"makeslice": true,
"makeslice64": true,
"growslice": true,
"memmove": true,
"memclrNoHeapPointers": true,
"memclrHasPointers": true,
"memequal": true,
"memequal8": true,
"memequal16": true,
"memequal32": true,
"memequal64": true,
"memequal128": true,
"int64div": true,
"uint64div": true,
"int64mod": true,
"uint64mod": true,
"float64toint64": true,
"float64touint64": true,
"float64touint32": true,
"int64tofloat64": true,
"uint64tofloat64": true,
"uint32tofloat64": true,
"complex128div": true,
"racefuncenter": true,
"racefuncenterfp": true,
"racefuncexit": true,
"raceread": true,
"racewrite": true,
"racereadrange": true,
"racewriterange": true,
"msanread": true,
"msanwrite": true,
"x86HasPOPCNT": true,
"x86HasSSE41": true,
"arm64HasATOMICS": true,
// The second part of the list is extracted from assembly code in
// the standard library, with the exception of the runtime package itself
"abort": true,
"aeshashbody": true,
"args": true,
"asminit": true,
"badctxt": true,
"badmcall2": true,
"badmcall": true,
"badmorestackg0": true,
"badmorestackgsignal": true,
"badsignal2": true,
"callbackasm1": true,
"callCfunction": true,
"cgocallback_gofunc": true,
"cgocallbackg": true,
"checkgoarm": true,
"check": true,
"debugCallCheck": true,
"debugCallWrap": true,
"emptyfunc": true,
"entersyscall": true,
"exit": true,
"exits": true,
"exitsyscall": true,
"externalthreadhandler": true,
"findnull": true,
"goexit1": true,
"gostring": true,
"i386_set_ldt": true,
"_initcgo": true,
"init_thread_tls": true,
"ldt0setup": true,
"libpreinit": true,
"load_g": true,
"morestack": true,
"mstart": true,
"nacl_sysinfo": true,
"nanotimeQPC": true,
"nanotime": true,
"newosproc0": true,
"newproc": true,
"newstack": true,
"noted": true,
"nowQPC": true,
"osinit": true,
"printf": true,
"racecallback": true,
"reflectcallmove": true,
"reginit": true,
"rt0_go": true,
"save_g": true,
"schedinit": true,
"setldt": true,
"settls": true,
"sighandler": true,
"sigprofNonGo": true,
"sigtrampgo": true,
"_sigtramp": true,
"sigtramp": true,
"stackcheck": true,
"syscall_chdir": true,
"syscall_chroot": true,
"syscall_close": true,
"syscall_dup2": true,
"syscall_execve": true,
"syscall_exit": true,
"syscall_fcntl": true,
"syscall_forkx": true,
"syscall_gethostname": true,
"syscall_getpid": true,
"syscall_ioctl": true,
"syscall_pipe": true,
"syscall_rawsyscall6": true,
"syscall_rawSyscall6": true,
"syscall_rawsyscall": true,
"syscall_RawSyscall": true,
"syscall_rawsysvicall6": true,
"syscall_setgid": true,
"syscall_setgroups": true,
"syscall_setpgid": true,
"syscall_setsid": true,
"syscall_setuid": true,
"syscall_syscall6": true,
"syscall_syscall": true,
"syscall_Syscall": true,
"syscall_sysvicall6": true,
"syscall_wait4": true,
"syscall_write": true,
"traceback": true,
"tstart": true,
"usplitR0": true,
"wbBufFlush": true,
"write": true,
}
type pkg struct {
Fset *token.FileSet
Files []*ast.File
Pkg *types.Package
TypesInfo *types.Info
TypesSizes types.Sizes
IR *ir.Package
SrcFuncs []*ir.Function
Directives []lint.Directive
}
// TODO(dh): should we return a map instead of two slices?
type Result struct {
Used []types.Object
Unused []types.Object
}
type SerializedResult struct {
Used []SerializedObject
Unused []SerializedObject
}
var Analyzer = &lint.Analyzer{
Doc: &lint.Documentation{
Title: "Unused code",
},
Analyzer: &analysis.Analyzer{
Name: "U1000",
Doc: "Unused code",
Run: run,
Requires: []*analysis.Analyzer{buildir.Analyzer, facts.Generated, facts.Directives},
ResultType: reflect.TypeOf(Result{}),
},
}
type SerializedObject struct {
Name string
Position token.Position
DisplayPosition token.Position
Kind string
InGenerated bool
}
func typString(obj types.Object) string {
switch obj := obj.(type) {
case *types.Func:
return "func"
case *types.Var:
if obj.IsField() {
return "field"
}
return "var"
case *types.Const:
return "const"
case *types.TypeName:
return "type"
default:
return "identifier"
}
}
func Serialize(pass *analysis.Pass, res Result, fset *token.FileSet) SerializedResult {
// OPT(dh): there's no point in serializing Used objects that are
// always used, such as exported names, blank identifiers, or
// anonymous struct fields. Used only exists to overrule Unused of
// a different package. If something can never be unused, then its
// presence in Used is useless.
//
// I'm not sure if this should happen when serializing, or when
// returning Result.
out := SerializedResult{
Used: make([]SerializedObject, len(res.Used)),
Unused: make([]SerializedObject, len(res.Unused)),
}
for i, obj := range res.Used {
out.Used[i] = serializeObject(pass, fset, obj)
}
for i, obj := range res.Unused {
out.Unused[i] = serializeObject(pass, fset, obj)
}
return out
}
func serializeObject(pass *analysis.Pass, fset *token.FileSet, obj types.Object) SerializedObject {
name := obj.Name()
if sig, ok := obj.Type().(*types.Signature); ok && sig.Recv() != nil {
switch sig.Recv().Type().(type) {
case *types.Named, *types.Pointer:
typ := types.TypeString(sig.Recv().Type(), func(*types.Package) string { return "" })
if len(typ) > 0 && typ[0] == '*' {
name = fmt.Sprintf("(%s).%s", typ, obj.Name())
} else if len(typ) > 0 {
name = fmt.Sprintf("%s.%s", typ, obj.Name())
}
}
}
return SerializedObject{
Name: name,
Position: fset.PositionFor(obj.Pos(), false),
DisplayPosition: report.DisplayPosition(fset, obj.Pos()),
Kind: typString(obj),
InGenerated: code.IsGenerated(pass, obj.Pos()),
}
}
func debugf(f string, v ...interface{}) {
if Debug != nil {
fmt.Fprintf(Debug, f, v...)
}
}
func run(pass *analysis.Pass) (interface{}, error) {
irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR)
dirs := pass.ResultOf[facts.Directives].([]lint.Directive)
pkg := &pkg{
Fset: pass.Fset,
Files: pass.Files,
Pkg: pass.Pkg,
TypesInfo: pass.TypesInfo,
TypesSizes: pass.TypesSizes,
IR: irpkg.Pkg,
SrcFuncs: irpkg.SrcFuncs,
Directives: dirs,
}
g := newGraph()
g.entry(pkg)
used, unused := results(g)
if Debug != nil {
debugNode := func(n *node) {
if n.obj == nil {
debugf("n%d [label=\"Root\"];\n", n.id)
} else {
color := "red"
if n.seen {
color = "green"
}
debugf("n%d [label=%q, color=%q];\n", n.id, fmt.Sprintf("(%T) %s", n.obj, n.obj), color)
}
for _, e := range n.used {
for i := edgeKind(1); i < 64; i++ {
if e.kind.is(1 << i) {
debugf("n%d -> n%d [label=%q];\n", n.id, e.node.id, edgeKind(1<<i))
}
}
}
}
debugf("digraph{\n")
debugNode(g.Root)
for _, v := range g.Nodes {
debugNode(v)
}
g.TypeNodes.Iterate(func(key types.Type, value interface{}) {
debugNode(value.(*node))
})
debugf("}\n")
}
return Result{Used: used, Unused: unused}, nil
}
func results(g *graph) (used, unused []types.Object) {
g.color(g.Root)
g.TypeNodes.Iterate(func(_ types.Type, value interface{}) {
node := value.(*node)
if node.seen {
return
}
switch obj := node.obj.(type) {
case *types.Struct:
for i := 0; i < obj.NumFields(); i++ {
if node, ok := g.nodeMaybe(obj.Field(i)); ok {
node.quiet = true
}
}
case *types.Interface:
for i := 0; i < obj.NumExplicitMethods(); i++ {
m := obj.ExplicitMethod(i)
if node, ok := g.nodeMaybe(m); ok {
node.quiet = true
}
}
}
})
// OPT(dh): can we find meaningful initial capacities for the used and unused slices?
for _, n := range g.Nodes {
if obj, ok := n.obj.(types.Object); ok {
switch obj := obj.(type) {
case *types.Var:
// don't report unnamed variables (interface embedding)
if obj.Name() == "" && obj.IsField() {
continue
}
case types.Object:
if obj.Name() == "_" {
continue
}
}
if obj.Pkg() != nil {
if n.seen {
used = append(used, obj)
} else if !n.quiet {
if obj.Pkg() != g.pkg.Pkg {
continue
}
unused = append(unused, obj)
}
}
}
}
return used, unused
}
type graph struct {
Root *node
seenTypes typemap.Map
TypeNodes typemap.Map
Nodes map[interface{}]*node
// context
pkg *pkg
seenFns map[*ir.Function]struct{}
nodeCounter uint64
}
func newGraph() *graph {
g := &graph{
Nodes: map[interface{}]*node{},
seenFns: map[*ir.Function]struct{}{},
}
g.Root = g.newNode(nil)
return g
}
func (g *graph) color(root *node) {
if root.seen {
return
}
root.seen = true
for _, e := range root.used {
g.color(e.node)
}
}
type constGroup struct {
// give the struct a size to get unique pointers
_ byte
}
func (constGroup) String() string { return "const group" }
type edge struct {
node *node
kind edgeKind
}
type node struct {
obj interface{}
id uint64
// OPT(dh): evaluate using a map instead of a slice to avoid
// duplicate edges.
used []edge
// set during final graph walk if node is reachable
seen bool
quiet bool
}
func (g *graph) nodeMaybe(obj types.Object) (*node, bool) {
if node, ok := g.Nodes[obj]; ok {
return node, true
}
return nil, false
}
func (g *graph) node(obj interface{}) (n *node, new bool) {
switch obj := obj.(type) {
case types.Type:
if v := g.TypeNodes.At(obj); v != nil {
return v.(*node), false
}
n = g.newNode(obj)
g.TypeNodes.Set(obj, n)
return n, true
case types.Object:
// OPT(dh): the types.Object and default cases are identical
if node, ok := g.Nodes[obj]; ok {
return node, false
}
n = g.newNode(obj)
g.Nodes[obj] = n
return n, true
default:
if node, ok := g.Nodes[obj]; ok {
return node, false
}
n = g.newNode(obj)
g.Nodes[obj] = n
return n, true
}
}
func (g *graph) newNode(obj interface{}) *node {
g.nodeCounter++
return &node{
obj: obj,
id: g.nodeCounter,
}
}
func (n *node) use(n2 *node, kind edgeKind) {
assert(n2 != nil)
n.used = append(n.used, edge{node: n2, kind: kind})
}
// isIrrelevant reports whether an object's presence in the graph is
// of any relevance. A lot of objects will never have outgoing edges,
// nor meaningful incoming ones. Examples are basic types and empty
// signatures, among many others.
//
// Dropping these objects should have no effect on correctness, but
// may improve performance. It also helps with debugging, as it
// greatly reduces the size of the graph.
func isIrrelevant(obj interface{}) bool {
if obj, ok := obj.(types.Object); ok {
switch obj := obj.(type) {
case *types.Var:
if obj.IsField() {
// We need to track package fields
return false
}
if obj.Pkg() != nil && obj.Parent() == obj.Pkg().Scope() {
// We need to track package-level variables
return false
}
return isIrrelevant(obj.Type())
default:
return false
}
}
if T, ok := obj.(types.Type); ok {
switch T := T.(type) {
case *types.Array:
return isIrrelevant(T.Elem())
case *types.Slice:
return isIrrelevant(T.Elem())
case *types.Basic:
return true
case *types.Tuple:
for i := 0; i < T.Len(); i++ {
if !isIrrelevant(T.At(i).Type()) {
return false
}
}
return true
case *types.Signature:
if T.Recv() != nil {
return false
}
for i := 0; i < T.Params().Len(); i++ {
if !isIrrelevant(T.Params().At(i)) {
return false
}
}
for i := 0; i < T.Results().Len(); i++ {
if !isIrrelevant(T.Results().At(i)) {
return false
}
}
return true
case *types.Interface:
return T.NumMethods() == 0 && T.NumEmbeddeds() == 0
case *types.Pointer:
return isIrrelevant(T.Elem())
case *types.Map:
return isIrrelevant(T.Key()) && isIrrelevant(T.Elem())
case *types.Struct:
return T.NumFields() == 0
case *types.Chan:
return isIrrelevant(T.Elem())
default:
return false
}
}
return false
}
func (g *graph) see(obj interface{}) *node {
if isIrrelevant(obj) {
return nil
}
assert(obj != nil)
// add new node to graph
node, _ := g.node(obj)
return node
}
func (g *graph) use(used, by interface{}, kind edgeKind) {
if isIrrelevant(used) {
return
}
assert(used != nil)
if obj, ok := by.(types.Object); ok && obj.Pkg() != nil {
if obj.Pkg() != g.pkg.Pkg {
return
}
}
usedNode, new := g.node(used)
assert(!new)
if by == nil {
g.Root.use(usedNode, kind)
} else {
byNode, new := g.node(by)
assert(!new)
byNode.use(usedNode, kind)
}
}
func (g *graph) seeAndUse(used, by interface{}, kind edgeKind) *node {
n := g.see(used)
g.use(used, by, kind)
return n
}
func (g *graph) entry(pkg *pkg) {
g.pkg = pkg
scopes := map[*types.Scope]*ir.Function{}
for _, fn := range pkg.SrcFuncs {
if fn.Object() != nil {
scope := fn.Object().(*types.Func).Scope()
scopes[scope] = fn
}
}
for _, f := range pkg.Files {
for _, cg := range f.Comments {
for _, c := range cg.List {
if strings.HasPrefix(c.Text, "//go:linkname ") {
// FIXME(dh): we're looking at all comments. The
// compiler only looks at comments in the
// left-most column. The intention probably is to
// only look at top-level comments.
// (1.8) packages use symbols linked via go:linkname
fields := strings.Fields(c.Text)
if len(fields) == 3 {
if m, ok := pkg.IR.Members[fields[1]]; ok {
var obj types.Object
switch m := m.(type) {
case *ir.Global:
obj = m.Object()
case *ir.Function:
obj = m.Object()
default:
panic(fmt.Sprintf("unhandled type: %T", m))
}
assert(obj != nil)
g.seeAndUse(obj, nil, edgeLinkname)
}
}
}
}
}
}
surroundingFunc := func(obj types.Object) *ir.Function {
scope := obj.Parent()
for scope != nil {
if fn := scopes[scope]; fn != nil {
return fn
}
scope = scope.Parent()
}
return nil
}
// IR form won't tell us about locally scoped types that aren't
// being used. Walk the list of Defs to get all named types.
//
// IR form also won't tell us about constants; use Defs and Uses
// to determine which constants exist and which are being used.
for _, obj := range pkg.TypesInfo.Defs {
switch obj := obj.(type) {
case *types.TypeName:
// types are being handled by walking the AST
case *types.Const:
g.see(obj)
fn := surroundingFunc(obj)
if fn == nil && obj.Exported() {
// (1.4) packages use exported constants
g.use(obj, nil, edgeExportedConstant)
}
g.typ(obj.Type(), nil)
g.seeAndUse(obj.Type(), obj, edgeType)
}
}
// Find constants being used inside functions, find sinks in tests
for _, fn := range pkg.SrcFuncs {
if fn.Object() != nil {
g.see(fn.Object())
}
n := fn.Source()
if n == nil {
continue
}
ast.Inspect(n, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.Ident:
obj, ok := pkg.TypesInfo.Uses[n]
if !ok {
return true
}
switch obj := obj.(type) {
case *types.Const:
g.seeAndUse(obj, owningObject(fn), edgeUsedConstant)
}
case *ast.AssignStmt:
for _, expr := range n.Lhs {
ident, ok := expr.(*ast.Ident)
if !ok {
continue
}
obj := pkg.TypesInfo.ObjectOf(ident)
if obj == nil {
continue
}
path := pkg.Fset.File(obj.Pos()).Name()
if strings.HasSuffix(path, "_test.go") {
if obj.Parent() != nil && obj.Parent().Parent() != nil && obj.Parent().Parent().Parent() == nil {
// object's scope is the package, whose
// parent is the file, whose parent is nil
// (4.9) functions use package-level variables they assign to iff in tests (sinks for benchmarks)
// (9.7) variable _reads_ use variables, writes do not, except in tests
g.seeAndUse(obj, owningObject(fn), edgeTestSink)
}
}
}
}
return true
})
}
// Find constants being used in non-function contexts
for _, obj := range pkg.TypesInfo.Uses {
_, ok := obj.(*types.Const)
if !ok {
continue
}
g.seeAndUse(obj, nil, edgeUsedConstant)
}
var fns []*types.Func
var fn *types.Func
var stack []ast.Node
for _, f := range pkg.Files {
ast.Inspect(f, func(n ast.Node) bool {
if n == nil {
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if _, ok := pop.(*ast.FuncDecl); ok {
fns = fns[:len(fns)-1]
if len(fns) == 0 {
fn = nil
} else {
fn = fns[len(fns)-1]
}
}
return true
}
stack = append(stack, n)
switch n := n.(type) {
case *ast.FuncDecl:
fn = pkg.TypesInfo.ObjectOf(n.Name).(*types.Func)
fns = append(fns, fn)
g.see(fn)
case *ast.GenDecl:
switch n.Tok {
case token.CONST:
groups := astutil.GroupSpecs(pkg.Fset, n.Specs)
for _, specs := range groups {
if len(specs) > 1 {
cg := &constGroup{}
g.see(cg)
for _, spec := range specs {
for _, name := range spec.(*ast.ValueSpec).Names {
obj := pkg.TypesInfo.ObjectOf(name)
// (10.1) const groups
g.seeAndUse(obj, cg, edgeConstGroup)
g.use(cg, obj, edgeConstGroup)