Skip to content

Commit 8e53413

Browse files
committed
Fix for #18
1 parent 7ec5400 commit 8e53413

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

forcetypeassert.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,11 @@ func checkAssignStmt(pass *analysis.Pass, result *Panicable, n *ast.AssignStmt)
9090
}
9191

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

115120
switch {
121+
// if right hand is a call expression, assign statement can't assert boolean value which describes type assertion is succeeded
122+
case len(n.Values) == 1 && isCallExpr(n.Values[0]):
123+
pass.Reportf(n.Pos(), "right hand must be only type assertion")
124+
return false
116125
// if right hand has 2 or more values, assign statement can't assert boolean value which describes type assertion is succeeded
117126
case len(n.Values) > 1:
118127
pass.Reportf(n.Pos(), "right hand must be only type assertion")
@@ -148,3 +157,8 @@ func findTypeAssertion(exprs []ast.Expr) *ast.TypeAssertExpr {
148157
}
149158
return nil
150159
}
160+
161+
func isCallExpr(expr ast.Expr) bool {
162+
_, isCallExpr := expr.(*ast.CallExpr)
163+
return isCallExpr
164+
}

forcetypeassert_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010

1111
func Test(t *testing.T) {
1212
testdata := analysistest.TestData()
13-
analysistest.Run(t, testdata, forcetypeassert.Analyzer, "a")
13+
analysistest.Run(t, testdata, forcetypeassert.Analyzer, "a", "issue")
1414
}
1515

1616
func TestResult(t *testing.T) {

testdata/src/issue/issue18.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// https://github.com/gostaticanalysis/forcetypeassert/issues/18
2+
package issue
3+
4+
type M struct{}
5+
6+
func (M) F() (bool, bool) { return true, true }
7+
8+
var _, ok = any(nil).(M).F() // want `right hand must be only type assertion`
9+
func Test(x any) bool {
10+
_, ok := x.(M).F() // want `right hand must be only type assertion`
11+
return ok
12+
}

0 commit comments

Comments
 (0)