-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewallocs.go
69 lines (53 loc) · 1.18 KB
/
newallocs.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package consistent
import (
"go/ast"
"go/token"
"go/types"
"github.com/go-toolsmith/astcast"
"golang.org/x/tools/go/analysis"
)
const (
newAllocsLiteral = "literal"
newAllocsNew = "new"
)
var newAllocsFlagAllowedValues = []string{flagIgnore, newAllocsLiteral, newAllocsNew}
func checkNewAllocLit(pass *analysis.Pass, expr *ast.UnaryExpr, mode string) {
if mode != newAllocsNew {
return
}
if expr.Op != token.AND {
return
}
comp := astcast.ToCompositeLit(expr.X)
if !identOrSelector(comp.Type) {
return
}
if len(comp.Elts) != 0 {
return
}
reportf(pass, expr.Pos(), "call new instead of using zero-value literal")
}
func checkNewAllocNew(pass *analysis.Pass, call *ast.CallExpr, mode string) {
if mode != newAllocsLiteral {
return
}
if astcast.ToIdent(call.Fun).Name != "new" {
return
}
if len(call.Args) != 1 {
return
}
typ := pass.TypesInfo.TypeOf(call.Args[0])
if _, ok := typ.Underlying().(*types.Interface); ok {
return
}
reportf(pass, call.Pos(), "use zero-value literal instead of calling new")
}
func identOrSelector(e ast.Expr) bool {
switch e.(type) {
case *ast.Ident, *ast.SelectorExpr:
return true
default:
return false
}
}