/
print_type.go
239 lines (223 loc) · 6.95 KB
/
print_type.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build go1.15
// Package pkgsite is not for external use. May change at any time without
// warning.
//
// Copied from
// https://github.com/golang/pkgsite/blob/ff1e697b104e751da362159cf6c7743898eea3fe/internal/fetch/dochtml/internal/render/
// and
// https://github.com/golang/pkgsite/tree/88f8a28ab2102416529d05d11e8135a43e146d46/internal/fetch/dochtml.
package pkgsite
import (
"bytes"
"fmt"
"go/ast"
"go/doc"
"go/printer"
"go/scanner"
"go/token"
"strconv"
"strings"
)
// PrintType returns a string representation of the decl.
//
// PrintType works by:
// 1. Generate a map from every identifier to a URL for the identifier (or no
// URL if the identifier shouldn't link).
// 2. ast.Inspect the decl to get an ordered slice of every identifier to the
// link for it, using the map from step 1.
// 3. Print out the plain doc for the decl.
// 4. Use scanner.Scanner to find every identifier (in the same order as step
// 2). If there is a link for the identifier, insert it. Otherwise, print
// the plain doc.
func PrintType(fset *token.FileSet, decl ast.Decl, toURL func(string, string) string, topLevelDecls map[interface{}]bool) string {
anchorLinksMap := generateAnchorLinks(decl, toURL, topLevelDecls)
// Convert the map (keyed by *ast.Ident) to a slice of URLs (or no URL).
//
// This relies on the ast.Inspect and scanner.Scanner both
// visiting *ast.Ident and token.IDENT nodes in the same order.
var anchorLinks []string
ast.Inspect(decl, func(node ast.Node) bool {
if id, ok := node.(*ast.Ident); ok {
anchorLinks = append(anchorLinks, anchorLinksMap[id])
}
return true
})
v := &declVisitor{}
ast.Walk(v, decl)
var b bytes.Buffer
p := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 4}
p.Fprint(&b, fset, &printer.CommentedNode{Node: decl, Comments: v.Comments})
src := b.Bytes()
var out strings.Builder
fakeFset := token.NewFileSet()
file := fakeFset.AddFile("", fakeFset.Base(), b.Len())
var lastOffset int // last src offset copied to output buffer
var s scanner.Scanner
s.Init(file, src, nil, scanner.ScanComments)
identIdx := 0
scan:
for {
p, tok, lit := s.Scan()
line := file.Line(p) - 1 // current 0-indexed line number
offset := file.Offset(p) // current offset into source file
// Add traversed bytes from src to the appropriate line.
prevLines := strings.SplitAfter(string(src[lastOffset:offset]), "\n")
for i, ln := range prevLines {
n := line - len(prevLines) + i + 1
if n < 0 { // possible at EOF
n = 0
}
out.WriteString(ln)
}
lastOffset = offset
switch tok {
case token.EOF:
break scan
case token.IDENT:
if identIdx < len(anchorLinks) && anchorLinks[identIdx] != "" {
fmt.Fprintf(&out, `<a href="%s">%s</a>`, anchorLinks[identIdx], lit)
} else {
out.WriteString(lit)
}
identIdx++
lastOffset += len(lit)
}
}
return out.String()
}
// declVisitor is used to walk over the AST and trim large string
// literals and arrays before package documentation is rendered.
// Comments are added to Comments to indicate that a part of the
// original code is not displayed.
type declVisitor struct {
Comments []*ast.CommentGroup
}
// Visit implements ast.Visitor.
func (v *declVisitor) Visit(n ast.Node) ast.Visitor {
switch n := n.(type) {
case *ast.BasicLit:
if n.Kind == token.STRING && len(n.Value) > 128 {
v.Comments = append(v.Comments,
&ast.CommentGroup{List: []*ast.Comment{{
Slash: n.Pos(),
Text: stringBasicLitSize(n.Value),
}}})
n.Value = `""`
}
case *ast.CompositeLit:
if len(n.Elts) > 100 {
v.Comments = append(v.Comments,
&ast.CommentGroup{List: []*ast.Comment{{
Slash: n.Lbrace,
Text: fmt.Sprintf("/* %d elements not displayed */", len(n.Elts)),
}}})
n.Elts = n.Elts[:0]
}
}
return v
}
// stringBasicLitSize computes the number of bytes in the given string basic literal.
//
// See noder.basicLit and syntax.StringLit cases in cmd/compile/internal/gc/noder.go.
func stringBasicLitSize(s string) string {
if len(s) > 0 && s[0] == '`' {
// strip carriage returns from raw string
s = strings.ReplaceAll(s, "\r", "")
}
u, err := strconv.Unquote(s)
if err != nil {
return fmt.Sprintf("/* invalid %d byte string literal not displayed */", len(s))
}
return fmt.Sprintf("/* %d byte string literal not displayed */", len(u))
}
// generateAnchorLinks returns a mapping of *ast.Ident objects to the URL
// that the identifier should link to.
func generateAnchorLinks(decl ast.Decl, toURL func(string, string) string, topLevelDecls map[interface{}]bool) map[*ast.Ident]string {
m := map[*ast.Ident]string{}
ignore := map[ast.Node]bool{}
ast.Inspect(decl, func(node ast.Node) bool {
if ignore[node] {
return false
}
switch node := node.(type) {
case *ast.SelectorExpr:
// Package qualified identifier (e.g., "io.EOF").
if prefix, _ := node.X.(*ast.Ident); prefix != nil {
if obj := prefix.Obj; obj != nil && obj.Kind == ast.Pkg {
if spec, _ := obj.Decl.(*ast.ImportSpec); spec != nil {
if path, err := strconv.Unquote(spec.Path.Value); err == nil {
// Register two links, one for the package
// and one for the qualified identifier.
m[prefix] = toURL(path, "")
m[node.Sel] = toURL(path, node.Sel.Name)
return false
}
}
}
}
case *ast.Ident:
if node.Obj == nil && doc.IsPredeclared(node.Name) {
m[node] = toURL("builtin", node.Name)
} else if node.Obj != nil && topLevelDecls[node.Obj.Decl] {
m[node] = toURL("", node.Name)
}
case *ast.FuncDecl:
ignore[node.Name] = true // E.g., "func NoLink() int"
case *ast.TypeSpec:
ignore[node.Name] = true // E.g., "type NoLink int"
case *ast.ValueSpec:
for _, n := range node.Names {
ignore[n] = true // E.g., "var NoLink1, NoLink2 int"
}
case *ast.AssignStmt:
for _, n := range node.Lhs {
ignore[n] = true // E.g., "NoLink1, NoLink2 := 0, 1"
}
}
return true
})
return m
}
// TopLevelDecls returns the top level declarations in the package.
func TopLevelDecls(pkg *doc.Package) map[interface{}]bool {
topLevelDecls := map[interface{}]bool{}
forEachPackageDecl(pkg, func(decl ast.Decl) {
topLevelDecls[decl] = true
if gd, _ := decl.(*ast.GenDecl); gd != nil {
for _, sp := range gd.Specs {
topLevelDecls[sp] = true
}
}
})
return topLevelDecls
}
// forEachPackageDecl iterates though every top-level declaration in a package.
func forEachPackageDecl(pkg *doc.Package, fnc func(decl ast.Decl)) {
for _, c := range pkg.Consts {
fnc(c.Decl)
}
for _, v := range pkg.Vars {
fnc(v.Decl)
}
for _, f := range pkg.Funcs {
fnc(f.Decl)
}
for _, t := range pkg.Types {
fnc(t.Decl)
for _, c := range t.Consts {
fnc(c.Decl)
}
for _, v := range t.Vars {
fnc(v.Decl)
}
for _, f := range t.Funcs {
fnc(f.Decl)
}
for _, m := range t.Methods {
fnc(m.Decl)
}
}
}