Skip to content

Commit

Permalink
fix: false positive in import-shadowing for method names (#876)
Browse files Browse the repository at this point in the history
  • Loading branch information
denisvmedia committed Aug 21, 2023
1 parent e758901 commit 4ee7542
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
11 changes: 9 additions & 2 deletions rule/import-shadowing.go
Expand Up @@ -29,6 +29,7 @@ func (*ImportShadowingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fail
failures = append(failures, failure)
},
alreadySeen: map[*ast.Object]struct{}{},
skipIdents: map[*ast.Ident]struct{}{},
}

ast.Walk(walker, fileAst)
Expand Down Expand Up @@ -62,6 +63,7 @@ type importShadowing struct {
importNames map[string]struct{}
onFailure func(lint.Failure)
alreadySeen map[*ast.Object]struct{}
skipIdents map[*ast.Ident]struct{}
}

// Visit visits AST nodes and checks if id nodes (ast.Ident) shadow an import name
Expand All @@ -80,6 +82,10 @@ func (w importShadowing) Visit(n ast.Node) ast.Visitor {
*ast.SelectorExpr, // skip analysis of selector expressions (anId.otherId): because if anId shadows an import name, it was already detected, and otherId does not shadows the import name
*ast.StructType: // skip analysis of struct type because struct fields can not shadow an import name
return nil
case *ast.FuncDecl:
if n.Recv != nil {
w.skipIdents[n.Name] = struct{}{}
}
case *ast.Ident:
if n == w.packageNameIdent {
return nil // skip the ident corresponding to the package name of this file
Expand All @@ -92,11 +98,12 @@ func (w importShadowing) Visit(n ast.Node) ast.Visitor {

_, isImportName := w.importNames[id]
_, alreadySeen := w.alreadySeen[n.Obj]
if isImportName && !alreadySeen {
_, skipIdent := w.skipIdents[n]
if isImportName && !alreadySeen && !skipIdent {
w.onFailure(lint.Failure{
Confidence: 1,
Node: n,
Category: "namming",
Category: "naming",
Failure: fmt.Sprintf("The name '%s' shadows an import name", id),
})

Expand Down
8 changes: 8 additions & 0 deletions testdata/import-shadowing.go
Expand Up @@ -23,6 +23,14 @@ type fmt interface {} // MATCH /The name 'fmt' shadows an import name/

func (ast myAst) foo() {} // MATCH /The name 'ast' shadows an import name/

func (a myAst) fmt() { // this should be skipped (method, not a pkg func)
var fmt string // MATCH /The name 'fmt' shadows an import name/
}

func (a myAst) md5() { // this should be skipped (method, not a pkg func)
strings := map[string]string{} // MATCH /The name 'strings' shadows an import name/
}

func md5() {} // MATCH /The name 'md5' shadows an import name/

func bar(_ string) {}
Expand Down

0 comments on commit 4ee7542

Please sign in to comment.