Skip to content
This repository was archived by the owner on Jul 31, 2022. It is now read-only.

Commit b2c7223

Browse files
committed
Fix a few edge cases due to missing ast node types
* Traverse Unary expressions in if statements * Traverse else blocks This fixes both false positives and negatives resulting from previously ignoring uses of variables in the above node types.
1 parent 1956076 commit b2c7223

File tree

3 files changed

+47
-1
lines changed

3 files changed

+47
-1
lines changed

pkg/analyzer/analyzer.go

+7
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,15 @@ func (nom namedOccurrenceMap) checkStatement(stmt ast.Stmt, ifPos token.Pos) {
108108
for _, el := range v.Body.List {
109109
nom.checkStatement(el, v.If)
110110
}
111+
if elseBlock, ok := v.Else.(*ast.BlockStmt); ok {
112+
for _, el := range elseBlock.List {
113+
nom.checkStatement(el, v.If)
114+
}
115+
}
111116

112117
switch cond := v.Cond.(type) {
118+
case *ast.UnaryExpr:
119+
nom.checkExpression(cond.X, v.If)
113120
case *ast.BinaryExpr:
114121
nom.checkExpression(cond.X, v.If)
115122
nom.checkExpression(cond.Y, v.If)

pkg/analyzer/occurrences.go

+7
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,13 @@ func (nom namedOccurrenceMap) addFromCondition(stmt *ast.IfStmt) {
193193
nom.addFromIdent(stmt.If, e.X)
194194
}
195195
}
196+
case *ast.UnaryExpr:
197+
switch e := v.X.(type) {
198+
case *ast.Ident:
199+
nom.addFromIdent(stmt.If, e)
200+
case *ast.SelectorExpr:
201+
nom.addFromIdent(stmt.If, e.X)
202+
}
196203
case *ast.Ident:
197204
nom.addFromIdent(stmt.If, v)
198205
case *ast.CallExpr:

testdata/testdata.go

+33-1
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,14 @@ func notUsed_DifferentVarsWithSameName_NotOK() {
7777
noOp2(b)
7878
}
7979

80+
func notUsed_UnaryOpIfStatement_NotOK() {
81+
shouldRun := false // want "variable '.+' is only used in the if-statement"
82+
if !shouldRun {
83+
return
84+
}
85+
noOp1(0)
86+
}
87+
8088
// Cases where short syntax SHOULD NOT be used AND IS NOT used.
8189

8290
func notUsed_DeferStmt_OK() {
@@ -574,4 +582,28 @@ func notUsed_ReturnInSlice_Selector_OK(d dummyType) ([]interface{}, interface{})
574582
return nil, v.interf
575583
}
576584
return []interface{}{v.interf}, nil
577-
}
585+
}
586+
587+
func notUsed_Multiple_If_Statements_OK() {
588+
shouldRun := false
589+
if shouldRun {
590+
noOp1(0)
591+
}
592+
if !shouldRun {
593+
return
594+
}
595+
noOp2(0)
596+
}
597+
598+
func notUsed_Also_Used_In_Else_Body_OK() {
599+
x := 0
600+
if x > 0 {
601+
noOp1(0)
602+
}
603+
604+
if y := getInt(0); y > 0 {
605+
noOp1(y)
606+
} else {
607+
noOp1(x)
608+
}
609+
}

0 commit comments

Comments
 (0)