From 4ee75424787629fda1692a2561440ba40f427adf Mon Sep 17 00:00:00 2001 From: Denis Voytyuk <5462781+denisvmedia@users.noreply.github.com> Date: Mon, 21 Aug 2023 23:45:41 +0200 Subject: [PATCH] fix: false positive in import-shadowing for method names (#876) --- rule/import-shadowing.go | 11 +++++++++-- testdata/import-shadowing.go | 8 ++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/rule/import-shadowing.go b/rule/import-shadowing.go index 2bab704d0..046aeb688 100644 --- a/rule/import-shadowing.go +++ b/rule/import-shadowing.go @@ -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) @@ -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 @@ -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 @@ -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), }) diff --git a/testdata/import-shadowing.go b/testdata/import-shadowing.go index 124f108fb..230f8079a 100644 --- a/testdata/import-shadowing.go +++ b/testdata/import-shadowing.go @@ -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) {}