| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package golang |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"fmt" |
| 12 |
"go/ast" |
| 13 |
"go/token" |
| 14 |
"go/types" |
| 15 |
"html" |
| 16 |
"slices" |
| 17 |
"sort" |
| 18 |
"strings" |
| 19 |
|
| 20 |
"golang.org/x/tools/go/ast/astutil" |
| 21 |
"golang.org/x/tools/gopls/internal/cache" |
| 22 |
"golang.org/x/tools/gopls/internal/cache/metadata" |
| 23 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 24 |
"golang.org/x/tools/gopls/internal/util/moremaps" |
| 25 |
"golang.org/x/tools/gopls/internal/util/safetoken" |
| 26 |
"golang.org/x/tools/internal/typesinternal" |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
func FreeSymbolsHTML(viewID string, pkg *cache.Package, pgf *parsego.File, start, end token.Pos, web Web) []byte { |
| 32 |
|
| 33 |
|
| 34 |
refs := freeRefs(pkg.Types(), pkg.TypesInfo(), pgf.File, start, end) |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
type Import struct { |
| 39 |
Path metadata.PackagePath |
| 40 |
Symbols []string |
| 41 |
} |
| 42 |
type Symbol struct { |
| 43 |
Kind string |
| 44 |
Type string |
| 45 |
Refs []types.Object |
| 46 |
} |
| 47 |
var model struct { |
| 48 |
Imported []Import |
| 49 |
PkgLevel []Symbol |
| 50 |
Local []Symbol |
| 51 |
} |
| 52 |
|
| 53 |
qualifier := typesinternal.NameRelativeTo(pkg.Types()) |
| 54 |
|
| 55 |
|
| 56 |
{ |
| 57 |
|
| 58 |
sort.Slice(refs, func(i, j int) bool { |
| 59 |
return refs[i].dotted < refs[j].dotted |
| 60 |
}) |
| 61 |
|
| 62 |
|
| 63 |
imported := make(map[string][]*freeRef) |
| 64 |
seen := make(map[string]bool) |
| 65 |
for _, ref := range refs { |
| 66 |
if seen[ref.dotted] { |
| 67 |
continue |
| 68 |
} |
| 69 |
seen[ref.dotted] = true |
| 70 |
|
| 71 |
var symbols *[]Symbol |
| 72 |
switch ref.scope { |
| 73 |
case "file": |
| 74 |
|
| 75 |
if pkgname, ok := ref.objects[0].(*types.PkgName); ok { |
| 76 |
path := pkgname.Imported().Path() |
| 77 |
imported[path] = append(imported[path], ref) |
| 78 |
} |
| 79 |
continue |
| 80 |
case "pkg": |
| 81 |
symbols = &model.PkgLevel |
| 82 |
case "local": |
| 83 |
symbols = &model.Local |
| 84 |
default: |
| 85 |
panic(ref.scope) |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
typestr := " " + types.TypeString(ref.typ, qualifier) |
| 93 |
var kind string |
| 94 |
switch obj := ref.objects[len(ref.objects)-1].(type) { |
| 95 |
case *types.Var: |
| 96 |
kind = "var" |
| 97 |
case *types.Func: |
| 98 |
kind = "func" |
| 99 |
case *types.TypeName: |
| 100 |
if is[*types.TypeParam](obj.Type()) { |
| 101 |
kind = "type parameter" |
| 102 |
} else { |
| 103 |
kind = "type" |
| 104 |
} |
| 105 |
typestr = "" |
| 106 |
case *types.Const: |
| 107 |
kind = "const" |
| 108 |
case *types.Label: |
| 109 |
kind = "label" |
| 110 |
typestr = "" |
| 111 |
} |
| 112 |
|
| 113 |
*symbols = append(*symbols, Symbol{ |
| 114 |
Kind: kind, |
| 115 |
Type: typestr, |
| 116 |
Refs: ref.objects, |
| 117 |
}) |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
for pkgPath, refs := range moremaps.Sorted(imported) { |
| 123 |
var syms []string |
| 124 |
for _, ref := range refs { |
| 125 |
|
| 126 |
syms = append(syms, ref.dotted[len(ref.objects[0].Name())+len("."):]) |
| 127 |
} |
| 128 |
sort.Strings(syms) |
| 129 |
const max = 4 |
| 130 |
if len(syms) > max { |
| 131 |
syms[max-1] = fmt.Sprintf("... (%d)", len(syms)) |
| 132 |
syms = syms[:max] |
| 133 |
} |
| 134 |
|
| 135 |
model.Imported = append(model.Imported, Import{ |
| 136 |
Path: PackagePath(pkgPath), |
| 137 |
Symbols: syms, |
| 138 |
}) |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
var buf bytes.Buffer |
| 145 |
buf.WriteString(`<!DOCTYPE html> |
| 146 |
<html> |
| 147 |
<head> |
| 148 |
<style> |
| 149 |
.col-pkg { color: #2eb007 } |
| 150 |
.col-file { color: #a10b15 } |
| 151 |
.col-local { color: #0cb7c9 } |
| 152 |
li { font-family: monospace; } |
| 153 |
p { max-width: 6in; } |
| 154 |
</style> |
| 155 |
<script src="/assets/common.js"></script> |
| 156 |
<link rel="stylesheet" href="/assets/common.css"> |
| 157 |
</head> |
| 158 |
<body> |
| 159 |
<h1>Free symbols</h1> |
| 160 |
<p> |
| 161 |
The selected code contains references to these free* symbols: |
| 162 |
</p> |
| 163 |
`) |
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
fmt.Fprintf(&buf, "<h2><span class='col-file'>⬤</span> Imported symbols</h2>\n") |
| 171 |
fmt.Fprintf(&buf, "<ul>\n") |
| 172 |
for _, imp := range model.Imported { |
| 173 |
fmt.Fprintf(&buf, "<li>import \"<a href='%s'>%s</a>\" // for %s</li>\n", |
| 174 |
web.PkgURL(viewID, imp.Path, ""), |
| 175 |
html.EscapeString(string(imp.Path)), |
| 176 |
strings.Join(imp.Symbols, ", ")) |
| 177 |
} |
| 178 |
if len(model.Imported) == 0 { |
| 179 |
fmt.Fprintf(&buf, "<li>(none)</li>\n") |
| 180 |
} |
| 181 |
buf.WriteString("</ul>\n") |
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
showSymbols := func(scope, title string, symbols []Symbol) { |
| 186 |
fmt.Fprintf(&buf, "<h2><span class='col-%s'>⬤</span> %s</h2>\n", scope, title) |
| 187 |
fmt.Fprintf(&buf, "<ul>\n") |
| 188 |
pre := buf.Len() |
| 189 |
for _, sym := range symbols { |
| 190 |
fmt.Fprintf(&buf, "<li>%s ", sym.Kind) |
| 191 |
for i, obj := range sym.Refs { |
| 192 |
if i > 0 { |
| 193 |
buf.WriteByte('.') |
| 194 |
} |
| 195 |
buf.WriteString(objHTML(pkg.FileSet(), web, obj)) |
| 196 |
} |
| 197 |
fmt.Fprintf(&buf, " %s</li>\n", html.EscapeString(sym.Type)) |
| 198 |
} |
| 199 |
if buf.Len() == pre { |
| 200 |
fmt.Fprintf(&buf, "<li>(none)</li>\n") |
| 201 |
} |
| 202 |
buf.WriteString("</ul>\n") |
| 203 |
} |
| 204 |
showSymbols("pkg", "Package-level symbols", model.PkgLevel) |
| 205 |
showSymbols("local", "Local symbols", model.Local) |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
buf.WriteString("<hr/>\n") |
| 211 |
sort.Slice(refs, func(i, j int) bool { |
| 212 |
return refs[i].expr.Pos() < refs[j].expr.Pos() |
| 213 |
}) |
| 214 |
pos := start |
| 215 |
emitTo := func(end token.Pos) { |
| 216 |
if pos < end { |
| 217 |
fileStart := pgf.File.FileStart |
| 218 |
text := pgf.Mapper.Content[pos-fileStart : end-fileStart] |
| 219 |
buf.WriteString(html.EscapeString(string(text))) |
| 220 |
pos = end |
| 221 |
} |
| 222 |
} |
| 223 |
buf.WriteString(`<pre>`) |
| 224 |
for _, ref := range refs { |
| 225 |
emitTo(ref.expr.Pos()) |
| 226 |
fmt.Fprintf(&buf, `<b class='col-%s'>`, ref.scope) |
| 227 |
emitTo(ref.expr.End()) |
| 228 |
buf.WriteString(`</b>`) |
| 229 |
} |
| 230 |
emitTo(end) |
| 231 |
buf.WriteString(`</pre> |
| 232 |
<hr> |
| 233 |
<p> |
| 234 |
*A symbol is "free" if it is referenced within the selection but declared |
| 235 |
outside of it. |
| 236 |
|
| 237 |
The free variables are approximately the set of parameters that |
| 238 |
would be needed if the block were extracted into its own function in |
| 239 |
the same package. |
| 240 |
|
| 241 |
Free identifiers may include local types and control labels as well. |
| 242 |
|
| 243 |
Even when you don't intend to extract a block into a new function, |
| 244 |
this information can help you to tell at a glance what names a block |
| 245 |
of code depends on. |
| 246 |
</p> |
| 247 |
<p> |
| 248 |
Each dotted path of identifiers (such as file.Name.Pos) is reported |
| 249 |
as a separate item, so that you can see which parts of a complex |
| 250 |
type are actually needed. |
| 251 |
|
| 252 |
The free symbols referenced by the body of a function may |
| 253 |
reveal that only a small part (a single field of a struct, say) of |
| 254 |
one of the function's parameters is used, allowing you to simplify |
| 255 |
and generalize the function by choosing a different type for that |
| 256 |
parameter. |
| 257 |
</p> |
| 258 |
`) |
| 259 |
return buf.Bytes() |
| 260 |
} |
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
type freeRef struct { |
| 265 |
objects []types.Object |
| 266 |
dotted string |
| 267 |
scope string |
| 268 |
expr ast.Expr |
| 269 |
typ types.Type |
| 270 |
} |
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
func freeRefs(pkg *types.Package, info *types.Info, file *ast.File, start, end token.Pos) []*freeRef { |
| 276 |
|
| 277 |
info = &types.Info{ |
| 278 |
Scopes: info.Scopes, |
| 279 |
Types: info.Types, |
| 280 |
Uses: info.Uses, |
| 281 |
} |
| 282 |
|
| 283 |
fileScope := info.Scopes[file] |
| 284 |
pkgScope := fileScope.Parent() |
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
id := func(n *ast.Ident, suffix []types.Object) *freeRef { |
| 289 |
obj := info.Uses[n] |
| 290 |
if obj == nil { |
| 291 |
return nil |
| 292 |
} |
| 293 |
if start <= obj.Pos() && obj.Pos() < end { |
| 294 |
return nil |
| 295 |
} |
| 296 |
parent := obj.Parent() |
| 297 |
|
| 298 |
|
| 299 |
objects := append(suffix, obj) |
| 300 |
if obj.Pkg() != nil && obj.Pkg() != pkg && typesinternal.IsPackageLevel(obj) { |
| 301 |
|
| 302 |
pkgName := types.NewPkgName(token.NoPos, pkg, obj.Pkg().Name(), obj.Pkg()) |
| 303 |
parent = fileScope |
| 304 |
objects = append(objects, pkgName) |
| 305 |
} |
| 306 |
slices.Reverse(objects) |
| 307 |
var dotted strings.Builder |
| 308 |
for i, obj := range objects { |
| 309 |
if obj == nil { |
| 310 |
return nil |
| 311 |
} |
| 312 |
if i > 0 { |
| 313 |
dotted.WriteByte('.') |
| 314 |
} |
| 315 |
dotted.WriteString(obj.Name()) |
| 316 |
} |
| 317 |
|
| 318 |
|
| 319 |
var scope string |
| 320 |
switch parent { |
| 321 |
case nil: |
| 322 |
return nil |
| 323 |
case types.Universe: |
| 324 |
return nil |
| 325 |
case fileScope: |
| 326 |
scope = "file" |
| 327 |
case pkgScope: |
| 328 |
scope = "pkg" |
| 329 |
default: |
| 330 |
scope = "local" |
| 331 |
} |
| 332 |
|
| 333 |
return &freeRef{ |
| 334 |
objects: objects, |
| 335 |
dotted: dotted.String(), |
| 336 |
scope: scope, |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
|
| 341 |
sel := func(sel *ast.SelectorExpr, suffix []types.Object) *freeRef { |
| 342 |
for { |
| 343 |
suffix = append(suffix, info.Uses[sel.Sel]) |
| 344 |
|
| 345 |
switch x := ast.Unparen(sel.X).(type) { |
| 346 |
case *ast.Ident: |
| 347 |
return id(x, suffix) |
| 348 |
default: |
| 349 |
return nil |
| 350 |
case *ast.SelectorExpr: |
| 351 |
sel = x |
| 352 |
} |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
|
| 357 |
var free []*freeRef |
| 358 |
path, _ := astutil.PathEnclosingInterval(file, start, end) |
| 359 |
var visit func(n ast.Node) bool |
| 360 |
visit = func(n ast.Node) bool { |
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
if n != nil && start <= n.Pos() && n.End() <= end { |
| 365 |
var ref *freeRef |
| 366 |
switch n := n.(type) { |
| 367 |
case *ast.Ident: |
| 368 |
ref = id(n, nil) |
| 369 |
case *ast.SelectorExpr: |
| 370 |
ref = sel(n, nil) |
| 371 |
} |
| 372 |
|
| 373 |
if ref != nil { |
| 374 |
ref.expr = n.(ast.Expr) |
| 375 |
if tv, ok := info.Types[ref.expr]; ok { |
| 376 |
ref.typ = tv.Type |
| 377 |
} else { |
| 378 |
ref.typ = types.Typ[types.Invalid] |
| 379 |
} |
| 380 |
free = append(free, ref) |
| 381 |
} |
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
if sel, ok := n.(*ast.SelectorExpr); ok { |
| 386 |
if ref == nil { |
| 387 |
ast.Inspect(sel.X, visit) |
| 388 |
} |
| 389 |
return false |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
return true |
| 394 |
} |
| 395 |
ast.Inspect(path[0], visit) |
| 396 |
return free |
| 397 |
} |
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
func objHTML(fset *token.FileSet, web Web, obj types.Object) string { |
| 403 |
text := obj.Name() |
| 404 |
if posn := safetoken.StartPosition(fset, obj.Pos()); posn.IsValid() { |
| 405 |
url := web.SrcURL(posn.Filename, posn.Line, posn.Column) |
| 406 |
return sourceLink(text, url) |
| 407 |
} |
| 408 |
return text |
| 409 |
} |
| 410 |
|
| 411 |
|
| 412 |
func sourceLink(text, url string) string { |
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
return fmt.Sprintf(`<a href="%[1]s" onclick='return httpGET("%[1]s")'>%[2]s</a>`, |
| 419 |
html.EscapeString(url), text) |
| 420 |
} |