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

Commit

Permalink
Merge pull request #25 from ezimanyi/fix-edge-cases
Browse files Browse the repository at this point in the history
Fix a few edge cases due to missing ast node types
  • Loading branch information
esimonov committed Dec 23, 2021
2 parents 1956076 + b2c7223 commit 5d70754
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
7 changes: 7 additions & 0 deletions pkg/analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,15 @@ func (nom namedOccurrenceMap) checkStatement(stmt ast.Stmt, ifPos token.Pos) {
for _, el := range v.Body.List {
nom.checkStatement(el, v.If)
}
if elseBlock, ok := v.Else.(*ast.BlockStmt); ok {
for _, el := range elseBlock.List {
nom.checkStatement(el, v.If)
}
}

switch cond := v.Cond.(type) {
case *ast.UnaryExpr:
nom.checkExpression(cond.X, v.If)
case *ast.BinaryExpr:
nom.checkExpression(cond.X, v.If)
nom.checkExpression(cond.Y, v.If)
Expand Down
7 changes: 7 additions & 0 deletions pkg/analyzer/occurrences.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,13 @@ func (nom namedOccurrenceMap) addFromCondition(stmt *ast.IfStmt) {
nom.addFromIdent(stmt.If, e.X)
}
}
case *ast.UnaryExpr:
switch e := v.X.(type) {
case *ast.Ident:
nom.addFromIdent(stmt.If, e)
case *ast.SelectorExpr:
nom.addFromIdent(stmt.If, e.X)
}
case *ast.Ident:
nom.addFromIdent(stmt.If, v)
case *ast.CallExpr:
Expand Down
34 changes: 33 additions & 1 deletion testdata/testdata.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ func notUsed_DifferentVarsWithSameName_NotOK() {
noOp2(b)
}

func notUsed_UnaryOpIfStatement_NotOK() {
shouldRun := false // want "variable '.+' is only used in the if-statement"
if !shouldRun {
return
}
noOp1(0)
}

// Cases where short syntax SHOULD NOT be used AND IS NOT used.

func notUsed_DeferStmt_OK() {
Expand Down Expand Up @@ -574,4 +582,28 @@ func notUsed_ReturnInSlice_Selector_OK(d dummyType) ([]interface{}, interface{})
return nil, v.interf
}
return []interface{}{v.interf}, nil
}
}

func notUsed_Multiple_If_Statements_OK() {
shouldRun := false
if shouldRun {
noOp1(0)
}
if !shouldRun {
return
}
noOp2(0)
}

func notUsed_Also_Used_In_Else_Body_OK() {
x := 0
if x > 0 {
noOp1(0)
}

if y := getInt(0); y > 0 {
noOp1(y)
} else {
noOp1(x)
}
}

0 comments on commit 5d70754

Please sign in to comment.