summaryrefslogtreecommitdiff
path: root/libgo/go/cmd/vet/assign.go
blob: bfa5b3032938e22eb37dffa586c1b4699bf80152 (plain)
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
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
This file contains the code to check for useless assignments.
*/

package main

import (
	"go/ast"
	"go/token"
	"reflect"
)

func init() {
	register("assign",
		"check for useless assignments",
		checkAssignStmt,
		assignStmt)
}

// TODO: should also check for assignments to struct fields inside methods
// that are on T instead of *T.

// checkAssignStmt checks for assignments of the form "<expr> = <expr>".
// These are almost always useless, and even when they aren't they are usually a mistake.
func checkAssignStmt(f *File, node ast.Node) {
	stmt := node.(*ast.AssignStmt)
	if stmt.Tok != token.ASSIGN {
		return // ignore :=
	}
	if len(stmt.Lhs) != len(stmt.Rhs) {
		// If LHS and RHS have different cardinality, they can't be the same.
		return
	}
	for i, lhs := range stmt.Lhs {
		rhs := stmt.Rhs[i]
		if hasSideEffects(lhs) || hasSideEffects(rhs) {
			continue // expressions may not be equal
		}
		if reflect.TypeOf(lhs) != reflect.TypeOf(rhs) {
			continue // short-circuit the heavy-weight gofmt check
		}
		le := f.gofmt(lhs)
		re := f.gofmt(rhs)
		if le == re {
			f.Badf(stmt.Pos(), "self-assignment of %s to %s", re, le)
		}
	}
}