diff --git a/pkg/linters/sortslice/sortslice.go b/pkg/linters/sortslice/sortslice.go index 02752e48a6f..7579f0d9480 100644 --- a/pkg/linters/sortslice/sortslice.go +++ b/pkg/linters/sortslice/sortslice.go @@ -6,6 +6,7 @@ package sortslice import ( "fmt" "go/ast" + "go/types" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" @@ -52,12 +53,25 @@ func run(pass *analysis.Pass) (any, error) { return } pkgIdent, ok := sel.X.(*ast.Ident) - if !ok || pkgIdent.Name != "sort" { + if !ok { + return + } + if pass.TypesInfo == nil { + return + } + obj := pass.TypesInfo.ObjectOf(pkgIdent) + // ObjectOf can be nil when type information is incomplete. + if obj == nil { + return + } + pkgName, ok := obj.(*types.PkgName) + if !ok || pkgName.Imported().Path() != "sort" { return } switch sel.Sel.Name { case "Slice": + // Keep diagnostics on canonical stdlib names even for aliased imports. pass.ReportRangef(call, "sort.Slice is not type-safe; use slices.SortFunc instead") case "SliceStable": pass.ReportRangef(call, "sort.SliceStable is not type-safe; use slices.SortStableFunc instead") diff --git a/pkg/linters/sortslice/testdata/src/sortslice/alias_import.go b/pkg/linters/sortslice/testdata/src/sortslice/alias_import.go new file mode 100644 index 00000000000..2045f59e9ed --- /dev/null +++ b/pkg/linters/sortslice/testdata/src/sortslice/alias_import.go @@ -0,0 +1,11 @@ +package sortslice + +import s "sort" + +func BadSliceAliasedImport(items []string) { + s.Slice(items, func(i, j int) bool { return items[i] < items[j] }) // want `sort\.Slice is not type-safe` +} + +func BadSliceStableAliasedImport(items []string) { + s.SliceStable(items, func(i, j int) bool { return items[i] < items[j] }) // want `sort\.SliceStable is not type-safe` +} diff --git a/pkg/linters/sortslice/testdata/src/sortslice/shadowed_identifier.go b/pkg/linters/sortslice/testdata/src/sortslice/shadowed_identifier.go new file mode 100644 index 00000000000..df46bc48ddc --- /dev/null +++ b/pkg/linters/sortslice/testdata/src/sortslice/shadowed_identifier.go @@ -0,0 +1,12 @@ +package sortslice + +type customSort struct{} + +func (customSort) Slice(_ []string, _ func(i, j int) bool) {} +func (customSort) SliceStable(_ []string, _ func(i, j int) bool) {} + +func GoodShadowedSortIdentifier(items []string) { + sort := customSort{} + sort.Slice(items, func(i, j int) bool { return items[i] < items[j] }) + sort.SliceStable(items, func(i, j int) bool { return items[i] < items[j] }) +}