|
| 1 | +// Copyright 2024 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package modernize |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "go/ast" |
| 10 | + "go/token" |
| 11 | + "go/types" |
| 12 | + |
| 13 | + "golang.org/x/tools/go/analysis" |
| 14 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 15 | + "golang.org/x/tools/go/ast/inspector" |
| 16 | + "golang.org/x/tools/gopls/internal/util/astutil" |
| 17 | + "golang.org/x/tools/internal/analysisinternal" |
| 18 | +) |
| 19 | + |
| 20 | +// The sortslice pass replaces sort.Slice(slice, less) with |
| 21 | +// slices.Sort(slice) when slice is a []T and less is a FuncLit |
| 22 | +// equivalent to cmp.Ordered[T]. |
| 23 | +// |
| 24 | +// sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) |
| 25 | +// => slices.Sort(s) |
| 26 | +// |
| 27 | +// It also supports the SliceStable variant. |
| 28 | +// |
| 29 | +// TODO(adonovan): support |
| 30 | +// |
| 31 | +// - sort.Slice(s, func(i, j int) bool { return s[i] ... s[j] }) |
| 32 | +// -> slices.SortFunc(s, func(x, y int) bool { return x ... y }) |
| 33 | +// iff all uses of i, j can be replaced by s[i], s[j]. |
| 34 | +// |
| 35 | +// - sort.Sort(x) where x has a named slice type whose Less method is the natural order. |
| 36 | +// -> sort.Slice(x) |
| 37 | +func sortslice(pass *analysis.Pass) { |
| 38 | + if !_imports(pass.Pkg, "sort") { |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 43 | + info := pass.TypesInfo |
| 44 | + for call := range inspector.All[*ast.CallExpr](inspect) { |
| 45 | + // call to sort.Slice{,Stable}? |
| 46 | + var stable string |
| 47 | + if isQualifiedIdent(info, call.Fun, "sort", "Slice") { |
| 48 | + } else if isQualifiedIdent(info, call.Fun, "sort", "SliceStable") { |
| 49 | + stable = "Stable" |
| 50 | + } else { |
| 51 | + continue |
| 52 | + } |
| 53 | + |
| 54 | + if lit, ok := call.Args[1].(*ast.FuncLit); ok && len(lit.Body.List) == 1 { |
| 55 | + sig := info.Types[lit.Type].Type.(*types.Signature) |
| 56 | + |
| 57 | + // Have: sort.Slice(s, func(i, j int) bool { return ... }) |
| 58 | + s := call.Args[0] |
| 59 | + i := sig.Params().At(0) |
| 60 | + j := sig.Params().At(1) |
| 61 | + |
| 62 | + ret := lit.Body.List[0].(*ast.ReturnStmt) |
| 63 | + if compare, ok := ret.Results[0].(*ast.BinaryExpr); ok && compare.Op == token.LSS { |
| 64 | + // isIndex reports whether e is s[v]. |
| 65 | + isIndex := func(e ast.Expr, v *types.Var) bool { |
| 66 | + index, ok := e.(*ast.IndexExpr) |
| 67 | + return ok && |
| 68 | + equalSyntax(index.X, s) && |
| 69 | + is[*ast.Ident](index.Index) && |
| 70 | + info.Uses[index.Index.(*ast.Ident)] == v |
| 71 | + } |
| 72 | + if isIndex(compare.X, i) && isIndex(compare.Y, j) { |
| 73 | + // Have: sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) |
| 74 | + |
| 75 | + file := enclosingFile(pass, call.Pos()) |
| 76 | + slicesName, importEdits := analysisinternal.AddImport(pass.TypesInfo, file, call.Pos(), "slices", "slices") |
| 77 | + |
| 78 | + pass.Report(analysis.Diagnostic{ |
| 79 | + // Highlight "sort.Slice". |
| 80 | + Pos: call.Fun.Pos(), |
| 81 | + End: call.Fun.End(), |
| 82 | + Category: "sortslice", |
| 83 | + Message: fmt.Sprintf("sort.Slice%[1]s can be modernized using slices.Sort%[1]s", stable), |
| 84 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 85 | + Message: fmt.Sprintf("Replace sort.Slice%[1]s call by slices.Sort%[1]s", stable), |
| 86 | + TextEdits: append(importEdits, []analysis.TextEdit{ |
| 87 | + { |
| 88 | + // Replace sort.Slice with slices.Sort. |
| 89 | + Pos: call.Fun.Pos(), |
| 90 | + End: call.Fun.End(), |
| 91 | + NewText: []byte(slicesName + ".Sort" + stable), |
| 92 | + }, |
| 93 | + { |
| 94 | + // Eliminate FuncLit. |
| 95 | + Pos: call.Args[0].End(), |
| 96 | + End: call.Rparen, |
| 97 | + }, |
| 98 | + }...), |
| 99 | + }}, |
| 100 | + }) |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +// isQualifiedIdent reports whether e is a reference to pkg.Name. |
| 108 | +func isQualifiedIdent(info *types.Info, e ast.Expr, pkgpath, name string) bool { |
| 109 | + var id *ast.Ident |
| 110 | + switch e := e.(type) { |
| 111 | + case *ast.Ident: |
| 112 | + id = e // e.g. dot import |
| 113 | + case *ast.SelectorExpr: |
| 114 | + id = e.Sel |
| 115 | + default: |
| 116 | + return false |
| 117 | + } |
| 118 | + obj, ok := info.Uses[id] |
| 119 | + return ok && isPackageLevel(obj) && obj.Pkg().Path() == pkgpath && id.Name == name |
| 120 | +} |
| 121 | + |
| 122 | +// isPackageLevel reports whether obj is a package-level func/var/const/type. |
| 123 | +func isPackageLevel(obj types.Object) bool { |
| 124 | + pkg := obj.Pkg() |
| 125 | + return pkg != nil && obj.Parent() == pkg.Scope() |
| 126 | +} |
| 127 | + |
| 128 | +// enclosingFile returns the file enclosing pos. |
| 129 | +// (It walks over the list of files, so is not terribly efficient.) |
| 130 | +func enclosingFile(pass *analysis.Pass, pos token.Pos) *ast.File { |
| 131 | + for _, file := range pass.Files { |
| 132 | + if astutil.NodeContains(file, pos) { |
| 133 | + return file |
| 134 | + } |
| 135 | + } |
| 136 | + return nil |
| 137 | +} |
0 commit comments