-
-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathunused.go
1692 lines (1481 loc) · 46.7 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 contains code for finding unused code.
package unused
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"io"
"reflect"
"strings"
"honnef.co/go/tools/analysis/facts/directives"
"honnef.co/go/tools/analysis/facts/generated"
"honnef.co/go/tools/analysis/lint"
"honnef.co/go/tools/analysis/report"
"honnef.co/go/tools/go/ast/astutil"
"honnef.co/go/tools/go/types/typeutil"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/types/objectpath"
)
// OPT(dh): don't track local variables that can't have any interesting outgoing edges. For example, using a local
// variable of type int is meaningless; we don't care if `int` is used or not.
//
// Note that we do have to track variables with for example array types, because the array type could have involved a
// named constant.
//
// We probably have different culling needs depending on the mode of operation, too. If we analyze multiple packages in
// one graph (unused's "whole program" mode), we could remove further useless edges (e.g. into nodes that themselves
// have no outgoing edges and aren't meaningful objects on their own) after having analyzed a package, to keep the
// in-memory representation small on average. If we only analyze a single package, that step would just waste cycles, as
// we're about to throw the entire graph away, anyway.
// TODO(dh): currently, types use methods that implement interfaces. However, this makes a method used even if the
// relevant interface is never used. What if instead interfaces used those methods? Right now we cannot do that, because
// methods use their receivers, so using a method uses the type. But do we need that edge? Is there a way to refer to a
// method without explicitly mentioning the type somewhere? If not, the edge from method to receiver is superfluous.
// XXX vet all code for proper use of core types
// TODO(dh): we cannot observe function calls in assembly files.
/*
This overview is true when using the default options. Different options may change individual behaviors.
- packages use:
- (1.1) exported named types
- (1.2) exported functions (but not methods!)
- (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
- (1.9) objects in generated files
- named types use:
- (2.1) exported methods
- (2.2) the type they're based on
- (2.5) all their type parameters. Unused type parameters are probably useless, but they're a brand new feature and we
don't want to introduce false positives because we couldn't anticipate some novel use-case.
- (2.6) all their type arguments
- 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
- (4.6) types they instantiate or convert to
- (4.7) fields they access
- (4.9) package-level variables they assign to iff in tests (sinks for benchmarks)
- (4.10) all their type parameters. See 2.5 for reasoning.
- (4.11) local variables
- Note that the majority of this is handled implicitly by seeing idents be used. In particular, unlike the old
IR-based implementation, the AST-based one doesn't care about closures, bound methods or anonymous functions.
They're all just additional nodes in the AST.
- 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.
- (8.2) 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:
- (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.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
- (9.9) objects named the blank identifier are used. They cannot be referred to and are usually used explicitly to
use something that would otherwise be unused.
- The majority of idents get marked as read by virtue of being in the AST.
- 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
Do not, however, include constants named _ in constant groups.
- (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.
- type parameters use:
- (12.1) their constraint type
*/
var Debug io.Writer
func assert(b bool) {
if !b {
panic("failed assertion")
}
}
// TODO(dh): should we return a map instead of two slices?
type Result struct {
Used []Object
Unused []Object
Quiet []Object
}
var Analyzer = &lint.Analyzer{
Doc: &lint.RawDocumentation{
Title: "Unused code",
},
Analyzer: &analysis.Analyzer{
Name: "U1000",
Doc: "Unused code",
Run: run,
Requires: []*analysis.Analyzer{generated.Analyzer, directives.Analyzer},
ResultType: reflect.TypeOf(Result{}),
},
}
func newGraph(
fset *token.FileSet,
files []*ast.File,
pkg *types.Package,
info *types.Info,
directives []lint.Directive,
generated map[string]generated.Generator,
opts Options,
) *graph {
g := graph{
pkg: pkg,
info: info,
files: files,
directives: directives,
generated: generated,
fset: fset,
nodes: []Node{{}},
edges: map[edge]struct{}{},
objects: map[types.Object]NodeID{},
opts: opts,
}
return &g
}
func run(pass *analysis.Pass) (interface{}, error) {
g := newGraph(
pass.Fset,
pass.Files,
pass.Pkg,
pass.TypesInfo,
pass.ResultOf[directives.Analyzer].([]lint.Directive),
pass.ResultOf[generated.Analyzer].(map[string]generated.Generator),
DefaultOptions,
)
g.entry()
sg := &SerializedGraph{
nodes: g.nodes,
}
if Debug != nil {
Debug.Write([]byte(sg.Dot()))
}
return sg.Results(), nil
}
type Options struct {
FieldWritesAreUses bool
PostStatementsAreReads bool
ExportedIsUsed bool
ExportedFieldsAreUsed bool
ParametersAreUsed bool
LocalVariablesAreUsed bool
GeneratedIsUsed bool
}
var DefaultOptions = Options{
FieldWritesAreUses: true,
PostStatementsAreReads: false,
ExportedIsUsed: true,
ExportedFieldsAreUsed: true,
ParametersAreUsed: true,
LocalVariablesAreUsed: true,
GeneratedIsUsed: true,
}
type edgeKind uint8
const (
edgeKindUse = iota + 1
edgeKindOwn
)
type edge struct {
from, to NodeID
kind edgeKind
}
type graph struct {
pkg *types.Package
info *types.Info
files []*ast.File
fset *token.FileSet
directives []lint.Directive
generated map[string]generated.Generator
opts Options
// edges tracks all edges between nodes (uses and owns relationships). This data is also present in the Node struct,
// but there it can't be accessed in O(1) time. edges is used to deduplicate edges.
edges map[edge]struct{}
nodes []Node
objects map[types.Object]NodeID
// package-level named types
namedTypes []*types.TypeName
interfaceTypes []*types.Interface
}
type nodeState uint8
//gcassert:inline
func (ns nodeState) seen() bool { return ns&nodeStateSeen != 0 }
//gcassert:inline
func (ns nodeState) quiet() bool { return ns&nodeStateQuiet != 0 }
const (
nodeStateSeen nodeState = 1 << iota
nodeStateQuiet
)
// OPT(dh): 32 bits would be plenty, but the Node struct would end up with padding, anyway.
type NodeID uint64
type Node struct {
id NodeID
obj Object
// using slices instead of maps here helps make merging of graphs simpler and more efficient, because we can rewrite
// IDs in place instead of having to build new maps.
uses []NodeID
owns []NodeID
}
func (g *graph) objectToObject(obj types.Object) Object {
// OPT(dh): I think we only need object paths in whole-program mode. In other cases, position-based node merging
// should suffice.
// objectpath.For is an expensive function and we'd like to avoid calling it when we know that there cannot be a
// path, or when the path doesn't matter.
//
// Unexported global objects don't have paths. Local variables may have paths when they're parameters or return
// parameters, but we do not care about those, because they're not API that other packages can refer to directly. We
// do have to track fields, because they may be part of an anonymous type declared in a parameter or return
// parameter. We cannot categorically ignore unexported identifiers, because an exported field might have been
// embedded via an unexported field, which will be referred to.
var relevant bool
switch obj := obj.(type) {
case *types.Var:
// If it's a field or it's an exported top-level variable, we care about it. Otherwise, we don't.
// OPT(dh): same question as posed in the default branch
relevant = obj.IsField() || token.IsExported(obj.Name())
default:
// OPT(dh): See if it's worth checking that the object is actually in package scope, and doesn't just have a
// capitalized name.
relevant = token.IsExported(obj.Name())
}
var path ObjectPath
if relevant {
objPath, _ := objectpath.For(obj)
if objPath != "" {
path = ObjectPath{
PkgPath: obj.Pkg().Path(),
ObjPath: objPath,
}
}
}
name := obj.Name()
if sig, ok := obj.Type().(*types.Signature); ok && sig.Recv() != nil {
switch types.Unalias(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 Object{
Name: name,
ShortName: obj.Name(),
Kind: typString(obj),
Path: path,
Position: g.fset.PositionFor(obj.Pos(), false),
DisplayPosition: report.DisplayPosition(g.fset, obj.Pos()),
}
}
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:
if _, ok := obj.Type().(*types.TypeParam); ok {
return "type param"
} else {
return "type"
}
default:
return "identifier"
}
}
func (g *graph) newNode(obj types.Object) NodeID {
id := NodeID(len(g.nodes))
n := Node{
id: id,
obj: g.objectToObject(obj),
}
g.nodes = append(g.nodes, n)
if _, ok := g.objects[obj]; ok {
panic(fmt.Sprintf("already had a node for %s", obj))
}
g.objects[obj] = id
return id
}
func (g *graph) node(obj types.Object) NodeID {
if obj == nil {
return 0
}
obj = origin(obj)
if n, ok := g.objects[obj]; ok {
return n
}
n := g.newNode(obj)
return n
}
func origin(obj types.Object) types.Object {
switch obj := obj.(type) {
case *types.Var:
return obj.Origin()
case *types.Func:
return obj.Origin()
default:
return obj
}
}
func (g *graph) addEdge(e edge) bool {
if _, ok := g.edges[e]; ok {
return false
}
g.edges[e] = struct{}{}
return true
}
func (g *graph) addOwned(owner, owned NodeID) {
e := edge{owner, owned, edgeKindOwn}
if !g.addEdge(e) {
return
}
n := &g.nodes[owner]
n.owns = append(n.owns, owned)
}
func (g *graph) addUse(by, used NodeID) {
e := edge{by, used, edgeKindUse}
if !g.addEdge(e) {
return
}
nBy := &g.nodes[by]
nBy.uses = append(nBy.uses, used)
}
func (g *graph) see(obj, owner types.Object) {
if obj == nil {
panic("saw nil object")
}
if g.opts.ExportedIsUsed && obj.Pkg() != g.pkg || obj.Pkg() == nil {
return
}
nObj := g.node(obj)
if owner != nil {
nOwner := g.node(owner)
g.addOwned(nOwner, nObj)
}
}
func isIrrelevant(obj types.Object) bool {
switch obj.(type) {
case *types.PkgName:
return true
default:
return false
}
}
func (g *graph) use(used, by types.Object) {
if g.opts.ExportedIsUsed {
if used.Pkg() != g.pkg || used.Pkg() == nil {
return
}
if by != nil && by.Pkg() != g.pkg {
return
}
}
if isIrrelevant(used) {
return
}
nUsed := g.node(used)
nBy := g.node(by)
g.addUse(nBy, nUsed)
}
func (g *graph) entry() {
for _, f := range g.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 {
obj := g.pkg.Scope().Lookup(fields[1])
if obj == nil {
continue
}
g.use(obj, nil)
}
}
}
}
}
for _, f := range g.files {
for _, decl := range f.Decls {
g.decl(decl, nil)
}
}
if g.opts.GeneratedIsUsed {
// OPT(dh): depending on the options used, we do not need to track all objects. For example, if local variables
// are always used, then it is enough to use their surrounding function.
for obj := range g.objects {
path := g.fset.PositionFor(obj.Pos(), false).Filename
if _, ok := g.generated[path]; ok {
g.use(obj, nil)
}
}
}
// We use a normal map instead of a typeutil.Map because we deduplicate
// these on a best effort basis, as an optimization.
allInterfaces := make(map[*types.Interface]struct{})
for _, typ := range g.interfaceTypes {
allInterfaces[typ] = struct{}{}
}
for _, ins := range g.info.Instances {
if typ, ok := ins.Type.(*types.Named); ok && typ.Obj().Pkg() == g.pkg {
if iface, ok := typ.Underlying().(*types.Interface); ok {
allInterfaces[iface] = struct{}{}
}
}
}
processMethodSet := func(named *types.TypeName, ms *types.MethodSet) {
if g.opts.ExportedIsUsed {
for i := 0; i < ms.Len(); i++ {
m := ms.At(i)
if token.IsExported(m.Obj().Name()) {
// (2.1) named types use exported methods
// (6.4) structs use embedded fields that have exported methods
//
// By reading the selection, we read all embedded fields that are part of the path
g.readSelection(m, named)
}
}
}
if _, ok := named.Type().Underlying().(*types.Interface); !ok {
// (8.0) handle interfaces
//
// We don't care about interfaces implementing interfaces; all their methods are already used, anyway
for iface := range allInterfaces {
if sels, ok := implements(named.Type(), iface, ms); ok {
for _, sel := range sels {
// (8.2) any concrete type implements all known interfaces
// (6.3) structs use embedded fields that help implement interfaces
g.readSelection(sel, named)
}
}
}
}
}
for _, named := range g.namedTypes {
// OPT(dh): do we already have the method set available?
processMethodSet(named, types.NewMethodSet(named.Type()))
processMethodSet(named, types.NewMethodSet(types.NewPointer(named.Type())))
}
type ignoredKey struct {
file string
line int
}
ignores := map[ignoredKey]struct{}{}
for _, dir := range g.directives {
if dir.Command != "ignore" && dir.Command != "file-ignore" {
continue
}
if len(dir.Arguments) == 0 {
continue
}
for _, check := range strings.Split(dir.Arguments[0], ",") {
if check == "U1000" {
pos := g.fset.PositionFor(dir.Node.Pos(), false)
var key ignoredKey
switch dir.Command {
case "ignore":
key = ignoredKey{
pos.Filename,
pos.Line,
}
case "file-ignore":
key = ignoredKey{
pos.Filename,
-1,
}
}
ignores[key] = struct{}{}
break
}
}
}
if len(ignores) > 0 {
// all objects annotated with a //lint:ignore U1000 are considered used
for obj := range g.objects {
pos := g.fset.PositionFor(obj.Pos(), false)
key1 := ignoredKey{
pos.Filename,
pos.Line,
}
key2 := ignoredKey{
pos.Filename,
-1,
}
_, ok := ignores[key1]
if !ok {
_, ok = ignores[key2]
}
if ok {
g.use(obj, nil)
// use methods and fields of ignored types
if obj, ok := obj.(*types.TypeName); ok {
if obj.IsAlias() {
if typ, ok := types.Unalias(obj.Type()).(*types.Named); ok && (g.opts.ExportedIsUsed && typ.Obj().Pkg() != obj.Pkg() || typ.Obj().Pkg() == nil) {
// This is an alias of a named type in another package.
// Don't walk its fields or methods; we don't have to.
//
// For aliases to types in the same package, we do want to ignore the fields and methods,
// because ignoring the alias should ignore the aliased type.
continue
}
}
if typ, ok := types.Unalias(obj.Type()).(*types.Named); ok {
for i := 0; i < typ.NumMethods(); i++ {
g.use(typ.Method(i), nil)
}
}
if typ, ok := obj.Type().Underlying().(*types.Struct); ok {
for i := 0; i < typ.NumFields(); i++ {
g.use(typ.Field(i), nil)
}
}
}
}
}
}
}
func isOfType[T any](x any) bool {
_, ok := x.(T)
return ok
}
func (g *graph) read(node ast.Node, by types.Object) {
if node == nil {
return
}
switch node := node.(type) {
case *ast.Ident:
// Among many other things, this handles
// (7.1) field accesses use fields
obj := g.info.ObjectOf(node)
g.use(obj, by)
case *ast.BasicLit:
// Nothing to do
case *ast.SliceExpr:
g.read(node.X, by)
g.read(node.Low, by)
g.read(node.High, by)
g.read(node.Max, by)
case *ast.UnaryExpr:
g.read(node.X, by)
case *ast.ParenExpr:
g.read(node.X, by)
case *ast.ArrayType:
g.read(node.Len, by)
g.read(node.Elt, by)
case *ast.SelectorExpr:
g.readSelectorExpr(node, by)
case *ast.IndexExpr:
// Among many other things, this handles
// (2.6) named types use all their type arguments
g.read(node.X, by)
g.read(node.Index, by)
case *ast.IndexListExpr:
// Among many other things, this handles
// (2.6) named types use all their type arguments
g.read(node.X, by)
for _, index := range node.Indices {
g.read(index, by)
}
case *ast.BinaryExpr:
g.read(node.X, by)
g.read(node.Y, by)
case *ast.CompositeLit:
g.read(node.Type, by)
// We get the type of the node itself, not of node.Type, to handle nested composite literals of the kind
// T{{...}}
typ, isStruct := typeutil.CoreType(g.info.TypeOf(node)).(*types.Struct)
if isStruct {
unkeyed := len(node.Elts) != 0 && !isOfType[*ast.KeyValueExpr](node.Elts[0])
if g.opts.FieldWritesAreUses && unkeyed {
// Untagged struct literal that specifies all fields. We have to manually use the fields in the type,
// because the unkeyd literal doesn't contain any nodes referring to the fields.
for i := 0; i < typ.NumFields(); i++ {
g.use(typ.Field(i), by)
}
}
if g.opts.FieldWritesAreUses || unkeyed {
for _, elt := range node.Elts {
g.read(elt, by)
}
} else {
for _, elt := range node.Elts {
kv := elt.(*ast.KeyValueExpr)
g.write(kv.Key, by)
g.read(kv.Value, by)
}
}
} else {
for _, elt := range node.Elts {
g.read(elt, by)
}
}
case *ast.KeyValueExpr:
g.read(node.Key, by)
g.read(node.Value, by)
case *ast.StarExpr:
g.read(node.X, by)
case *ast.MapType:
g.read(node.Key, by)
g.read(node.Value, by)
case *ast.FuncLit:
g.read(node.Type, by)
// See graph.decl's handling of ast.FuncDecl for why this bit of code is necessary.
fn := g.info.TypeOf(node).(*types.Signature)
for params, i := fn.Params(), 0; i < params.Len(); i++ {
g.see(params.At(i), by)
if params.At(i).Name() == "" {
g.use(params.At(i), by)
}
}
g.block(node.Body, by)
case *ast.FuncType:
m := map[*types.Var]struct{}{}
if !g.opts.ParametersAreUsed {
m = map[*types.Var]struct{}{}
// seeScope marks all local variables in the scope as used, but we don't want to unconditionally use
// parameters, as this is controlled by Options.ParametersAreUsed. Pass seeScope a list of variables it
// should skip.
for _, f := range node.Params.List {
for _, name := range f.Names {
m[g.info.ObjectOf(name).(*types.Var)] = struct{}{}
}
}
}
g.seeScope(node, by, m)
// (4.1) functions use all their arguments, return parameters and receivers
// (12.1) type parameters use their constraint type
g.read(node.TypeParams, by)
if g.opts.ParametersAreUsed {
g.read(node.Params, by)
}
g.read(node.Results, by)
case *ast.FieldList:
if node == nil {
return
}
// This branch is only hit for field lists enclosed by parentheses or square brackets, i.e. parameters. Fields
// (for structs) and method lists (for interfaces) are handled elsewhere.
for _, field := range node.List {
if len(field.Names) == 0 {
g.read(field.Type, by)
} else {
for _, name := range field.Names {
// OPT(dh): instead of by -> name -> type, we could just emit by -> type. We don't care about the
// (un)usedness of parameters of any kind.
obj := g.info.ObjectOf(name)
g.use(obj, by)
g.read(field.Type, obj)
}
}
}
case *ast.ChanType:
g.read(node.Value, by)
case *ast.StructType:
// This is only used for anonymous struct types, not named ones.
for _, field := range node.Fields.List {
if len(field.Names) == 0 {
// embedded field
f := g.embeddedField(field.Type, by)
g.use(f, by)
} else {
for _, name := range field.Names {
// (11.1) anonymous struct types use all their fields
// OPT(dh): instead of by -> name -> type, we could just emit by -> type. If the type is used, then the fields are used.
obj := g.info.ObjectOf(name)
g.see(obj, by)
g.use(obj, by)
g.read(field.Type, g.info.ObjectOf(name))
}
}
}
case *ast.TypeAssertExpr:
g.read(node.X, by)
g.read(node.Type, by)
case *ast.InterfaceType:
if len(node.Methods.List) != 0 {
g.interfaceTypes = append(g.interfaceTypes, g.info.TypeOf(node).(*types.Interface))
}
for _, meth := range node.Methods.List {
switch len(meth.Names) {
case 0:
// Embedded type or type union
// (8.4) all embedded interfaces are marked as used
// (this also covers type sets)
g.read(meth.Type, by)
case 1:
// Method
// (8.3) all interface methods are marked as used
obj := g.info.ObjectOf(meth.Names[0])
g.see(obj, by)
g.use(obj, by)
g.read(meth.Type, obj)
default:
panic(fmt.Sprintf("unexpected number of names: %d", len(meth.Names)))
}
}
case *ast.Ellipsis:
g.read(node.Elt, by)
case *ast.CallExpr:
g.read(node.Fun, by)
for _, arg := range node.Args {
g.read(arg, by)
}
// Handle conversiosn
conv := node
if len(conv.Args) != 1 || conv.Ellipsis.IsValid() {
return
}
dst := g.info.TypeOf(conv.Fun)
src := g.info.TypeOf(conv.Args[0])
// XXX use DereferenceR instead
// XXX guard against infinite recursion in DereferenceR
tSrc := typeutil.CoreType(typeutil.Dereference(src))
tDst := typeutil.CoreType(typeutil.Dereference(dst))
stSrc, okSrc := tSrc.(*types.Struct)
stDst, okDst := tDst.(*types.Struct)
if okDst && okSrc {
// Converting between two structs. The fields are
// relevant for the conversion, but only if the
// fields are also used outside of the conversion.
// Mark fields as used by each other.
assert(stDst.NumFields() == stSrc.NumFields())
for i := 0; i < stDst.NumFields(); i++ {
// (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.
g.use(stDst.Field(i), stSrc.Field(i))
g.use(stSrc.Field(i), stDst.Field(i))
}
} else if okSrc && tDst == types.Typ[types.UnsafePointer] {
// (5.2) when converting to or from unsafe.Pointer, mark all fields as used.
g.useAllFieldsRecursively(stSrc, by)
} else if okDst && tSrc == types.Typ[types.UnsafePointer] {
// (5.2) when converting to or from unsafe.Pointer, mark all fields as used.
g.useAllFieldsRecursively(stDst, by)
}
default:
lint.ExhaustiveTypeSwitch(node)
}
}
func (g *graph) useAllFieldsRecursively(typ types.Type, by types.Object) {
switch typ := typ.Underlying().(type) {
case *types.Struct:
for i := 0; i < typ.NumFields(); i++ {
field := typ.Field(i)
g.use(field, by)
g.useAllFieldsRecursively(field.Type(), by)
}
case *types.Array:
g.useAllFieldsRecursively(typ.Elem(), by)
default:
return
}
}
func (g *graph) write(node ast.Node, by types.Object) {
if node == nil {
return
}
switch node := node.(type) {
case *ast.Ident:
obj := g.info.ObjectOf(node)
if obj == nil {
// This can happen for `switch x := v.(type)`, where that x doesn't have an object
return
}
// (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
path := g.fset.File(obj.Pos()).Name()
if strings.HasSuffix(path, "_test.go") {
if isGlobal(obj) {
g.use(obj, by)
}
}
case *ast.IndexExpr:
g.read(node.X, by)
g.read(node.Index, by)
case *ast.SelectorExpr:
if g.opts.FieldWritesAreUses {
// Writing to a field constitutes a use. See https://staticcheck.dev/issues/288 for some discussion on that.
//
// This code can also get triggered by qualified package variables, in which case it doesn't matter what we do,
// because the object is in another package.
//
// FIXME(dh): ^ isn't true if we track usedness of exported identifiers
g.readSelectorExpr(node, by)
} else {
g.read(node.X, by)
g.write(node.Sel, by)
}
case *ast.StarExpr:
g.read(node.X, by)
case *ast.ParenExpr:
g.write(node.X, by)
default:
lint.ExhaustiveTypeSwitch(node)
}
}
// readSelectorExpr reads all elements of a selector expression, including implicit fields.
func (g *graph) readSelectorExpr(sel *ast.SelectorExpr, by types.Object) {