Skip to content

Commit

Permalink
chore: add missing tests for var-declarations, fix any/interface{} ty…
Browse files Browse the repository at this point in the history
…pe issue
  • Loading branch information
denisvmedia committed Dec 1, 2024
1 parent b532dc8 commit 52534df
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
13 changes: 12 additions & 1 deletion rule/var_declarations.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func (w *lintVarDeclarations) Visit(node ast.Node) ast.Visitor {
// If the RHS is a isZero value, suggest dropping it.
isZero := false
if lit, ok := rhs.(*ast.BasicLit); ok {
isZero = zeroLiteral[lit.Value]
isZero = isZeroValue(lit.Value, v.Type)
} else if isIdent(rhs, "nil") {
isZero = true
}
Expand Down Expand Up @@ -142,3 +142,14 @@ func validType(t types.Type) bool {
t != types.Typ[types.Invalid] &&
!strings.Contains(t.String(), "invalid type") // good but not foolproof
}

func isZeroValue(litValue string, typ ast.Expr) bool {
switch val := typ.(type) {
case *ast.Ident:
return val.Name == "any" && litValue == "nil"
case *ast.InterfaceType:
return litValue == "nil"
}

return zeroLiteral[litValue]
}
13 changes: 13 additions & 0 deletions test/var_declarations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package test

import (
"testing"

"github.com/mgechev/revive/lint"
"github.com/mgechev/revive/rule"
)

func TestVarDeclarations(t *testing.T) {
testRule(t, "var_declarations_type_inference", &rule.VarDeclarationsRule{}, &lint.RuleConfig{})
testRule(t, "var_declarations_zero_value", &rule.VarDeclarationsRule{}, &lint.RuleConfig{})
}
6 changes: 6 additions & 0 deletions testdata/var_declarations_type_inference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package fixtures

func typeInferenceExample() {
var x int = 42 // MATCH /should omit type int from declaration of var x; it will be inferred from the right-hand side/
var y = 42 // No warning, type is inferred
}
9 changes: 9 additions & 0 deletions testdata/var_declarations_zero_value.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package fixtures

func zeroValueExample() {
var y int // No warning, zero value is implicit
var z1 any = 0 // No warning, zero value for any is nil
var z2 any = nil // MATCH /should drop = nil from declaration of var z2; it is the zero value/
var z3 interface{} = 0 // No warning, zero value for any is nil
var z4 interface{} = nil // MATCH /should drop = nil from declaration of var z4; it is the zero value/
}

0 comments on commit 52534df

Please sign in to comment.