@@ -2,6 +2,7 @@ package forcetypeassert
2
2
3
3
import (
4
4
"go/ast"
5
+ "go/types"
5
6
"reflect"
6
7
7
8
"golang.org/x/tools/go/analysis"
@@ -42,7 +43,9 @@ func (p *Panicable) At(i int) ast.Node {
42
43
43
44
const Doc = "forcetypeassert is finds type assertions which did forcely"
44
45
45
- func run (pass * analysis.Pass ) (interface {}, error ) {
46
+ var anyTyp = types .Universe .Lookup ("any" ).Type ()
47
+
48
+ func run (pass * analysis.Pass ) (any , error ) {
46
49
inspect , _ := pass .ResultOf [inspect .Analyzer ].(* inspector.Inspector )
47
50
result := & Panicable {m : make (map [ast.Node ]bool )}
48
51
@@ -62,7 +65,7 @@ func run(pass *analysis.Pass) (interface{}, error) {
62
65
case * ast.ValueSpec :
63
66
return checkValueSpec (pass , result , n )
64
67
case * ast.TypeAssertExpr :
65
- if n .Type != nil {
68
+ if n .Type != nil && ! isAny ( pass , n . Type ) {
66
69
result .m [n ] = true
67
70
result .nodes = append (result .nodes , n )
68
71
pass .Reportf (n .Pos (), "type assertion must be checked" )
@@ -76,6 +79,10 @@ func run(pass *analysis.Pass) (interface{}, error) {
76
79
return result , nil
77
80
}
78
81
82
+ func isAny (pass * analysis.Pass , expr ast.Expr ) bool {
83
+ return types .Identical (pass .TypesInfo .TypeOf (expr ), anyTyp )
84
+ }
85
+
79
86
func checkAssignStmt (pass * analysis.Pass , result * Panicable , n * ast.AssignStmt ) bool {
80
87
tae := findTypeAssertion (n .Rhs )
81
88
if tae == nil {
@@ -87,7 +94,7 @@ func checkAssignStmt(pass *analysis.Pass, result *Panicable, n *ast.AssignStmt)
87
94
case len (n .Rhs ) > 1 :
88
95
pass .Reportf (n .Pos (), "right hand must be only type assertion" )
89
96
return false
90
- case len (n .Lhs ) != 2 && tae .Type != nil :
97
+ case len (n .Lhs ) != 2 && tae .Type != nil && ! isAny ( pass , tae . Type ) :
91
98
result .m [n ] = true
92
99
result .nodes = append (result .nodes , n )
93
100
pass .Reportf (n .Pos (), "type assertion must be checked" )
@@ -110,7 +117,7 @@ func checkValueSpec(pass *analysis.Pass, result *Panicable, n *ast.ValueSpec) bo
110
117
case len (n .Values ) > 1 :
111
118
pass .Reportf (n .Pos (), "right hand must be only type assertion" )
112
119
return false
113
- case len (n .Names ) != 2 && tae .Type != nil :
120
+ case len (n .Names ) != 2 && tae .Type != nil && ! isAny ( pass , tae . Type ) :
114
121
result .m [n ] = true
115
122
result .nodes = append (result .nodes , n )
116
123
pass .Reportf (n .Pos (), "type assertion must be checked" )
0 commit comments