| 1 | // Copyright 2023 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 | //go:build go1.23 |
| 6 | |
| 7 | // The play program is a playground for go/types: a simple web-based |
| 8 | // text editor into which the user can enter a Go program, select a |
| 9 | // region, and see type information about it. |
| 10 | // |
| 11 | // It is intended for convenient exploration and debugging of |
| 12 | // go/types. The command and its web interface are not officially |
| 13 | // supported and they may be changed arbitrarily in the future. |
| 14 | package main |
| 15 | |
| 16 | import ( |
| 17 | "encoding/json" |
| 18 | "fmt" |
| 19 | "go/ast" |
| 20 | "go/format" |
| 21 | "go/token" |
| 22 | "go/types" |
| 23 | "io" |
| 24 | "log" |
| 25 | "net/http" |
| 26 | "os" |
| 27 | "path/filepath" |
| 28 | "reflect" |
| 29 | "slices" |
| 30 | "strconv" |
| 31 | "strings" |
| 32 | |
| 33 | goastutil "golang.org/x/tools/go/ast/astutil" |
| 34 | "golang.org/x/tools/go/ast/inspector" |
| 35 | "golang.org/x/tools/go/packages" |
| 36 | "golang.org/x/tools/go/types/typeutil" |
| 37 | "golang.org/x/tools/internal/astutil" |
| 38 | "golang.org/x/tools/internal/typeparams" |
| 39 | ) |
| 40 | |
| 41 | // TODO(adonovan): |
| 42 | // - show line numbers next to textarea. |
| 43 | // - mention this in the go/types tutorial. |
| 44 | // - display versions of go/types and go command. |
| 45 | |
| 46 | func main() { |
| 47 | http.HandleFunc("/", handleRoot) |
| 48 | http.HandleFunc("/main.js", handleJS) |
| 49 | http.HandleFunc("/main.css", handleCSS) |
| 50 | http.HandleFunc("/select.json", handleSelectJSON) |
| 51 | const addr = "localhost:9999" |
| 52 | log.Printf("Listening on http://%s", addr) |
| 53 | log.Fatal(http.ListenAndServe(addr, nil)) |
| 54 | } |
| 55 | |
| 56 | func handleSelectJSON(w http.ResponseWriter, req *http.Request) { |
| 57 | // Parse request. |
| 58 | if err := req.ParseForm(); err != nil { |
| 59 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 60 | return |
| 61 | } |
| 62 | startOffset, err := strconv.Atoi(req.Form.Get("start")) |
| 63 | if err != nil { |
| 64 | http.Error(w, fmt.Sprintf("start: %v", err), http.StatusBadRequest) |
| 65 | return |
| 66 | } |
| 67 | endOffset, err := strconv.Atoi(req.Form.Get("end")) |
| 68 | if err != nil { |
| 69 | http.Error(w, fmt.Sprintf("end: %v", err), http.StatusBadRequest) |
| 70 | return |
| 71 | } |
| 72 | |
| 73 | // Write Go program to temporary file. |
| 74 | f, err := os.CreateTemp("", "play-*.go") |
| 75 | if err != nil { |
| 76 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 77 | return |
| 78 | } |
| 79 | if _, err := io.Copy(f, req.Body); err != nil { |
| 80 | f.Close() // ignore error |
| 81 | http.Error(w, fmt.Sprintf("can't read body: %v", err), http.StatusInternalServerError) |
| 82 | return |
| 83 | } |
| 84 | if err := f.Close(); err != nil { |
| 85 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 86 | return |
| 87 | } |
| 88 | defer func() { |
| 89 | _ = os.Remove(f.Name()) // ignore error |
| 90 | }() |
| 91 | |
| 92 | // Load and type check it. |
| 93 | cfg := &packages.Config{ |
| 94 | Fset: token.NewFileSet(), |
| 95 | Mode: packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo, |
| 96 | Dir: filepath.Dir(f.Name()), |
| 97 | } |
| 98 | pkgs, err := packages.Load(cfg, "file="+f.Name()) |
| 99 | if err != nil { |
| 100 | http.Error(w, fmt.Sprintf("load: %v", err), http.StatusInternalServerError) |
| 101 | return |
| 102 | } |
| 103 | pkg := pkgs[0] |
| 104 | |
| 105 | // -- Format the response -- |
| 106 | |
| 107 | out := new(strings.Builder) |
| 108 | |
| 109 | // Parse/type error information. |
| 110 | if len(pkg.Errors) > 0 { |
| 111 | fmt.Fprintf(out, "Errors:\n") |
| 112 | for _, err := range pkg.Errors { |
| 113 | fmt.Fprintf(out, "%s: %s\n", err.Pos, err.Msg) |
| 114 | } |
| 115 | fmt.Fprintf(out, "\n") |
| 116 | } |
| 117 | |
| 118 | fset := pkg.Fset |
| 119 | file := pkg.Syntax[0] |
| 120 | tokFile := fset.File(file.FileStart) |
| 121 | startPos := tokFile.Pos(startOffset) |
| 122 | endPos := tokFile.Pos(endOffset) |
| 123 | |
| 124 | // Syntax information |
| 125 | path, exact := goastutil.PathEnclosingInterval(file, startPos, endPos) |
| 126 | fmt.Fprintf(out, "Path enclosing interval #%d-%d [exact=%t]:\n", |
| 127 | startOffset, endOffset, exact) |
| 128 | var innermostExpr ast.Expr |
| 129 | for i, n := range path { |
| 130 | // Show set of names defined in each scope. |
| 131 | scopeNames := "" |
| 132 | { |
| 133 | node := n |
| 134 | prefix := "" |
| 135 | |
| 136 | // A function (Func{Decl.Lit}) doesn't have a scope of its |
| 137 | // own, nor does its Body: only nested BlockStmts do. |
| 138 | // The type parameters, parameters, and locals are all |
| 139 | // in the scope associated with the FuncType; show it. |
| 140 | switch n := n.(type) { |
| 141 | case *ast.FuncDecl: |
| 142 | node = n.Type |
| 143 | prefix = "Type." |
| 144 | case *ast.FuncLit: |
| 145 | node = n.Type |
| 146 | prefix = "Type." |
| 147 | } |
| 148 | |
| 149 | if scope := pkg.TypesInfo.Scopes[node]; scope != nil { |
| 150 | scopeNames = fmt.Sprintf(" %sScope={%s}", |
| 151 | prefix, |
| 152 | strings.Join(scope.Names(), ", ")) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // TODO(adonovan): turn these into links to highlight the source. |
| 157 | start, end := fset.Position(n.Pos()), fset.Position(n.End()) |
| 158 | fmt.Fprintf(out, "[%d] %T @ %d:%d-%d:%d (#%d-%d)%s\n", |
| 159 | i, n, |
| 160 | start.Line, start.Column, end.Line, |
| 161 | end.Column, start.Offset, end.Offset, |
| 162 | scopeNames) |
| 163 | if e, ok := n.(ast.Expr); ok && innermostExpr == nil { |
| 164 | innermostExpr = e |
| 165 | } |
| 166 | } |
| 167 | // Show the Cursor.Enclosing stack too. |
| 168 | // It's usually the same, but may differ in edge |
| 169 | // cases (e.g. around FuncType.Func). |
| 170 | curFile, _ := inspector.New([]*ast.File{file}).Root().FirstChild() |
| 171 | if cur, ok := curFile.FindByPos(startPos, endPos); ok { |
| 172 | fmt.Fprintf(out, "Cursor.FindByPos().Enclosing() = %v\n", |
| 173 | slices.Collect(cur.Enclosing())) |
| 174 | } else { |
| 175 | fmt.Fprintf(out, "Cursor.FindPos() failed\n") |
| 176 | } |
| 177 | // And show the astutil.Select result (enclosing, leftmost & rightmost enclosed). |
| 178 | if curEnclosing, curStart, curEnd, err := astutil.Select(curFile, startPos, endPos); err == nil { |
| 179 | format := func(cur inspector.Cursor) string { |
| 180 | return fmt.Sprintf("%T@%v", cur.Node(), fset.Position(cur.Node().Pos())) |
| 181 | } |
| 182 | fmt.Fprintf(out, "astutil.Select() = (%s, %s, %s)\n", |
| 183 | format(curEnclosing), format(curStart), format(curEnd)) |
| 184 | } else { |
| 185 | fmt.Fprintf(out, "astutil.Select() = %v", err) |
| 186 | } |
| 187 | fmt.Fprintf(out, "\n") |
| 188 | |
| 189 | // Expression type information |
| 190 | if innermostExpr != nil { |
| 191 | if tv, ok := pkg.TypesInfo.Types[innermostExpr]; ok { |
| 192 | var modes []string |
| 193 | for _, mode := range []struct { |
| 194 | name string |
| 195 | condition func(types.TypeAndValue) bool |
| 196 | }{ |
| 197 | {"IsVoid", types.TypeAndValue.IsVoid}, |
| 198 | {"IsType", types.TypeAndValue.IsType}, |
| 199 | {"IsBuiltin", types.TypeAndValue.IsBuiltin}, |
| 200 | {"IsValue", types.TypeAndValue.IsValue}, |
| 201 | {"IsNil", types.TypeAndValue.IsNil}, |
| 202 | {"Addressable", types.TypeAndValue.Addressable}, |
| 203 | {"Assignable", types.TypeAndValue.Assignable}, |
| 204 | {"HasOk", types.TypeAndValue.HasOk}, |
| 205 | } { |
| 206 | if mode.condition(tv) { |
| 207 | modes = append(modes, mode.name) |
| 208 | } |
| 209 | } |
| 210 | fmt.Fprintf(out, "%T has type %v, mode %s", |
| 211 | innermostExpr, tv.Type, modes) |
| 212 | if tu := tv.Type.Underlying(); tu != tv.Type { |
| 213 | fmt.Fprintf(out, ", underlying type %v", tu) |
| 214 | } |
| 215 | if tc := typeparams.CoreType(tv.Type); tc != tv.Type { |
| 216 | fmt.Fprintf(out, ", core type %v", tc) |
| 217 | } |
| 218 | if tv.Value != nil { |
| 219 | fmt.Fprintf(out, ", and constant value %v", tv.Value) |
| 220 | } |
| 221 | terms, err := typeparams.NormalTerms(tv.Type) |
| 222 | if err != nil { |
| 223 | fmt.Fprintf(out, ", NormalTerms=%q", err) |
| 224 | } else { |
| 225 | fmt.Fprintf(out, ", NormalTerms=%v", terms) |
| 226 | } |
| 227 | } else { |
| 228 | fmt.Fprintf(out, "%T has no type", innermostExpr) |
| 229 | } |
| 230 | fmt.Fprintf(out, "\n\n") |
| 231 | } |
| 232 | |
| 233 | // selection x.f information (if cursor is over .f) |
| 234 | for _, n := range path[:min(2, len(path))] { |
| 235 | if sel, ok := n.(*ast.SelectorExpr); ok { |
| 236 | seln, ok := pkg.TypesInfo.Selections[sel] |
| 237 | if ok { |
| 238 | fmt.Fprintf(out, "Selection: %s recv=%v obj=%v type=%v indirect=%t index=%d\n\n", |
| 239 | strings.Fields("FieldVal MethodVal MethodExpr")[seln.Kind()], |
| 240 | seln.Recv(), |
| 241 | seln.Obj(), |
| 242 | seln.Type(), |
| 243 | seln.Indirect(), |
| 244 | seln.Index()) |
| 245 | |
| 246 | } else { |
| 247 | fmt.Fprintf(out, "Selector is qualified identifier.\n\n") |
| 248 | } |
| 249 | break |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // Object type information. |
| 254 | switch n := path[0].(type) { |
| 255 | case *ast.Ident: |
| 256 | // An embedded field is both a def and a use. |
| 257 | if obj, ok := pkg.TypesInfo.Defs[n]; ok { |
| 258 | if obj == nil { |
| 259 | fmt.Fprintf(out, "nil def") // e.g. package name, "_", type switch |
| 260 | } else { |
| 261 | formatObj(out, fset, "def", obj) |
| 262 | } |
| 263 | } |
| 264 | if obj, ok := pkg.TypesInfo.Uses[n]; ok { |
| 265 | formatObj(out, fset, "use", obj) |
| 266 | } |
| 267 | default: |
| 268 | if obj, ok := pkg.TypesInfo.Implicits[n]; ok { |
| 269 | formatObj(out, fset, "implicit def", obj) |
| 270 | } |
| 271 | } |
| 272 | fmt.Fprintf(out, "\n") |
| 273 | |
| 274 | // Pretty-print of selected syntax. |
| 275 | fmt.Fprintf(out, "Pretty-printed:\n") |
| 276 | format.Node(out, fset, path[0]) |
| 277 | fmt.Fprintf(out, "\n\n") |
| 278 | |
| 279 | // Syntax debug output. |
| 280 | fmt.Fprintf(out, "Syntax:\n") |
| 281 | ast.Fprint(out, fset, path[0], nil) // ignore errors |
| 282 | fmt.Fprintf(out, "\n\n") |
| 283 | |
| 284 | // Show inventory of all objects, including addresses to disambiguate. |
| 285 | fmt.Fprintf(out, "Objects:\n") |
| 286 | for curId := range curFile.Preorder((*ast.Ident)(nil)) { |
| 287 | id := curId.Node().(*ast.Ident) |
| 288 | if obj := pkg.TypesInfo.Defs[id]; obj != nil { |
| 289 | fmt.Fprintf(out, "%s: def %v (%p)\n", fset.Position(id.Pos()), obj, obj) |
| 290 | } |
| 291 | if obj, ok := pkg.TypesInfo.Uses[id]; ok { |
| 292 | fmt.Fprintf(out, "%s: use %v (%p)\n", fset.Position(id.Pos()), obj, obj) |
| 293 | } |
| 294 | } |
| 295 | fmt.Fprintf(out, "\n\n") |
| 296 | |
| 297 | // Clean up the messy temp file name. |
| 298 | outStr := strings.ReplaceAll(out.String(), f.Name(), "play.go") |
| 299 | |
| 300 | // Send response. |
| 301 | var respJSON struct { |
| 302 | Out string |
| 303 | } |
| 304 | respJSON.Out = outStr |
| 305 | |
| 306 | data, _ := json.Marshal(respJSON) // can't fail |
| 307 | w.Write(data) // ignore error |
| 308 | } |
| 309 | |
| 310 | func formatObj(out *strings.Builder, fset *token.FileSet, ref string, obj types.Object) { |
| 311 | // e.g. *types.Func -> "func" |
| 312 | kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types.")) |
| 313 | |
| 314 | // Show origin of generics, and refine kind. |
| 315 | var origin types.Object |
| 316 | switch obj := obj.(type) { |
| 317 | case *types.Var: |
| 318 | if obj.IsField() { |
| 319 | kind = "field" |
| 320 | } |
| 321 | origin = obj.Origin() |
| 322 | |
| 323 | case *types.Func: |
| 324 | if recv := obj.Signature().Recv(); recv != nil { |
| 325 | kind = fmt.Sprintf("method (with recv %v)", recv.Type()) |
| 326 | } |
| 327 | origin = obj.Origin() |
| 328 | |
| 329 | case *types.TypeName: |
| 330 | if obj.IsAlias() { |
| 331 | kind = "type alias" |
| 332 | } |
| 333 | if named, ok := types.Unalias(obj.Type()).(*types.Named); ok { |
| 334 | origin = named.Obj() |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // Include the pointer value to help distinguish fn and fn.Origin(). |
| 339 | // (Beware that every invocation creates new pointers so they are |
| 340 | // only comparable within a single result page. Hence the need |
| 341 | // for the inventory of objects below.) |
| 342 | fmt.Fprintf(out, "%s of %s %s of type %v declared at %v (%p)", |
| 343 | ref, kind, obj.Name(), obj.Type(), fset.Position(obj.Pos()), obj) |
| 344 | if origin != nil && origin != obj { |
| 345 | fmt.Fprintf(out, " (instantiation of %v)", origin.Type()) |
| 346 | } |
| 347 | fmt.Fprintf(out, "\n\n") |
| 348 | |
| 349 | fmt.Fprintf(out, "Type:\n") |
| 350 | describeType(out, obj.Type()) |
| 351 | fmt.Fprintf(out, "\n") |
| 352 | |
| 353 | // method set |
| 354 | if methods := typeutil.IntuitiveMethodSet(obj.Type(), nil); len(methods) > 0 { |
| 355 | fmt.Fprintf(out, "Methods:\n") |
| 356 | for _, m := range methods { |
| 357 | fmt.Fprintln(out, m) |
| 358 | } |
| 359 | fmt.Fprintf(out, "\n") |
| 360 | } |
| 361 | |
| 362 | // scope tree |
| 363 | fmt.Fprintf(out, "Scopes:\n") |
| 364 | for scope := obj.Parent(); scope != nil; scope = scope.Parent() { |
| 365 | var ( |
| 366 | start = fset.Position(scope.Pos()) |
| 367 | end = fset.Position(scope.End()) |
| 368 | ) |
| 369 | fmt.Fprintf(out, "%d:%d-%d:%d: %s\n", |
| 370 | start.Line, start.Column, end.Line, end.Column, scope) |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | // describeType formats t to out in a way that makes it clear what methods to call on t to |
| 375 | // get at its parts. |
| 376 | // describeType assumes t was constructed by the type checker, so it doesn't check |
| 377 | // for recursion. The type checker replaces recursive alias types, which are illegal, |
| 378 | // with a BasicType that says as much. Other types that it constructs are recursive |
| 379 | // only via a name, and this function does not traverse names. |
| 380 | func describeType(out *strings.Builder, t types.Type) { |
| 381 | depth := -1 |
| 382 | |
| 383 | var ft func(string, types.Type) |
| 384 | ft = func(prefix string, t types.Type) { |
| 385 | depth++ |
| 386 | defer func() { depth-- }() |
| 387 | |
| 388 | for range depth { |
| 389 | fmt.Fprint(out, ". ") |
| 390 | } |
| 391 | |
| 392 | fmt.Fprintf(out, "%s%T:", prefix, t) |
| 393 | switch t := t.(type) { |
| 394 | case *types.Basic: |
| 395 | fmt.Fprintf(out, " Name: %q\n", t.Name()) |
| 396 | case *types.Pointer: |
| 397 | fmt.Fprintln(out) |
| 398 | ft("Elem: ", t.Elem()) |
| 399 | case *types.Slice: |
| 400 | fmt.Fprintln(out) |
| 401 | ft("Elem: ", t.Elem()) |
| 402 | case *types.Array: |
| 403 | fmt.Fprintf(out, " Len: %d\n", t.Len()) |
| 404 | ft("Elem: ", t.Elem()) |
| 405 | case *types.Map: |
| 406 | fmt.Fprintln(out) |
| 407 | ft("Key: ", t.Key()) |
| 408 | ft("Elem: ", t.Elem()) |
| 409 | case *types.Chan: |
| 410 | fmt.Fprintf(out, " Dir: %s\n", chanDirs[t.Dir()]) |
| 411 | ft("Elem: ", t.Elem()) |
| 412 | case *types.Alias: |
| 413 | fmt.Fprintf(out, " Name: %q\n", t.Obj().Name()) |
| 414 | ft("Rhs: ", t.Rhs()) |
| 415 | default: |
| 416 | // For types we may have missed or which have too much to bother with, |
| 417 | // print their string representation. |
| 418 | // TODO(jba): print more about struct types (their fields) and interface and named |
| 419 | // types (their methods). |
| 420 | fmt.Fprintf(out, " %s\n", t) |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | ft("", t) |
| 425 | } |
| 426 | |
| 427 | var chanDirs = []string{ |
| 428 | "SendRecv", |
| 429 | "SendOnly", |
| 430 | "RecvOnly", |
| 431 | } |
| 432 | |
| 433 | func handleRoot(w http.ResponseWriter, req *http.Request) { io.WriteString(w, mainHTML) } |
| 434 | func handleJS(w http.ResponseWriter, req *http.Request) { io.WriteString(w, mainJS) } |
| 435 | func handleCSS(w http.ResponseWriter, req *http.Request) { io.WriteString(w, mainCSS) } |
| 436 | |
| 437 | // TODO(adonovan): avoid CSS reliance on quirks mode and enable strict mode (<!DOCTYPE html>). |
| 438 | const mainHTML = `<html> |
| 439 | <head> |
| 440 | <script src="/main.js"></script> |
| 441 | <link rel="stylesheet" href="/main.css"></link> |
| 442 | </head> |
| 443 | <body onload="onLoad()"> |
| 444 | <h1>go/types playground</h1> |
| 445 | <p>Select an expression to see information about it.</p> |
| 446 | <textarea rows='25' id='src'> |
| 447 | package main |
| 448 | |
| 449 | import "fmt" |
| 450 | |
| 451 | func main() { |
| 452 | fmt.Println("Hello, world!") |
| 453 | } |
| 454 | </textarea> |
| 455 | <div id='out'/> |
| 456 | </body> |
| 457 | </html> |
| 458 | ` |
| 459 | |
| 460 | const mainJS = ` |
| 461 | function onSelectionChange() { |
| 462 | var start = document.activeElement.selectionStart; |
| 463 | var end = document.activeElement.selectionEnd; |
| 464 | var req = new XMLHttpRequest(); |
| 465 | req.open("POST", "/select.json?start=" + start + "&end=" + end, false); |
| 466 | req.send(document.activeElement.value); |
| 467 | var resp = JSON.parse(req.responseText); |
| 468 | document.getElementById('out').innerText = resp.Out; |
| 469 | } |
| 470 | |
| 471 | function onLoad() { |
| 472 | document.getElementById("src").addEventListener('select', onSelectionChange) |
| 473 | } |
| 474 | ` |
| 475 | |
| 476 | const mainCSS = ` |
| 477 | textarea { width: 6in; } |
| 478 | body { color: gray; } |
| 479 | div#out { font-family: monospace; font-size: 80%; } |
| 480 | ` |