From afb84ff20c19f90603fffa2d6fc7ee107d75c6d4 Mon Sep 17 00:00:00 2001 From: Tommy Murphy Date: Sun, 6 Nov 2016 12:31:12 -0500 Subject: [PATCH] rand: use a MatchCallByPackage helper --- core/helpers.go | 6 +++--- rules/rand.go | 38 ++++---------------------------------- 2 files changed, 7 insertions(+), 37 deletions(-) diff --git a/core/helpers.go b/core/helpers.go index 81bd9e8..7573636 100644 --- a/core/helpers.go +++ b/core/helpers.go @@ -52,11 +52,11 @@ func MatchCall(n ast.Node, r *regexp.Regexp) *ast.CallExpr { // package and identifier name matches the passed in parameters. // // Usage: -// node, obj := MatchCall(n, ctx, "math/rand", "Read") +// node, obj := MatchCallByPackage(n, ctx, "math/rand", "Read") // -func MatchCallByObject(n ast.Node, c *Context, pkg, name string) (*ast.CallExpr, types.Object) { +func MatchCallByPackage(n ast.Node, c *Context, pkg, name string) (*ast.CallExpr, types.Object) { call, obj := GetCallObject(n, c) - if obj != nil && obj.Pkg().Path() == pkg && obj.Name() == name { + if obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == pkg && obj.Name() == name { return call, obj } return nil, nil diff --git a/rules/rand.go b/rules/rand.go index ad1d6ef..52469c7 100644 --- a/rules/rand.go +++ b/rules/rand.go @@ -16,50 +16,20 @@ package rules import ( "go/ast" - "go/types" - "regexp" gas "github.com/GoASTScanner/gas/core" ) type WeakRand struct { gas.MetaData - pattern *regexp.Regexp + funcName string packagePath string } -func matchFuncCall(n ast.Node, c *gas.Context) (types.Object, *ast.Ident) { - call, ok := n.(*ast.CallExpr) - if !ok { - return nil, nil - } - - sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok { - return nil, nil - } - - id, ok := sel.X.(*ast.Ident) - if !ok { - return nil, nil - } - - return c.Info.ObjectOf(id), sel.Sel -} - func (w *WeakRand) Match(n ast.Node, c *gas.Context) (*gas.Issue, error) { - o, f := matchFuncCall(n, c) + node, _ := gas.MatchCallByPackage(n, c, w.packagePath, w.funcName) - if o == nil || f == nil { - return nil, nil - } - - pkg, ok := o.(*types.PkgName) - if !ok { - return nil, nil - } - - if pkg.Imported().Path() == w.packagePath && w.pattern.MatchString(f.String()) { + if node != nil { return gas.NewIssue(c, n, w.What, w.Severity, w.Confidence), nil } @@ -68,7 +38,7 @@ func (w *WeakRand) Match(n ast.Node, c *gas.Context) (*gas.Issue, error) { func NewWeakRandCheck(conf map[string]interface{}) (r gas.Rule, n ast.Node) { r = &WeakRand{ - pattern: regexp.MustCompile(`^Read$`), + funcName: "Read", packagePath: "math/rand", MetaData: gas.MetaData{ Severity: gas.High,