-
Notifications
You must be signed in to change notification settings - Fork 526
Expand file tree
/
Copy pathsortslice.go
More file actions
78 lines (67 loc) · 2.12 KB
/
Copy pathsortslice.go
File metadata and controls
78 lines (67 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Package sortslice implements a Go analysis linter that flags sort.Slice
// and sort.SliceStable calls that should use the type-safe slices.SortFunc
// or slices.SortStableFunc from the standard library slices package.
package sortslice
import (
"fmt"
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"github.com/github/gh-aw/pkg/linters/internal/filecheck"
"github.com/github/gh-aw/pkg/linters/internal/nolint"
)
// Analyzer is the sort-slice analysis pass.
var Analyzer = &analysis.Analyzer{
Name: "sortslice",
Doc: "reports sort.Slice and sort.SliceStable calls that should use the type-safe slices.SortFunc or slices.SortStableFunc",
URL: "https://github.com/github/gh-aw/tree/main/pkg/linters/sortslice",
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: run,
}
func run(pass *analysis.Pass) (any, error) {
insp, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
if !ok {
return nil, fmt.Errorf("inspect analyzer result has unexpected type %T", pass.ResultOf[inspect.Analyzer])
}
noLintLinesByFile := nolint.BuildLineIndex(pass, "sortslice")
nodeFilter := []ast.Node{(*ast.CallExpr)(nil)}
insp.Preorder(nodeFilter, func(n ast.Node) {
call, ok := n.(*ast.CallExpr)
if !ok {
return
}
pos := pass.Fset.PositionFor(call.Pos(), false)
if filecheck.IsTestFile(pos.Filename) {
return
}
if nolint.HasDirective(pos, noLintLinesByFile) {
return
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return
}
pkgIdent, ok := sel.X.(*ast.Ident)
if !ok {
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":
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")
}
})
return nil, nil
}