...
Run Format

Source file src/cmd/vet/atomic.go

Documentation: cmd/vet

     1  // Copyright 2013 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  package main
     6  
     7  import (
     8  	"go/ast"
     9  	"go/token"
    10  	"go/types"
    11  )
    12  
    13  func init() {
    14  	register("atomic",
    15  		"check for common mistaken usages of the sync/atomic package",
    16  		checkAtomicAssignment,
    17  		assignStmt)
    18  }
    19  
    20  // checkAtomicAssignment walks the assignment statement checking for common
    21  // mistaken usage of atomic package, such as: x = atomic.AddUint64(&x, 1)
    22  func checkAtomicAssignment(f *File, node ast.Node) {
    23  	n := node.(*ast.AssignStmt)
    24  	if len(n.Lhs) != len(n.Rhs) {
    25  		return
    26  	}
    27  	if len(n.Lhs) == 1 && n.Tok == token.DEFINE {
    28  		return
    29  	}
    30  
    31  	for i, right := range n.Rhs {
    32  		call, ok := right.(*ast.CallExpr)
    33  		if !ok {
    34  			continue
    35  		}
    36  		sel, ok := call.Fun.(*ast.SelectorExpr)
    37  		if !ok {
    38  			continue
    39  		}
    40  		pkgIdent, _ := sel.X.(*ast.Ident)
    41  		pkgName, ok := f.pkg.uses[pkgIdent].(*types.PkgName)
    42  		if !ok || pkgName.Imported().Path() != "sync/atomic" {
    43  			continue
    44  		}
    45  
    46  		switch sel.Sel.Name {
    47  		case "AddInt32", "AddInt64", "AddUint32", "AddUint64", "AddUintptr":
    48  			f.checkAtomicAddAssignment(n.Lhs[i], call)
    49  		}
    50  	}
    51  }
    52  
    53  // checkAtomicAddAssignment walks the atomic.Add* method calls checking for assigning the return value
    54  // to the same variable being used in the operation
    55  func (f *File) checkAtomicAddAssignment(left ast.Expr, call *ast.CallExpr) {
    56  	if len(call.Args) != 2 {
    57  		return
    58  	}
    59  	arg := call.Args[0]
    60  	broken := false
    61  
    62  	if uarg, ok := arg.(*ast.UnaryExpr); ok && uarg.Op == token.AND {
    63  		broken = f.gofmt(left) == f.gofmt(uarg.X)
    64  	} else if star, ok := left.(*ast.StarExpr); ok {
    65  		broken = f.gofmt(star.X) == f.gofmt(arg)
    66  	}
    67  
    68  	if broken {
    69  		f.Bad(left.Pos(), "direct assignment to atomic value")
    70  	}
    71  }
    72  

View as plain text