Skip to content

Commit

Permalink
Fix for #18
Browse files Browse the repository at this point in the history
  • Loading branch information
tenntenn committed Feb 13, 2025
1 parent 7ec5400 commit 8e53413
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
14 changes: 14 additions & 0 deletions forcetypeassert.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ func checkAssignStmt(pass *analysis.Pass, result *Panicable, n *ast.AssignStmt)
}

switch {

// if right hand is a call expression, assign statement can't assert boolean value which describes type assertion is succeeded
case len(n.Rhs) == 1 && isCallExpr(n.Rhs[0]):
pass.Reportf(n.Pos(), "right hand must be only type assertion")
return false
// if right hand has 2 or more values, assign statement can't assert boolean value which describes type assertion is succeeded
case len(n.Rhs) > 1:
pass.Reportf(n.Pos(), "right hand must be only type assertion")
Expand All @@ -113,6 +118,10 @@ func checkValueSpec(pass *analysis.Pass, result *Panicable, n *ast.ValueSpec) bo
}

switch {
// if right hand is a call expression, assign statement can't assert boolean value which describes type assertion is succeeded
case len(n.Values) == 1 && isCallExpr(n.Values[0]):
pass.Reportf(n.Pos(), "right hand must be only type assertion")
return false
// if right hand has 2 or more values, assign statement can't assert boolean value which describes type assertion is succeeded
case len(n.Values) > 1:
pass.Reportf(n.Pos(), "right hand must be only type assertion")
Expand Down Expand Up @@ -148,3 +157,8 @@ func findTypeAssertion(exprs []ast.Expr) *ast.TypeAssertExpr {
}
return nil
}

func isCallExpr(expr ast.Expr) bool {
_, isCallExpr := expr.(*ast.CallExpr)
return isCallExpr
}
2 changes: 1 addition & 1 deletion forcetypeassert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func Test(t *testing.T) {
testdata := analysistest.TestData()
analysistest.Run(t, testdata, forcetypeassert.Analyzer, "a")
analysistest.Run(t, testdata, forcetypeassert.Analyzer, "a", "issue")
}

func TestResult(t *testing.T) {
Expand Down
12 changes: 12 additions & 0 deletions testdata/src/issue/issue18.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// https://github.com/gostaticanalysis/forcetypeassert/issues/18
package issue

type M struct{}

func (M) F() (bool, bool) { return true, true }

var _, ok = any(nil).(M).F() // want `right hand must be only type assertion`
func Test(x any) bool {
_, ok := x.(M).F() // want `right hand must be only type assertion`
return ok
}

0 comments on commit 8e53413

Please sign in to comment.