Skip to content

Commit

Permalink
fix(type assert): add more check for type assert
Browse files Browse the repository at this point in the history
  • Loading branch information
meteorgan committed Apr 17, 2024
1 parent b65821b commit b411d9d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
37 changes: 32 additions & 5 deletions errcheck/errcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -586,18 +586,29 @@ func (v *visitor) Visit(node ast.Node) ast.Visitor {
for _, name := range vspec.Names {
lhs = append(lhs, ast.Expr(name))
}
v.checkAssignment(lhs, vspec.Values)
followed := v.checkAssignment(lhs, vspec.Values)
if !followed {
return nil
}
}

case *ast.AssignStmt:
v.checkAssignment(stmt.Lhs, stmt.Rhs)
followed := v.checkAssignment(stmt.Lhs, stmt.Rhs)
if !followed {
return nil
}

case *ast.TypeAssertExpr:
v.checkAssertExpr(stmt)
return nil

default:
}
return v
}

func (v *visitor) checkAssignment(lhs, rhs []ast.Expr) {
func (v *visitor) checkAssignment(lhs, rhs []ast.Expr) (followed bool) {
followed = true
if len(rhs) == 1 {
// single value on rhs; check against lhs identifiers
if call, ok := rhs[0].(*ast.CallExpr); ok {
Expand All @@ -619,11 +630,11 @@ func (v *visitor) checkAssignment(lhs, rhs []ast.Expr) {
}
} else if assert, ok := rhs[0].(*ast.TypeAssertExpr); ok {
if !v.asserts {
return
return false
}
if assert.Type == nil {
// type switch
return
return false
}
if len(lhs) < 2 {
// assertion result not read
Expand All @@ -632,6 +643,7 @@ func (v *visitor) checkAssignment(lhs, rhs []ast.Expr) {
// assertion result ignored
v.addErrorAtPosition(id.NamePos, nil)
}
return false
}
} else {
// multiple value on rhs; in this case a call can't return
Expand Down Expand Up @@ -661,6 +673,21 @@ func (v *visitor) checkAssignment(lhs, rhs []ast.Expr) {
}
}
}

return
}

func (v *visitor) checkAssertExpr(expr *ast.TypeAssertExpr) bool {
if !v.asserts {
return false
}
if expr.Type == nil {
// type switch
return false
}
v.addErrorAtPosition(expr.Pos(), nil)

return false
}

func isErrorType(t types.Type) bool {
Expand Down
17 changes: 17 additions & 0 deletions errcheck/testdata/src/assert/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,21 @@ package assert
func main() {
var i interface{}
_ = i.(string) // want "unchecked error"

handleInterface(i.(string)) // want "unchecked error"

if i.(string) == "hello" { // want "unchecked error"
//
}

switch i.(type) {
case string:
case int:
_ = i.(int) // want "unchecked error"
case nil:
}
}

func handleInterface(i interface{}) string {
return i.(string) // want "unchecked error"
}

0 comments on commit b411d9d

Please sign in to comment.