Debian Codegraph @

go/analysis/passes/unusedwrite/testdata/src/a/unusedwrite.go

raw symbols SCIP
1 package a
2
3 type T1 struct{ x int }
4
5 type T2 struct {
6 x int
7 y int
8 }
9
10 type T3 struct{ y *T1 }
11
12 func BadWrites() {
13 // Test struct field writes.
14 var s1 T1
15 s1.x = 10 // want "unused write to field x"
16
17 // Test array writes.
18 var s2 [10]int
19 s2[1] = 10 // want "unused write to array index 1:int"
20
21 // Test range variables of struct type.
22 s3 := []T1{T1{x: 100}}
23 for i, v := range s3 {
24 v.x = i // want "unused write to field x"
25 }
26
27 // Test the case where a different field is read after the write.
28 s4 := []T2{T2{x: 1, y: 2}}
29 for i, v := range s4 {
30 v.x = i // want "unused write to field x"
31 _ = v.y
32 }
33
34 // The analyzer can handle only simple control flow.
35 type T struct{ x, y int }
36 t := new(T)
37 if true {
38 t = new(T)
39 } // causes t below to become phi(alloc, alloc), not a simple alloc
40 t.x = 1 // false negative
41 print(t.y)
42 }
43
44 func (t T1) BadValueReceiverWrite(v T2) {
45 t.x = 10 // want "unused write to field x"
46 v.y = 20 // want "unused write to field y"
47 }
48
49 func GoodWrites(m map[int]int) {
50 // A map is copied by reference such that a write will affect the original map.
51 m[1] = 10
52
53 // Test struct field writes.
54 var s1 T1
55 s1.x = 10
56 print(s1.x)
57
58 // Test array writes.
59 var s2 [10]int
60 s2[1] = 10
61 // Current the checker doesn't distinguish index 1 and index 2.
62 _ = s2[2]
63
64 // Test range variables of struct type.
65 s3 := []T1{T1{x: 100}}
66 for i, v := range s3 { // v is a copy
67 v.x = i
68 _ = v.x // still a usage
69 }
70
71 // Test an object with multiple fields.
72 o := &T2{x: 10, y: 20}
73 print(o)
74
75 // Test an object of embedded struct/pointer type.
76 t1 := &T1{x: 10}
77 t2 := &T3{y: t1}
78 print(t2)
79 }
80
81 func (t *T1) GoodPointerReceiverWrite(v *T2) {
82 t.x = 10
83 v.y = 20
84 }