| 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 typesinternal |
| 6 | |
| 7 | import ( |
| 8 | "go/ast" |
| 9 | "go/types" |
| 10 | "strconv" |
| 11 | ) |
| 12 | |
| 13 | // FileQualifier returns a [types.Qualifier] function that qualifies |
| 14 | // imported symbols appropriately based on the import environment of a given |
| 15 | // file. |
| 16 | // If the same package is imported multiple times, the last appearance is |
| 17 | // recorded. |
| 18 | // |
| 19 | // TODO(adonovan): this function ignores the effect of shadowing. It |
| 20 | // should accept a [token.Pos] and a [types.Info] and compute only the |
| 21 | // set of imports that are not shadowed at that point, analogous to |
| 22 | // [analysis.AddImport]. It could also compute (as a side |
| 23 | // effect) the set of additional imports required to ensure that there |
| 24 | // is an accessible import for each necessary package, making it |
| 25 | // converge even more closely with AddImport. |
| 26 | func FileQualifier(f *ast.File, pkg *types.Package) types.Qualifier { |
| 27 | // Construct mapping of import paths to their defined names. |
| 28 | // It is only necessary to look at renaming imports. |
| 29 | imports := make(map[string]string) |
| 30 | for _, imp := range f.Imports { |
| 31 | if imp.Name != nil && imp.Name.Name != "_" { |
| 32 | path, _ := strconv.Unquote(imp.Path.Value) |
| 33 | imports[path] = imp.Name.Name |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Define qualifier to replace full package paths with names of the imports. |
| 38 | return func(p *types.Package) string { |
| 39 | if p == nil || p == pkg { |
| 40 | return "" |
| 41 | } |
| 42 | |
| 43 | if name, ok := imports[p.Path()]; ok { |
| 44 | if name == "." { |
| 45 | return "" |
| 46 | } else { |
| 47 | return name |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // If there is no local renaming, fall back to the package name. |
| 52 | return p.Name() |
| 53 | } |
| 54 | } |