| 1 |
// Copyright 2020 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// This file contains tests for the useless-assignment checker. |
| 6 |
|
| 7 |
package testdata |
| 8 |
|
| 9 |
import "math/rand" |
| 10 |
|
| 11 |
type ST struct { |
| 12 |
x int |
| 13 |
l []int |
| 14 |
} |
| 15 |
|
| 16 |
func (s *ST) SetX(x int, ch chan int) { |
| 17 |
// Accidental self-assignment; it should be "s.x = x" |
| 18 |
// Another mistake |
| 19 |
|
| 20 |
// Report self-assignment to x but preserve the actual assignment to s.x |
| 21 |
s.x = 1 // want "self-assignment of x" |
| 22 |
s.x = 1 // want "self-assignment of x" |
| 23 |
|
| 24 |
// Delete multiple self-assignment |
| 25 |
s.l[0] = 1 // want "self-assignment of x, s.x" |
| 26 |
s.l[0] = 1 // want "self-assignment of x, s.x" |
| 27 |
s.l[0] = 1 // want "self-assignment of x, s.x" |
| 28 |
s.l[0], s.l[1] = 1, 1 // want "self-assignment of x, s.x" |
| 29 |
s.l[0], s.l[1] = 1, 1 // want "self-assignment of x, s.x" |
| 30 |
|
| 31 |
// Bail on any potential side effects to avoid false positives |
| 32 |
s.l[num()] = s.l[num()] |
| 33 |
rng := rand.New(rand.NewSource(0)) |
| 34 |
s.l[rng.Intn(len(s.l))] = s.l[rng.Intn(len(s.l))] |
| 35 |
s.l[<-ch] = s.l[<-ch] |
| 36 |
} |
| 37 |
|
| 38 |
func num() int { return 2 } |
| 39 |
|
| 40 |
func Index() { |
| 41 |
s := []int{1} |
| 42 |
|
| 43 |
var a [5]int |
| 44 |
|
| 45 |
pa := &[2]int{1, 2} |
| 46 |
|
| 47 |
var pss *struct { // report self assignment despite nil dereference |
| 48 |
s []int |
| 49 |
} |
| 50 |
|
| 51 |
m := map[int]string{1: "a"} |
| 52 |
m[0] = m[0] // bail on map self-assignments due to side effects |
| 53 |
m[1] = m[1] // not modeling what elements must be in the map |
| 54 |
(m[2]) = (m[2]) // even with parens |
| 55 |
type Map map[string]bool |
| 56 |
named := make(Map) |
| 57 |
named["s"] = named["s"] // even on named maps. |
| 58 |
var psm *struct { |
| 59 |
m map[string]int |
| 60 |
} |
| 61 |
psm.m["key"] = psm.m["key"] // handles dereferences |
| 62 |
} |