-
Notifications
You must be signed in to change notification settings - Fork 5
/
outparamcheck.go
236 lines (216 loc) · 5.72 KB
/
outparamcheck.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright 2013 Kamil Kisiel
// Modifications copyright 2016 Palantir Technologies, Inc.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
package outparamcheck
import (
"encoding/json"
"fmt"
"go/ast"
"go/build"
"go/token"
"go/types"
"io/ioutil"
"sort"
"strings"
"sync"
"github.com/kisielk/gotool"
"github.com/pkg/errors"
"golang.org/x/tools/go/loader"
"github.com/palantir/outparamcheck/exprs"
)
func Run(cfgParam string, paths []string) error {
cfg := Config{}
if cfgParam != "" {
var usrCfg Config
var err error
if strings.HasPrefix(cfgParam, "@") {
usrCfg, err = loadCfgFromPath(cfgParam[1:])
} else {
usrCfg, err = loadCfg(cfgParam)
}
if err != nil {
return errors.Wrapf(err, "Failed to load configuration from parameter %s", cfgParam)
}
for key, val := range usrCfg {
cfg[key] = val
}
}
// add default config (values for default will override any user-supplied config for the same keys)
for key, val := range defaultCfg {
cfg[key] = val
}
prog, err := load(paths)
if err != nil {
return errors.WithStack(err)
}
errs := run(prog, cfg)
if len(errs) > 0 {
reportErrors(errs)
return fmt.Errorf("%s; the parameters listed above require the use of '&', for example f(&x) instead of f(x)",
plural(len(errs), "error", "errors"))
}
return nil
}
func run(prog *loader.Program, cfg Config) []OutParamError {
var errs []OutParamError
var mut sync.Mutex // guards errs
var wg sync.WaitGroup
for _, pkgInfo := range prog.InitialPackages() {
if pkgInfo.Pkg.Path() == "unsafe" { // not a real package
continue
}
wg.Add(1)
go func(pkgInfo *loader.PackageInfo) {
defer wg.Done()
v := &visitor{
prog: prog,
pkg: pkgInfo,
lines: map[string][]string{},
errors: []OutParamError{},
cfg: cfg,
}
for _, astFile := range pkgInfo.Files {
exprs.Walk(v, astFile)
}
mut.Lock()
defer mut.Unlock()
errs = append(errs, v.errors...)
}(pkgInfo)
}
wg.Wait()
return errs
}
func loadCfgFromPath(cfgPath string) (Config, error) {
cfgBytes, err := ioutil.ReadFile(cfgPath)
if err != nil {
return Config{}, errors.Wrapf(err, "failed to read file %s", cfgPath)
}
return loadCfg(string(cfgBytes))
}
func loadCfg(cfgJSON string) (Config, error) {
var cfg Config
if err := json.Unmarshal([]byte(cfgJSON), &cfg); err != nil {
return Config{}, errors.Wrapf(err, "failed to unmarshal json %s", cfgJSON)
}
return cfg, nil
}
func load(paths []string) (*loader.Program, error) {
loadcfg := loader.Config{
Build: &build.Default,
}
includeTests := true
rest, err := loadcfg.FromArgs(gotool.ImportPaths(paths), includeTests)
if err != nil {
return nil, errors.Wrapf(err, "could not parse arguments")
}
if len(rest) > 0 {
return nil, errors.Errorf("unhandled extra arguments: %v", rest)
}
prog, err := loadcfg.Load()
if err != nil {
return nil, errors.WithStack(err)
}
return prog, nil
}
type visitor struct {
prog *loader.Program
pkg *loader.PackageInfo
lines map[string][]string
errors []OutParamError
cfg Config
}
func (v *visitor) Visit(expr ast.Expr) {
call, ok := expr.(*ast.CallExpr)
if !ok {
return
}
key, method, ok := v.keyAndName(call)
if !ok {
return
}
for name, outs := range v.cfg {
// Suffix-matching so they also apply to vendored packages
if strings.HasSuffix(key, name) {
for _, i := range outs {
arg := call.Args[i]
if !isAddr(arg) {
v.errorAt(arg.Pos(), method, i)
}
}
}
}
}
func (v *visitor) keyAndName(call *ast.CallExpr) (key string, name string, ok bool) {
switch target := call.Fun.(type) {
case *ast.Ident:
// Function calls without a selector; this includes calls within the
// same package as well as calls into dot-imported packages
if def, ok := v.pkg.Uses[target]; ok && def.Pkg() != nil {
return fmt.Sprintf("%v.%v", def.Pkg().Path(), target.Name), target.Name, true
}
case *ast.SelectorExpr:
// Function calls into other packages
if recv, ok := target.X.(*ast.Ident); ok {
if pkg, ok := v.pkg.Uses[recv].(*types.PkgName); ok {
return fmt.Sprintf("%v.%v", pkg.Imported().Path(), target.Sel.Name), target.Sel.Name, true
}
}
// Method calls
if typ, ok := v.pkg.Types[target.X]; ok {
return fmt.Sprintf("%v.%v", typ.Type.String(), target.Sel.Name), target.Sel.Name, true
}
}
return "", "", false
}
func (v *visitor) errorAt(pos token.Pos, method string, argument int) {
position := v.prog.Fset.Position(pos)
lines, ok := v.lines[position.Filename]
if !ok {
contents, err := ioutil.ReadFile(position.Filename)
if err != nil {
contents = nil
}
lines = strings.Split(string(contents), "\n")
v.lines[position.Filename] = lines
}
var line string
if position.Line-1 < len(lines) {
line = strings.TrimSpace(lines[position.Line-1])
}
v.errors = append(v.errors, OutParamError{position, line, method, argument})
}
func isAddr(expr ast.Expr) bool {
switch expr := expr.(type) {
case *ast.UnaryExpr:
// The expected usage for output parameters, which is &x
return expr.Op == token.AND
case *ast.StarExpr:
// Allow *&x as an explicit way to signal that no & is intended
child, ok := expr.X.(*ast.UnaryExpr)
return ok && child.Op == token.AND
case *ast.Ident:
if expr.Obj != nil && expr.Obj.Decl != nil {
switch child := expr.Obj.Decl.(type) {
case *ast.AssignStmt:
return isAddr(child.Rhs[0])
}
}
// Allow passing a pointer or literal nil
return expr.Name == "nil"
default:
return false
}
}
func reportErrors(errs []OutParamError) {
sort.Sort(byLocation(errs))
for _, err := range errs {
fmt.Println(err)
}
}
func plural(count int, singular, plural string) string {
if count == 1 {
return fmt.Sprintf("%d %s", count, singular)
}
return fmt.Sprintf("%d %s", count, plural)
}