Debian Codegraph @

gopls/internal/golang/pkgdoc.go

raw symbols SCIP
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 golang
6
7 // This file defines a simple HTML rendering of package documentation
8 // in imitation of the style of pkg.go.dev.
9 //
10 // The current implementation is just a starting point and a
11 // placeholder for a more sophisticated one.
12 //
13 // TODO(adonovan):
14 // - rewrite using html/template.
15 // Or factor with golang.org/x/pkgsite/internal/godoc/dochtml.
16 // - emit breadcrumbs for parent + sibling packages.
17 // - list promoted methods---we have type information! (golang/go#67158)
18 // - gather Example tests, following go/doc and pkgsite.
19 // - add option for doc.AllDecls: show non-exported symbols too.
20 // - style the <li> bullets in the index as invisible.
21 // - add push notifications such as didChange -> reload.
22 // - there appears to be a maximum file size beyond which the
23 // "source.doc" code action is not offered. Remove that.
24 // - modify JS httpGET function to give a transient visual indication
25 // when clicking a source link that the editor is being navigated
26 // (in case it doesn't raise itself, like VS Code).
27 // - move this into a new package, golang/web, and then
28 // split out the various helpers without fear of polluting
29 // the golang package namespace?
30 // - show "Deprecated" chip when appropriate.
31
32 import (
33 "bytes"
34 "fmt"
35 "go/ast"
36 "go/doc"
37 "go/doc/comment"
38 "go/format"
39 "go/token"
40 "go/types"
41 "html"
42 "path/filepath"
43 "slices"
44 "strings"
45
46 "golang.org/x/tools/gopls/internal/cache"
47 "golang.org/x/tools/gopls/internal/cache/parsego"
48 "golang.org/x/tools/gopls/internal/protocol"
49 "golang.org/x/tools/gopls/internal/util/bug"
50 "golang.org/x/tools/gopls/internal/util/cursorutil"
51 "golang.org/x/tools/internal/astutil"
52 "golang.org/x/tools/internal/stdlib"
53 "golang.org/x/tools/internal/typesinternal"
54 )
55
56 // DocFragment finds the package and (optionally) symbol identified by
57 // the current selection, and returns the package path and the
58 // optional symbol URL fragment (e.g. "#Buffer.Len") for a symbol,
59 // along with a title for the code action.
60 //
61 // It is called once to offer the code action, and again when the
62 // command is executed. This is slightly inefficient but ensures that
63 // the title and package/symbol logic are consistent in all cases.
64 //
65 // It returns zeroes if there is nothing to see here (e.g. reference to a builtin).
66 func DocFragment(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (pkgpath PackagePath, fragment, title string) {
67 thing := thingAtPoint(pkg, pgf, start, end)
68
69 makeTitle := func(kind string, imp *types.Package, name string) string {
70 title := "Browse documentation for " + kind + " "
71 if imp != nil && imp != pkg.Types() {
72 title += imp.Name() + "."
73 }
74 return title + name
75 }
76
77 wholePackage := func(pkg *types.Package) (PackagePath, string, string) {
78 // External test packages don't have /pkg doc pages,
79 // so instead show the doc for the package under test.
80 // (This named-based heuristic is imperfect.)
81 if forTest, ok := strings.CutSuffix(pkg.Path(), "_test"); ok {
82 return PackagePath(forTest), "", makeTitle("package", nil, filepath.Base(forTest))
83 }
84
85 return PackagePath(pkg.Path()), "", makeTitle("package", nil, pkg.Name())
86 }
87
88 // Conceptually, we check cases in the order:
89 // 1. symbol
90 // 2. package
91 // 3. enclosing
92 // but the logic of cases 1 and 3 are identical, hence the odd factoring.
93
94 // Imported package?
95 if thing.pkg != nil && thing.symbol == nil {
96 return wholePackage(thing.pkg)
97 }
98
99 // Symbol?
100 var sym types.Object
101 if thing.symbol != nil {
102 sym = thing.symbol // reference to a symbol
103 } else if thing.enclosing != nil {
104 sym = thing.enclosing // selection is within a declaration of a symbol
105 }
106 if sym == nil {
107 return wholePackage(pkg.Types()) // no symbol
108 }
109
110 // Built-in (error.Error, append or unsafe).
111 // TODO(adonovan): handle builtins in /pkg viewer.
112 if sym.Pkg() == nil {
113 return "", "", "" // nothing to see here
114 }
115 pkgpath = PackagePath(sym.Pkg().Path())
116
117 // Unexported? Show enclosing type or package.
118 if !sym.Exported() {
119 // Unexported method of exported type?
120 if fn, ok := sym.(*types.Func); ok {
121 if recv := fn.Signature().Recv(); recv != nil {
122 _, named := typesinternal.ReceiverNamed(recv)
123 if named != nil && named.Obj().Exported() {
124 sym = named.Obj()
125 goto below
126 }
127 }
128 }
129
130 return wholePackage(sym.Pkg())
131 below:
132 }
133
134 // Reference to symbol in external test package?
135 // Short-circuit: see comment in wholePackage.
136 if strings.HasSuffix(string(pkgpath), "_test") {
137 return wholePackage(pkg.Types())
138 }
139
140 // package-level symbol?
141 if typesinternal.IsPackageLevel(sym) {
142 return pkgpath, sym.Name(), makeTitle(objectKind(sym), sym.Pkg(), sym.Name())
143 }
144
145 // Inv: sym is field or method, or local.
146 switch sym := sym.(type) {
147 case *types.Func: // => method
148 sig := sym.Signature()
149 isPtr, named := typesinternal.ReceiverNamed(sig.Recv())
150 if named != nil {
151 if !named.Obj().Exported() {
152 return wholePackage(sym.Pkg()) // exported method of unexported type
153 }
154 name := fmt.Sprintf("(%s%s).%s",
155 strings.Repeat("*", btoi(isPtr)), // for *T
156 named.Obj().Name(),
157 sym.Name())
158 fragment := named.Obj().Name() + "." + sym.Name()
159 return pkgpath, fragment, makeTitle("method", sym.Pkg(), name)
160 }
161
162 case *types.Var:
163 if sym.IsField() {
164 // TODO(adonovan): support fields.
165 // The Var symbol doesn't include the struct
166 // type, so we need to use the logic from
167 // Hover. (This isn't important for
168 // DocFragment as fields don't have fragments,
169 // but it matters to the grand unification of
170 // Hover/Definition/DocFragment.
171 }
172 }
173
174 // Field, non-exported method, or local declaration:
175 // just show current package.
176 return wholePackage(pkg.Types())
177 }
178
179 // thing describes the package or symbol denoted by a selection.
180 //
181 // TODO(adonovan): Hover, Definition, and References all start by
182 // identifying the selected object. Let's achieve a better factoring
183 // of the common parts using this structure, including uniform
184 // treatment of doc links, linkname, and suchlike.
185 type thing struct {
186 // At most one of these fields is set.
187 // (The 'enclosing' field is a fallback for when neither
188 // of the first two is set.)
189 symbol types.Object // referenced symbol
190 pkg *types.Package // referenced package
191 enclosing types.Object // package-level symbol or method decl enclosing selection
192 }
193
194 func thingAtPoint(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) thing {
195 cur, _, _, _ := astutil.Select(pgf.Cursor(), start, end)
196
197 // In an import spec?
198 if spec, _ := cursorutil.FirstEnclosing[*ast.ImportSpec](cur); spec != nil {
199 if pkgname := pkg.TypesInfo().PkgNameOf(spec); pkgname != nil {
200 return thing{pkg: pkgname.Imported()}
201 }
202 }
203
204 // Definition or reference to symbol?
205 var obj types.Object
206 if id, ok := cur.Node().(*ast.Ident); ok {
207 obj = pkg.TypesInfo().ObjectOf(id)
208
209 // Treat use to PkgName like ImportSpec.
210 if pkgname, ok := obj.(*types.PkgName); ok {
211 return thing{pkg: pkgname.Imported()}
212 }
213
214 } else if sel, ok := cur.Node().(*ast.SelectorExpr); ok {
215 // e.g. selection is "fmt.Println" or just a portion ("mt.Prin")
216 obj = pkg.TypesInfo().Uses[sel.Sel]
217 }
218 if obj != nil {
219 return thing{symbol: obj}
220 }
221
222 // Find outermost enclosing declaration.
223 var id *ast.Ident
224 for cur := range cur.Enclosing((*ast.FuncDecl)(nil), (*ast.ValueSpec)(nil), (*ast.TypeSpec)(nil)) {
225 switch n := cur.Node().(type) {
226 case *ast.FuncDecl: // function or method
227 id = n.Name
228 case *ast.ValueSpec:
229 id = n.Names[0] // var, const: use first name
230 case *ast.TypeSpec:
231 id = n.Name
232 }
233 }
234 if obj := pkg.TypesInfo().Defs[id]; obj != nil {
235 return thing{enclosing: obj}
236 }
237
238 return thing{} // nothing to see here
239 }
240
241 // Web is an abstraction of gopls' web server.
242 type Web interface {
243 // PkgURL forms URLs of package or symbol documentation.
244 PkgURL(viewID string, path PackagePath, fragment string) protocol.URI
245
246 // SrcURL forms URLs that cause the editor to open a file at a specific position.
247 SrcURL(filename string, line, col8 int) protocol.URI
248 }
249
250 // PackageDocHTML formats the package documentation page.
251 //
252 // The posURL function returns a URL that when visited, has the side
253 // effect of causing gopls to direct the client editor to navigate to
254 // the specified file/line/column position, in UTF-8 coordinates.
255 //
256 // TODO(adonovan): this function could use some unit tests; we
257 // shouldn't have to use integration tests to cover microdetails of
258 // HTML rendering. (It is tempting to abstract this function so that
259 // it depends only on FileSet/File/Types/TypeInfo/etc, but we should
260 // bend the tests to the production interfaces, not the other way
261 // around.)
262 func PackageDocHTML(viewID string, pkg *cache.Package, web Web) ([]byte, error) {
263 // We can't use doc.NewFromFiles (even with doc.PreserveAST
264 // mode) as it calls ast.NewPackage which assumes that each
265 // ast.File has an ast.Scope and resolves identifiers to
266 // (deprecated) ast.Objects. (This is golang/go#66290.)
267 // But doc.New only requires pkg.{Name,Files},
268 // so we just boil it down.
269 //
270 // The only loss is doc.classifyExamples.
271 // TODO(adonovan): simulate that too.
272 fileMap := make(map[string]*ast.File)
273 for _, f := range pkg.Syntax() {
274 fileMap[pkg.FileSet().File(f.FileStart).Name()] = f
275 }
276 astpkg := &ast.Package{
277 Name: pkg.Types().Name(),
278 Files: fileMap,
279 }
280 // PreserveAST mode only half works (golang/go#66449): it still
281 // mutates ASTs when filtering out non-exported symbols.
282 // As a workaround, enable AllDecls to suppress filtering,
283 // and do it ourselves.
284 mode := doc.PreserveAST | doc.AllDecls
285 docpkg := doc.New(astpkg, pkg.Types().Path(), mode)
286
287 // Discard non-exported symbols.
288 // TODO(adonovan): do this conditionally, and expose option in UI.
289 const showUnexported = false
290 if !showUnexported {
291 var (
292 unexported = func(name string) bool { return !token.IsExported(name) }
293 filterValues = func(slice *[]*doc.Value) {
294 delValue := func(v *doc.Value) bool {
295 v.Names = slices.DeleteFunc(v.Names, unexported)
296 return len(v.Names) == 0
297 }
298 *slice = slices.DeleteFunc(*slice, delValue)
299 }
300 filterFuncs = func(funcs *[]*doc.Func) {
301 *funcs = slices.DeleteFunc(*funcs, func(v *doc.Func) bool {
302 return unexported(v.Name)
303 })
304 }
305 )
306 filterValues(&docpkg.Consts)
307 filterValues(&docpkg.Vars)
308 filterFuncs(&docpkg.Funcs)
309 docpkg.Types = slices.DeleteFunc(docpkg.Types, func(t *doc.Type) bool {
310 filterValues(&t.Consts)
311 filterValues(&t.Vars)
312 filterFuncs(&t.Funcs)
313 filterFuncs(&t.Methods)
314 if unexported(t.Name) {
315 // If an unexported type has an exported constructor function,
316 // treat the constructor as an ordinary standalone function.
317 // We will sort Funcs again below.
318 docpkg.Funcs = append(docpkg.Funcs, t.Funcs...)
319 return true // delete this type
320 }
321 return false // keep this type
322 })
323 slices.SortFunc(docpkg.Funcs, func(x, y *doc.Func) int {
324 return strings.Compare(x.Name, y.Name)
325 })
326 }
327
328 // docHTML renders the doc comment as Markdown.
329 // The fileNode is used to deduce the enclosing file
330 // for the correct import mapping.
331 //
332 // It is not concurrency-safe.
333 var docHTML func(fileNode ast.Node, comment string) []byte
334 {
335 // Adapt doc comment parser and printer
336 // to our representation of Go packages
337 // so that doc links (e.g. "[fmt.Println]")
338 // become valid links.
339 printer := &comment.Printer{
340 DocLinkURL: func(link *comment.DocLink) string {
341 path := pkg.Metadata().PkgPath
342 if link.ImportPath != "" {
343 path = PackagePath(link.ImportPath)
344 }
345 fragment := link.Name
346 if link.Recv != "" {
347 fragment = link.Recv + "." + link.Name
348 }
349 return web.PkgURL(viewID, path, fragment)
350 },
351 }
352 parse := newDocCommentParser(pkg)
353 docHTML = func(fileNode ast.Node, comment string) []byte {
354 doc := parse(fileNode, comment)
355 return printer.HTML(doc)
356 }
357 }
358
359 scope := pkg.Types().Scope()
360 escape := html.EscapeString
361
362 title := fmt.Sprintf("%s package - %s - Gopls packages",
363 pkg.Types().Name(), escape(pkg.Types().Path()))
364
365 var buf bytes.Buffer
366 buf.WriteString(`<!DOCTYPE html>
367 <html>
368 <head>
369 <meta charset="UTF-8">
370 <title>` + title + `</title>
371 <link rel="stylesheet" href="/assets/common.css">
372 <script src="/assets/common.js"></script>
373 <style>
374 .lit { color: darkgreen; }
375
376 header {
377 position: sticky;
378 top: 0;
379 left: 0;
380 width: 100%;
381 padding: 0.3em;
382 }
383
384 .Documentation-sinceVersion {
385 font-weight: normal;
386 color: #808080;
387 float: right;
388 }
389
390 #pkgsite { height: 1.5em; }
391
392 #hdr-Selector {
393 margin-right: 0.3em;
394 float: right;
395 min-width: 25em;
396 padding: 0.3em;
397 }
398 </style>
399 <script type='text/javascript'>
400 window.addEventListener('load', function() {
401 // Hook up the navigation selector.
402 document.getElementById('hdr-Selector').onchange = (e) => {
403 window.location.href = e.target.value;
404 };
405 });
406 </script>
407 </head>
408 <body>
409 <header>
410 <select id='hdr-Selector'>
411 <optgroup label="Documentation">
412 <option label="Overview" value="#hdr-Overview"/>
413 <option label="Index" value="#hdr-Index"/>
414 <option label="Constants" value="#hdr-Constants"/>
415 <option label="Variables" value="#hdr-Variables"/>
416 <option label="Functions" value="#hdr-Functions"/>
417 <option label="Types" value="#hdr-Types"/>
418 <option label="Source Files" value="#hdr-SourceFiles"/>
419 </optgroup>
420 `)
421
422 // -- header select element --
423
424 // option emits an <option> for the specified symbol.
425 //
426 // recvType is the apparent receiver type, which may
427 // differ from ReceiverNamed(obj.Signature.Recv).Name
428 // for promoted methods.
429 option := func(obj types.Object, recvType string) {
430 // Render functions/methods as "(recv) Method(p1, ..., pN)".
431 fragment := obj.Name()
432
433 // format parameter names (p1, ..., pN)
434 label := obj.Name() // for a type
435 if fn, ok := obj.(*types.Func); ok {
436 var buf strings.Builder
437 sig := fn.Signature()
438 if sig.Recv() != nil {
439 fmt.Fprintf(&buf, "(%s) ", sig.Recv().Name())
440 fragment = recvType + "." + fn.Name()
441 }
442 fmt.Fprintf(&buf, "%s(", fn.Name())
443 for i := 0; i < sig.Params().Len(); i++ {
444 if i > 0 {
445 buf.WriteString(", ")
446 }
447 name := sig.Params().At(i).Name()
448 if name == "" {
449 name = "_"
450 }
451 buf.WriteString(name)
452 }
453 buf.WriteByte(')')
454 label = buf.String()
455 }
456
457 fmt.Fprintf(&buf, " <option label='%s' value='#%s'/>\n", label, fragment)
458 }
459
460 // index of functions
461 fmt.Fprintf(&buf, "<optgroup label='Functions'>\n")
462 for _, fn := range docpkg.Funcs {
463 option(scope.Lookup(fn.Name), "")
464 }
465 fmt.Fprintf(&buf, "</optgroup>\n")
466
467 // index of types
468 fmt.Fprintf(&buf, "<optgroup label='Types'>\n")
469 for _, doctype := range docpkg.Types {
470 option(scope.Lookup(doctype.Name), "")
471 }
472 fmt.Fprintf(&buf, "</optgroup>\n")
473
474 // index of constructors and methods of each type
475 for _, doctype := range docpkg.Types {
476 tname := scope.Lookup(doctype.Name).(*types.TypeName)
477 if len(doctype.Funcs)+len(doctype.Methods) > 0 {
478 fmt.Fprintf(&buf, "<optgroup label='type %s'>\n", doctype.Name)
479 for _, docfn := range doctype.Funcs {
480 option(scope.Lookup(docfn.Name), "")
481 }
482 for _, docmethod := range doctype.Methods {
483 method, _, _ := types.LookupFieldOrMethod(tname.Type(), true, tname.Pkg(), docmethod.Name)
484 option(method, doctype.Name)
485 }
486 fmt.Fprintf(&buf, "</optgroup>\n")
487 }
488 }
489 fmt.Fprintf(&buf, "</select>\n")
490 fmt.Fprintf(&buf, "</header>\n")
491
492 // -- main element --
493
494 // nodeHTML returns HTML markup for a syntax tree.
495 // It replaces referring identifiers with links,
496 // and adds style spans for strings and comments.
497 nodeHTML := func(n ast.Node) string {
498
499 // linkify returns the appropriate URL (if any) for an identifier.
500 linkify := func(id *ast.Ident) protocol.URI {
501 if obj, ok := pkg.TypesInfo().Uses[id]; ok && obj.Pkg() != nil {
502 // imported package name?
503 if pkgname, ok := obj.(*types.PkgName); ok {
504 // TODO(adonovan): do this for Defs of PkgName too.
505 return web.PkgURL(viewID, PackagePath(pkgname.Imported().Path()), "")
506 }
507
508 // package-level symbol?
509 if obj.Parent() == obj.Pkg().Scope() {
510 if obj.Pkg() == pkg.Types() {
511 return "#" + obj.Name() // intra-package ref
512 } else {
513 return web.PkgURL(viewID, PackagePath(obj.Pkg().Path()), obj.Name())
514 }
515 }
516
517 // method of package-level named type?
518 if fn, ok := obj.(*types.Func); ok {
519 sig := fn.Signature()
520 if sig.Recv() != nil {
521 _, named := typesinternal.ReceiverNamed(sig.Recv())
522 if named != nil {
523 fragment := named.Obj().Name() + "." + fn.Name()
524 return web.PkgURL(viewID, PackagePath(fn.Pkg().Path()), fragment)
525 }
526 }
527 return ""
528 }
529
530 // TODO(adonovan): field of package-level named struct type.
531 // (Requires an index, since there's no way to
532 // get from Var to Named.)
533 }
534 return ""
535 }
536
537 // Splice spans into HTML-escaped segments of the
538 // original source buffer (which is usually but not
539 // necessarily formatted).
540 //
541 // (For expedience we don't use the more sophisticated
542 // approach taken by cmd/godoc and pkgsite's render
543 // package, which emit the text, spans, and comments
544 // in one traversal of the syntax tree.)
545 //
546 // TODO(adonovan): splice styled spans around comments too.
547 //
548 // TODO(adonovan): pkgsite prints specs from grouped
549 // type decls like "type ( T1; T2 )" to make them
550 // appear as separate decls. We should too.
551 var buf bytes.Buffer
552 for _, file := range pkg.CompiledGoFiles() {
553 if astutil.NodeContainsPos(file.File, n.Pos()) {
554 pos := n.Pos()
555
556 // emit emits source in the interval [pos:to] and updates pos.
557 emit := func(to token.Pos) {
558 // Ident and BasicLit always have a valid pos.
559 // (Failure means the AST has been corrupted.)
560 if !to.IsValid() {
561 bug.Reportf("invalid Pos")
562 }
563 text, err := file.PosText(pos, to)
564 if err != nil {
565 bug.Reportf("invalid pos range: %v", err)
566 return
567 }
568 buf.WriteString(escape(string(text)))
569 pos = to
570 }
571 ast.Inspect(n, func(n ast.Node) bool {
572 switch n := n.(type) {
573 case *ast.Ident:
574 emit(n.Pos())
575 pos = n.End()
576 if url := linkify(n); url != "" {
577 fmt.Fprintf(&buf, "<a class='id' href='%s'>%s</a>", url, escape(n.Name))
578 } else {
579 buf.WriteString(escape(n.Name)) // plain
580 }
581
582 case *ast.BasicLit:
583 emit(n.Pos())
584 pos = n.End()
585 fmt.Fprintf(&buf, "<span class='lit'>%s</span>", escape(n.Value))
586 }
587 return true
588 })
589 emit(n.End())
590 return buf.String()
591 }
592 }
593
594 // Original source not found.
595 // Format the node without adornments.
596 if err := format.Node(&buf, pkg.FileSet(), n); err != nil {
597 // e.g. BadDecl?
598 buf.Reset()
599 fmt.Fprintf(&buf, "formatting error: %v", err)
600 }
601 return escape(buf.String())
602 }
603
604 // fnString is like fn.String() except that it:
605 // - shows the receiver name;
606 // - uses space "(T) M()" not dot "(T).M()" after receiver;
607 // - doesn't bother with the special case for interface receivers
608 // since it is unreachable for the methods in go/doc.
609 // - elides parameters after the first three: f(a, b, c, ...).
610 fnString := func(fn *types.Func) string {
611 pkgRelative := typesinternal.NameRelativeTo(pkg.Types())
612
613 sig := fn.Signature()
614
615 // Emit "func (recv T) F".
616 var buf bytes.Buffer
617 buf.WriteString("func ")
618 if recv := sig.Recv(); recv != nil {
619 buf.WriteByte('(')
620 if recv.Name() != "" {
621 buf.WriteString(recv.Name())
622 buf.WriteByte(' ')
623 }
624 types.WriteType(&buf, recv.Type(), pkgRelative)
625 buf.WriteByte(')')
626 buf.WriteByte(' ') // (ObjectString uses a '.' here)
627 } else if pkg := fn.Pkg(); pkg != nil {
628 if s := pkgRelative(pkg); s != "" {
629 buf.WriteString(s)
630 buf.WriteByte('.')
631 }
632 }
633 buf.WriteString(fn.Name())
634
635 // Emit signature.
636 //
637 // Elide parameters after the third one.
638 // WriteSignature is too complex to fork, so we replace
639 // parameters 4+ with "invalid type", format,
640 // then post-process the string.
641 if sig.Params().Len() > 3 {
642
643 // Clone each TypeParam as NewSignatureType modifies them (#67294).
644 cloneTparams := func(seq *types.TypeParamList) []*types.TypeParam {
645 slice := make([]*types.TypeParam, seq.Len())
646 for i := range slice {
647 tparam := seq.At(i)
648 slice[i] = types.NewTypeParam(tparam.Obj(), tparam.Constraint())
649 }
650 return slice
651 }
652
653 sig = types.NewSignatureType(
654 sig.Recv(),
655 cloneTparams(sig.RecvTypeParams()),
656 cloneTparams(sig.TypeParams()),
657 types.NewTuple(append(
658 slices.Collect(sig.Params().Variables())[:3],
659 types.NewParam(0, nil, "", types.Typ[types.Invalid]))...),
660 sig.Results(),
661 false) // any final ...T parameter is truncated
662 }
663 types.WriteSignature(&buf, sig, pkgRelative)
664 return strings.ReplaceAll(buf.String(), ", invalid type)", ", ...)")
665 }
666
667 fmt.Fprintf(&buf, "<main>\n")
668
669 // package name
670 fmt.Fprintf(&buf, "<h1 id='hdr-Overview'>Package %s</h1>\n", pkg.Types().Name())
671
672 // import path
673 fmt.Fprintf(&buf, "<pre class='code'>import %q</pre>\n", pkg.Types().Path())
674
675 // link to same package in pkg.go.dev
676 fmt.Fprintf(&buf, "<div><a href=%q title='View in pkg.go.dev'><img id='pkgsite' src='/assets/go-logo-blue.svg'/></a>\n",
677 "https://pkg.go.dev/"+string(pkg.Types().Path()))
678
679 // package doc
680 for _, f := range pkg.Syntax() {
681 if f.Doc != nil {
682 fmt.Fprintf(&buf, "<div class='comment'>%s</div>\n", docHTML(f.Doc, docpkg.Doc))
683 break
684 }
685 }
686
687 // symbol index
688 fmt.Fprintf(&buf, "<h2 id='hdr-Index'>Index</h2>\n")
689 fmt.Fprintf(&buf, "<ul>\n")
690 if len(docpkg.Consts) > 0 {
691 fmt.Fprintf(&buf, "<li><a href='#hdr-Constants'>Constants</a></li>\n")
692 }
693 if len(docpkg.Vars) > 0 {
694 fmt.Fprintf(&buf, "<li><a href='#hdr-Variables'>Variables</a></li>\n")
695 }
696 for _, fn := range docpkg.Funcs {
697 obj := scope.Lookup(fn.Name).(*types.Func)
698 fmt.Fprintf(&buf, "<li><a href='#%s'>%s</a></li>\n",
699 obj.Name(), escape(fnString(obj)))
700 }
701 for _, doctype := range docpkg.Types {
702 tname := scope.Lookup(doctype.Name).(*types.TypeName)
703 fmt.Fprintf(&buf, "<li><a href='#%[1]s'>type %[1]s</a></li>\n",
704 tname.Name())
705
706 if len(doctype.Funcs)+len(doctype.Methods) > 0 {
707 fmt.Fprintf(&buf, "<ul>\n")
708
709 // constructors
710 for _, docfn := range doctype.Funcs {
711 obj := scope.Lookup(docfn.Name).(*types.Func)
712 fmt.Fprintf(&buf, "<li><a href='#%s'>%s</a></li>\n",
713 docfn.Name, escape(fnString(obj)))
714 }
715 // methods
716 for _, docmethod := range doctype.Methods {
717 method, _, _ := types.LookupFieldOrMethod(tname.Type(), true, tname.Pkg(), docmethod.Name)
718 fmt.Fprintf(&buf, "<li><a href='#%s.%s'>%s</a></li>\n",
719 doctype.Name,
720 docmethod.Name,
721 escape(fnString(method.(*types.Func))))
722 }
723 fmt.Fprintf(&buf, "</ul>\n")
724 }
725 }
726 // TODO(adonovan): add index of Examples here.
727 fmt.Fprintf(&buf, "</ul>\n")
728
729 // constants and variables
730 values := func(vals []*doc.Value) {
731 for _, v := range vals {
732 // anchors
733 for _, name := range v.Names {
734 fmt.Fprintf(&buf, "<a id='%s'></a>\n", escape(name))
735 }
736
737 // declaration
738 decl2 := *v.Decl // shallow copy
739 decl2.Doc = nil
740 fmt.Fprintf(&buf, "<pre class='code'>%s</pre>\n", nodeHTML(&decl2))
741
742 // comment (if any)
743 fmt.Fprintf(&buf, "<div class='comment'>%s</div>\n", docHTML(v.Decl, v.Doc))
744 }
745 }
746 fmt.Fprintf(&buf, "<h2 id='hdr-Constants'>Constants</h2>\n")
747 if len(docpkg.Consts) == 0 {
748 fmt.Fprintf(&buf, "<div>(no constants)</div>\n")
749 } else {
750 values(docpkg.Consts)
751 }
752 fmt.Fprintf(&buf, "<h2 id='hdr-Variables'>Variables</h2>\n")
753 if len(docpkg.Vars) == 0 {
754 fmt.Fprintf(&buf, "<div>(no variables)</div>\n")
755 } else {
756 values(docpkg.Vars)
757 }
758
759 // addedInHTML returns an HTML division containing the Go release version at
760 // which this obj became available.
761 addedInHTML := func(obj types.Object) string {
762 if sym := StdSymbolOf(obj); sym != nil && sym.Version != stdlib.Version(0) {
763 return fmt.Sprintf("<span class='Documentation-sinceVersion'>added in %v</span>", sym.Version)
764 }
765 return ""
766 }
767
768 // package-level functions
769 fmt.Fprintf(&buf, "<h2 id='hdr-Functions'>Functions</h2>\n")
770 // funcs emits a list of package-level functions,
771 // possibly organized beneath the type they construct.
772 funcs := func(funcs []*doc.Func) {
773 for _, docfn := range funcs {
774 obj := scope.Lookup(docfn.Name).(*types.Func)
775
776 fmt.Fprintf(&buf, "<h3 id='%s'>func %s %s</h3>\n",
777 docfn.Name, objHTML(pkg.FileSet(), web, obj), addedInHTML(obj))
778
779 // decl: func F(params) results
780 fmt.Fprintf(&buf, "<pre class='code'>%s</pre>\n",
781 nodeHTML(docfn.Decl.Type))
782
783 // comment (if any)
784 fmt.Fprintf(&buf, "<div class='comment'>%s</div>\n", docHTML(docfn.Decl, docfn.Doc))
785 }
786 }
787 funcs(docpkg.Funcs)
788
789 // types and their subelements
790 fmt.Fprintf(&buf, "<h2 id='hdr-Types'>Types</h2>\n")
791 for _, doctype := range docpkg.Types {
792 tname := scope.Lookup(doctype.Name).(*types.TypeName)
793
794 // title and source link
795 fmt.Fprintf(&buf, "<h3 id='%s'>type %s %s</h3>\n",
796 doctype.Name, objHTML(pkg.FileSet(), web, tname), addedInHTML(tname))
797
798 // declaration
799 // TODO(adonovan): excise non-exported struct fields somehow.
800 decl2 := *doctype.Decl // shallow copy
801 decl2.Doc = nil
802 fmt.Fprintf(&buf, "<pre class='code'>%s</pre>\n", nodeHTML(&decl2))
803
804 // comment (if any)
805 fmt.Fprintf(&buf, "<div class='comment'>%s</div>\n", docHTML(doctype.Decl, doctype.Doc))
806
807 // subelements
808 values(doctype.Consts) // constants of type T
809 values(doctype.Vars) // vars of type T
810 funcs(doctype.Funcs) // constructors of T
811
812 // methods on T
813 for _, docmethod := range doctype.Methods {
814 method, _, _ := types.LookupFieldOrMethod(tname.Type(), true, tname.Pkg(), docmethod.Name)
815 fmt.Fprintf(&buf, "<h4 id='%s.%s'>func (%s) %s %s</h4>\n",
816 doctype.Name, docmethod.Name,
817 docmethod.Orig, // T or *T
818 objHTML(pkg.FileSet(), web, method), addedInHTML(method))
819
820 // decl: func (x T) M(params) results
821 fmt.Fprintf(&buf, "<pre class='code'>%s</pre>\n",
822 nodeHTML(docmethod.Decl.Type))
823
824 // comment (if any)
825 fmt.Fprintf(&buf, "<div class='comment'>%s</div>\n",
826 docHTML(docmethod.Decl, docmethod.Doc))
827 }
828 }
829
830 // source files
831 fmt.Fprintf(&buf, "<h2 id='hdr-SourceFiles'>Source files</h2>\n")
832 for _, filename := range docpkg.Filenames {
833 fmt.Fprintf(&buf, "<div class='comment'>%s</div>\n",
834 sourceLink(filepath.Base(filename), web.SrcURL(filename, 1, 1)))
835 }
836
837 fmt.Fprintf(&buf, "</main>\n")
838 fmt.Fprintf(&buf, "</body>\n")
839 fmt.Fprintf(&buf, "</html>\n")
840
841 return buf.Bytes(), nil
842 }