| 1 | // Copyright 2013 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 | // Hacked up copy of go/ast/import.go |
| 6 | // Modified to use a single token.File in preference to a FileSet. |
| 7 | |
| 8 | package imports |
| 9 | |
| 10 | import ( |
| 11 | "go/ast" |
| 12 | "go/token" |
| 13 | "log" |
| 14 | "reflect" |
| 15 | "slices" |
| 16 | "sort" |
| 17 | "strconv" |
| 18 | ) |
| 19 | |
| 20 | // sortImports sorts runs of consecutive import lines in import blocks in f. |
| 21 | // It also removes duplicate imports when it is possible to do so without data loss. |
| 22 | // |
| 23 | // It may mutate the token.File and the ast.File. |
| 24 | func sortImports(localPrefix string, tokFile *token.File, f *ast.File) { |
| 25 | for i, d := range f.Decls { |
| 26 | d, ok := d.(*ast.GenDecl) |
| 27 | if !ok || d.Tok != token.IMPORT { |
| 28 | // Not an import declaration, so we're done. |
| 29 | // Imports are always first. |
| 30 | break |
| 31 | } |
| 32 | |
| 33 | if len(d.Specs) == 0 { |
| 34 | // Empty import block, remove it. |
| 35 | f.Decls = slices.Delete(f.Decls, i, i+1) |
| 36 | } |
| 37 | |
| 38 | if !d.Lparen.IsValid() { |
| 39 | // Not a block: sorted by default. |
| 40 | continue |
| 41 | } |
| 42 | |
| 43 | // Identify and sort runs of specs on successive lines. |
| 44 | i := 0 |
| 45 | specs := d.Specs[:0] |
| 46 | for j, s := range d.Specs { |
| 47 | if j > i && tokFile.Line(s.Pos()) > 1+tokFile.Line(d.Specs[j-1].End()) { |
| 48 | // j begins a new run. End this one. |
| 49 | specs = append(specs, sortSpecs(localPrefix, tokFile, f, d.Specs[i:j])...) |
| 50 | i = j |
| 51 | } |
| 52 | } |
| 53 | specs = append(specs, sortSpecs(localPrefix, tokFile, f, d.Specs[i:])...) |
| 54 | d.Specs = specs |
| 55 | |
| 56 | // Deduping can leave a blank line before the rparen; clean that up. |
| 57 | // Ignore line directives. |
| 58 | if len(d.Specs) > 0 { |
| 59 | lastSpec := d.Specs[len(d.Specs)-1] |
| 60 | lastLine := tokFile.PositionFor(lastSpec.Pos(), false).Line |
| 61 | if rParenLine := tokFile.PositionFor(d.Rparen, false).Line; rParenLine > lastLine+1 { |
| 62 | tokFile.MergeLine(rParenLine - 1) // has side effects! |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // mergeImports merges all the import declarations into the first one. |
| 69 | // Taken from golang.org/x/tools/go/ast/astutil. |
| 70 | // This does not adjust line numbers properly |
| 71 | func mergeImports(f *ast.File) { |
| 72 | if len(f.Decls) <= 1 { |
| 73 | return |
| 74 | } |
| 75 | |
| 76 | // Merge all the import declarations into the first one. |
| 77 | var first *ast.GenDecl |
| 78 | for i := 0; i < len(f.Decls); i++ { |
| 79 | decl := f.Decls[i] |
| 80 | gen, ok := decl.(*ast.GenDecl) |
| 81 | if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") { |
| 82 | continue |
| 83 | } |
| 84 | if first == nil { |
| 85 | first = gen |
| 86 | continue // Don't touch the first one. |
| 87 | } |
| 88 | // We now know there is more than one package in this import |
| 89 | // declaration. Ensure that it ends up parenthesized. |
| 90 | first.Lparen = first.Pos() |
| 91 | // Move the imports of the other import declaration to the first one. |
| 92 | for _, spec := range gen.Specs { |
| 93 | updateBasicLitPos(spec.(*ast.ImportSpec).Path, first.Pos()) |
| 94 | first.Specs = append(first.Specs, spec) |
| 95 | } |
| 96 | f.Decls = slices.Delete(f.Decls, i, i+1) |
| 97 | i-- |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // declImports reports whether gen contains an import of path. |
| 102 | // Taken from golang.org/x/tools/go/ast/astutil. |
| 103 | func declImports(gen *ast.GenDecl, path string) bool { |
| 104 | if gen.Tok != token.IMPORT { |
| 105 | return false |
| 106 | } |
| 107 | for _, spec := range gen.Specs { |
| 108 | impspec := spec.(*ast.ImportSpec) |
| 109 | if importPath(impspec) == path { |
| 110 | return true |
| 111 | } |
| 112 | } |
| 113 | return false |
| 114 | } |
| 115 | |
| 116 | func importPath(s ast.Spec) string { |
| 117 | t, err := strconv.Unquote(s.(*ast.ImportSpec).Path.Value) |
| 118 | if err == nil { |
| 119 | return t |
| 120 | } |
| 121 | return "" |
| 122 | } |
| 123 | |
| 124 | func importName(s ast.Spec) string { |
| 125 | n := s.(*ast.ImportSpec).Name |
| 126 | if n == nil { |
| 127 | return "" |
| 128 | } |
| 129 | return n.Name |
| 130 | } |
| 131 | |
| 132 | func importComment(s ast.Spec) string { |
| 133 | c := s.(*ast.ImportSpec).Comment |
| 134 | if c == nil { |
| 135 | return "" |
| 136 | } |
| 137 | return c.Text() |
| 138 | } |
| 139 | |
| 140 | // collapse indicates whether prev may be removed, leaving only next. |
| 141 | func collapse(prev, next ast.Spec) bool { |
| 142 | if importPath(next) != importPath(prev) || importName(next) != importName(prev) { |
| 143 | return false |
| 144 | } |
| 145 | return prev.(*ast.ImportSpec).Comment == nil |
| 146 | } |
| 147 | |
| 148 | type posSpan struct { |
| 149 | Start token.Pos |
| 150 | End token.Pos |
| 151 | } |
| 152 | |
| 153 | // sortSpecs sorts the import specs within each import decl. |
| 154 | // It may mutate the token.File. |
| 155 | func sortSpecs(localPrefix string, tokFile *token.File, f *ast.File, specs []ast.Spec) []ast.Spec { |
| 156 | // Can't short-circuit here even if specs are already sorted, |
| 157 | // since they might yet need deduplication. |
| 158 | // A lone import, however, may be safely ignored. |
| 159 | if len(specs) <= 1 { |
| 160 | return specs |
| 161 | } |
| 162 | |
| 163 | // Record positions for specs. |
| 164 | pos := make([]posSpan, len(specs)) |
| 165 | for i, s := range specs { |
| 166 | pos[i] = posSpan{s.Pos(), s.End()} |
| 167 | } |
| 168 | |
| 169 | // Identify comments in this range. |
| 170 | // Any comment from pos[0].Start to the final line counts. |
| 171 | lastLine := tokFile.Line(pos[len(pos)-1].End) |
| 172 | cstart := len(f.Comments) |
| 173 | cend := len(f.Comments) |
| 174 | for i, g := range f.Comments { |
| 175 | if g.Pos() < pos[0].Start { |
| 176 | continue |
| 177 | } |
| 178 | if i < cstart { |
| 179 | cstart = i |
| 180 | } |
| 181 | if tokFile.Line(g.End()) > lastLine { |
| 182 | cend = i |
| 183 | break |
| 184 | } |
| 185 | } |
| 186 | comments := f.Comments[cstart:cend] |
| 187 | |
| 188 | // Assign each comment to the import spec preceding it. |
| 189 | importComment := map[*ast.ImportSpec][]*ast.CommentGroup{} |
| 190 | specIndex := 0 |
| 191 | for _, g := range comments { |
| 192 | for specIndex+1 < len(specs) && pos[specIndex+1].Start <= g.Pos() { |
| 193 | specIndex++ |
| 194 | } |
| 195 | s := specs[specIndex].(*ast.ImportSpec) |
| 196 | importComment[s] = append(importComment[s], g) |
| 197 | } |
| 198 | |
| 199 | // Sort the import specs by import path. |
| 200 | // Remove duplicates, when possible without data loss. |
| 201 | // Reassign the import paths to have the same position sequence. |
| 202 | // Reassign each comment to abut the end of its spec. |
| 203 | // Sort the comments by new position. |
| 204 | sort.Sort(byImportSpec{localPrefix, specs}) |
| 205 | |
| 206 | // Dedup. Thanks to our sorting, we can just consider |
| 207 | // adjacent pairs of imports. |
| 208 | deduped := specs[:0] |
| 209 | for i, s := range specs { |
| 210 | if i == len(specs)-1 || !collapse(s, specs[i+1]) { |
| 211 | deduped = append(deduped, s) |
| 212 | } else { |
| 213 | p := s.Pos() |
| 214 | tokFile.MergeLine(tokFile.Line(p)) // has side effects! |
| 215 | } |
| 216 | } |
| 217 | specs = deduped |
| 218 | |
| 219 | // Fix up comment positions |
| 220 | for i, s := range specs { |
| 221 | s := s.(*ast.ImportSpec) |
| 222 | if s.Name != nil { |
| 223 | s.Name.NamePos = pos[i].Start |
| 224 | } |
| 225 | updateBasicLitPos(s.Path, pos[i].Start) |
| 226 | s.EndPos = pos[i].End |
| 227 | nextSpecPos := pos[i].End |
| 228 | |
| 229 | for _, g := range importComment[s] { |
| 230 | for _, c := range g.List { |
| 231 | c.Slash = pos[i].End |
| 232 | nextSpecPos = c.End() |
| 233 | } |
| 234 | } |
| 235 | if i < len(specs)-1 { |
| 236 | pos[i+1].Start = nextSpecPos |
| 237 | pos[i+1].End = nextSpecPos |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | sort.Sort(byCommentPos(comments)) |
| 242 | |
| 243 | // Fixup comments can insert blank lines, because import specs are on different lines. |
| 244 | // We remove those blank lines here by merging import spec to the first import spec line. |
| 245 | firstSpecLine := tokFile.Line(specs[0].Pos()) |
| 246 | for _, s := range specs[1:] { |
| 247 | p := s.Pos() |
| 248 | line := tokFile.Line(p) |
| 249 | for previousLine := line - 1; previousLine >= firstSpecLine; { |
| 250 | // MergeLine can panic. Avoid the panic at the cost of not removing the blank line |
| 251 | // golang/go#50329 |
| 252 | if previousLine > 0 && previousLine < tokFile.LineCount() { |
| 253 | tokFile.MergeLine(previousLine) // has side effects! |
| 254 | previousLine-- |
| 255 | } else { |
| 256 | // try to gather some data to diagnose how this could happen |
| 257 | req := "Please report what the imports section of your go file looked like." |
| 258 | log.Printf("panic avoided: first:%d line:%d previous:%d max:%d. %s", |
| 259 | firstSpecLine, line, previousLine, tokFile.LineCount(), req) |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | return specs |
| 264 | } |
| 265 | |
| 266 | type byImportSpec struct { |
| 267 | localPrefix string |
| 268 | specs []ast.Spec // slice of *ast.ImportSpec |
| 269 | } |
| 270 | |
| 271 | func (x byImportSpec) Len() int { return len(x.specs) } |
| 272 | func (x byImportSpec) Swap(i, j int) { x.specs[i], x.specs[j] = x.specs[j], x.specs[i] } |
| 273 | func (x byImportSpec) Less(i, j int) bool { |
| 274 | ipath := importPath(x.specs[i]) |
| 275 | jpath := importPath(x.specs[j]) |
| 276 | |
| 277 | igroup := importGroup(x.localPrefix, ipath) |
| 278 | jgroup := importGroup(x.localPrefix, jpath) |
| 279 | if igroup != jgroup { |
| 280 | return igroup < jgroup |
| 281 | } |
| 282 | |
| 283 | if ipath != jpath { |
| 284 | return ipath < jpath |
| 285 | } |
| 286 | iname := importName(x.specs[i]) |
| 287 | jname := importName(x.specs[j]) |
| 288 | |
| 289 | if iname != jname { |
| 290 | return iname < jname |
| 291 | } |
| 292 | return importComment(x.specs[i]) < importComment(x.specs[j]) |
| 293 | } |
| 294 | |
| 295 | type byCommentPos []*ast.CommentGroup |
| 296 | |
| 297 | func (x byCommentPos) Len() int { return len(x) } |
| 298 | func (x byCommentPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] } |
| 299 | func (x byCommentPos) Less(i, j int) bool { return x[i].Pos() < x[j].Pos() } |
| 300 | |
| 301 | // updateBasicLitPos updates lit.Pos, |
| 302 | // ensuring that lit.End (if set) is displaced by the same amount. |
| 303 | // (See https://go.dev/issue/76395.) |
| 304 | func updateBasicLitPos(lit *ast.BasicLit, pos token.Pos) { |
| 305 | len := lit.End() - lit.Pos() |
| 306 | lit.ValuePos = pos |
| 307 | // TODO(adonovan): after go1.26, simplify to: |
| 308 | // lit.ValueEnd = pos + len |
| 309 | v := reflect.ValueOf(lit).Elem().FieldByName("ValueEnd") |
| 310 | if v.IsValid() && v.Int() != 0 { |
| 311 | v.SetInt(int64(pos + len)) |
| 312 | } |
| 313 | } |