Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

extend nilValReturn checker #1025

Merged
merged 1 commit into from Feb 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 14 additions & 7 deletions checkers/nilValReturn_checker.go
Expand Up @@ -45,17 +45,24 @@ func (c *nilValReturnChecker) VisitStmt(stmt ast.Stmt) {
return
}
ret, ok := ifStmt.Body.List[0].(*ast.ReturnStmt)
if !ok || len(ret.Results) != 1 {
if !ok {
return
}
expr, ok := ifStmt.Cond.(*ast.BinaryExpr)
cond := ok &&
expr.Op == token.EQL &&
if !ok {
return
}
xIsNil := expr.Op == token.EQL &&
typep.SideEffectFree(c.ctx.TypesInfo, expr.X) &&
qualifiedName(expr.Y) == "nil" &&
astequal.Expr(expr.X, ret.Results[0])
if cond {
c.warn(ret, expr.X)
qualifiedName(expr.Y) == "nil"
if !xIsNil {
return
}
for _, res := range ret.Results {
if astequal.Expr(expr.X, res) {
c.warn(ret, expr.X)
break
}
}
}

Expand Down
21 changes: 21 additions & 0 deletions checkers/testdata/nilValReturn/negative_tests.go
Expand Up @@ -22,6 +22,13 @@ func explicitNil() {
return nil
}

_ = func(o *object, err error) (*object, error) {
if err == nil {
return o, nil
}
return nil, err
}

_ = func(pointers [][][]map[string]*int) *int {
if pointers[0][1][2]["ptr"] == nil {
return nil
Expand Down Expand Up @@ -55,6 +62,20 @@ func explicitNotEqual() {
return nil
}

_ = func(o *object, a *object) *object {
if o != nil {
return o
}
return a
}

_ = func(o *object, err error) (*object, error) {
if err != nil {
return nil, err
}
return o, nil
}

_ = func(pointers [][][]map[string]*int) *int {
if pointers[0][1][2]["ptr"] != nil {
return pointers[0][1][2]["ptr"]
Expand Down
16 changes: 16 additions & 0 deletions checkers/testdata/nilValReturn/positive_tests.go
Expand Up @@ -29,6 +29,22 @@ func suspiciousReturns() {
return nil
}

_ = func(o *object, err error) (*object, error) {
if err == nil {
/*! returned expr is always nil; replace err with nil */
return nil, err
}
return o, nil
}

_ = func(o *object, a *object) *object {
if o == nil {
/*! returned expr is always nil; replace o with nil */
return o
}
return a
}

_ = func(pointers [][][]map[string]*int) *int {
if pointers[0][1][2]["ptr"] == nil {
/*! returned expr is always nil; replace pointers[0][1][2]["ptr"] with nil */
Expand Down