1
0
mirror of https://github.com/golang/go synced 2024-09-30 22:48:32 -06:00
go/cmd/vet/assign.go
Rob Pike 95c9b7bad1 go.tools/cmd/vet: replace warnings by errors
Over time, a number of modules were added that used Warn instead of Bad
to report problems with the code, but the documentation states that
if there is a problem, the exit code must be 1, not 0. Warn does not set the
exit code and should be used only for internal errors and messages
triggered by the -v flag.

There's nothing substantive here except calling the other function in a few
places.

Fixes golang/go#7017.

LGTM=crawshaw
R=golang-codereviews, crawshaw
CC=golang-codereviews
https://golang.org/cl/71860044
2014-03-07 15:31:28 +11:00

45 lines
1.1 KiB
Go

// 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"
)
// 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 (f *File) checkAssignStmt(stmt *ast.AssignStmt) {
if !vet("assign") {
return
}
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 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)
}
}
}