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

Fix a few edge cases due to missing ast node types #25

Merged
merged 1 commit into from
Dec 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}