Debian Codegraph @

go/types/internal/play/play.go

raw symbols SCIP
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
268 if inst, ok := pkg.TypesInfo.Instances[n]; ok {
269 fmt.Fprintf(out, "Instances[ident] = %v.\n\n", inst)
270 }
271
272 default:
273 if obj, ok := pkg.TypesInfo.Implicits[n]; ok {
274 formatObj(out, fset, "implicit def", obj)
275 }
276 }
277 fmt.Fprintf(out, "\n")
278
279 // Pretty-print of selected syntax.
280 fmt.Fprintf(out, "Pretty-printed:\n")
281 format.Node(out, fset, path[0])
282 fmt.Fprintf(out, "\n\n")
283
284 // Syntax debug output.
285 fmt.Fprintf(out, "Syntax:\n")
286 ast.Fprint(out, fset, path[0], nil) // ignore errors
287 fmt.Fprintf(out, "\n\n")
288
289 // Show inventory of all objects, including addresses to disambiguate.
290 fmt.Fprintf(out, "Objects:\n")
291 for curId := range curFile.Preorder((*ast.Ident)(nil)) {
292 id := curId.Node().(*ast.Ident)
293 if obj := pkg.TypesInfo.Defs[id]; obj != nil {
294 fmt.Fprintf(out, "%s: def %v (%p)\n", fset.Position(id.Pos()), obj, obj)
295 }
296 if obj, ok := pkg.TypesInfo.Uses[id]; ok {
297 fmt.Fprintf(out, "%s: use %v (%p)\n", fset.Position(id.Pos()), obj, obj)
298 }
299 }
300 fmt.Fprintf(out, "\n\n")
301
302 // Clean up the messy temp file name.
303 outStr := strings.ReplaceAll(out.String(), f.Name(), "play.go")
304
305 // Send response.
306 var respJSON struct {
307 Out string
308 }
309 respJSON.Out = outStr
310
311 data, _ := json.Marshal(respJSON) // can't fail
312 w.Write(data) // ignore error
313 }
314
315 func formatObj(out *strings.Builder, fset *token.FileSet, ref string, obj types.Object) {
316 // e.g. *types.Func -> "func"
317 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
318
319 // Show origin of generics, and refine kind.
320 var origin types.Object
321 switch obj := obj.(type) {
322 case *types.Var:
323 if obj.IsField() {
324 kind = "field"
325 }
326 origin = obj.Origin()
327
328 case *types.Func:
329 if recv := obj.Signature().Recv(); recv != nil {
330 kind = fmt.Sprintf("method (with recv %v)", recv.Type())
331 }
332 origin = obj.Origin()
333
334 case *types.TypeName:
335 if obj.IsAlias() {
336 kind = "type alias"
337 }
338 if named, ok := types.Unalias(obj.Type()).(*types.Named); ok {
339 origin = named.Obj()
340 }
341 }
342
343 // Include the pointer value to help distinguish fn and fn.Origin().
344 // (Beware that every invocation creates new pointers so they are
345 // only comparable within a single result page. Hence the need
346 // for the inventory of objects below.)
347 fmt.Fprintf(out, "%s of %s %s of type %v declared at %v (%p)",
348 ref, kind, obj.Name(), obj.Type(), fset.Position(obj.Pos()), obj)
349 if origin != nil && origin != obj {
350 fmt.Fprintf(out, " (instantiation of %v)", origin.Type())
351 }
352 fmt.Fprintf(out, "\n\n")
353
354 fmt.Fprintf(out, "Type:\n")
355 describeType(out, obj.Type())
356 fmt.Fprintf(out, "\n")
357
358 // method set
359 if methods := typeutil.IntuitiveMethodSet(obj.Type(), nil); len(methods) > 0 {
360 fmt.Fprintf(out, "Methods:\n")
361 for _, m := range methods {
362 fmt.Fprintln(out, m)
363 }
364 fmt.Fprintf(out, "\n")
365 }
366
367 // scope tree
368 fmt.Fprintf(out, "Scopes:\n")
369 for scope := obj.Parent(); scope != nil; scope = scope.Parent() {
370 var (
371 start = fset.Position(scope.Pos())
372 end = fset.Position(scope.End())
373 )
374 fmt.Fprintf(out, "%d:%d-%d:%d: %s\n",
375 start.Line, start.Column, end.Line, end.Column, scope)
376 }
377 }
378
379 // describeType formats t to out in a way that makes it clear what methods to call on t to
380 // get at its parts.
381 // describeType assumes t was constructed by the type checker, so it doesn't check
382 // for recursion. The type checker replaces recursive alias types, which are illegal,
383 // with a BasicType that says as much. Other types that it constructs are recursive
384 // only via a name, and this function does not traverse names.
385 func describeType(out *strings.Builder, t types.Type) {
386 depth := -1
387
388 var ft func(string, types.Type)
389 ft = func(prefix string, t types.Type) {
390 depth++
391 defer func() { depth-- }()
392
393 for range depth {
394 fmt.Fprint(out, ". ")
395 }
396
397 fmt.Fprintf(out, "%s%T:", prefix, t)
398 switch t := t.(type) {
399 case *types.Basic:
400 fmt.Fprintf(out, " Name: %q\n", t.Name())
401 case *types.Pointer:
402 fmt.Fprintln(out)
403 ft("Elem: ", t.Elem())
404 case *types.Slice:
405 fmt.Fprintln(out)
406 ft("Elem: ", t.Elem())
407 case *types.Array:
408 fmt.Fprintf(out, " Len: %d\n", t.Len())
409 ft("Elem: ", t.Elem())
410 case *types.Map:
411 fmt.Fprintln(out)
412 ft("Key: ", t.Key())
413 ft("Elem: ", t.Elem())
414 case *types.Chan:
415 fmt.Fprintf(out, " Dir: %s\n", chanDirs[t.Dir()])
416 ft("Elem: ", t.Elem())
417 case *types.Alias:
418 fmt.Fprintf(out, " Name: %q\n", t.Obj().Name())
419 ft("Rhs: ", t.Rhs())
420 default:
421 // For types we may have missed or which have too much to bother with,
422 // print their string representation.
423 // TODO(jba): print more about struct types (their fields) and interface and named
424 // types (their methods).
425 fmt.Fprintf(out, " %s\n", t)
426 }
427 }
428
429 ft("", t)
430 }
431
432 var chanDirs = []string{
433 "SendRecv",
434 "SendOnly",
435 "RecvOnly",
436 }
437
438 func handleRoot(w http.ResponseWriter, req *http.Request) { io.WriteString(w, mainHTML) }
439 func handleJS(w http.ResponseWriter, req *http.Request) { io.WriteString(w, mainJS) }
440 func handleCSS(w http.ResponseWriter, req *http.Request) { io.WriteString(w, mainCSS) }
441
442 // TODO(adonovan): avoid CSS reliance on quirks mode and enable strict mode (<!DOCTYPE html>).
443 const mainHTML = `<html>
444 <head>
445 <script src="/main.js"></script>
446 <link rel="stylesheet" href="/main.css"></link>
447 </head>
448 <body onload="onLoad()">
449 <h1>go/types playground</h1>
450 <p>Select an expression to see information about it.</p>
451 <textarea rows='25' id='src'>
452 package main
453
454 import "fmt"
455
456 func main() {
457 fmt.Println("Hello, world!")
458 }
459 </textarea>
460 <div id='out'/>
461 </body>
462 </html>
463 `
464
465 const mainJS = `
466 function onSelectionChange() {
467 var start = document.activeElement.selectionStart;
468 var end = document.activeElement.selectionEnd;
469 var req = new XMLHttpRequest();
470 req.open("POST", "/select.json?start=" + start + "&end=" + end, false);
471 req.send(document.activeElement.value);
472 var resp = JSON.parse(req.responseText);
473 document.getElementById('out').innerText = resp.Out;
474 }
475
476 function onLoad() {
477 document.getElementById("src").addEventListener('select', onSelectionChange)
478 }
479 `
480
481 const mainCSS = `
482 textarea { width: 6in; }
483 body { color: gray; }
484 div#out { font-family: monospace; font-size: 80%; }
485 `