Debian Codegraph @

gopls/internal/doc/generate/generate.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 // The generate command updates the following files of documentation:
6 //
7 // gopls/doc/settings.md -- from linking gopls/internal/settings.DefaultOptions
8 // gopls/doc/analyzers.md -- from linking gopls/internal/settings.DefaultAnalyzers
9 // gopls/doc/inlayHints.md -- from loading gopls/internal/settings.InlayHint
10 // gopls/internal/doc/api.json -- all of the above in a single value, for 'gopls api-json'
11 //
12 // Run it with this command:
13 //
14 // $ cd gopls/internal/doc/generate && go generate
15 package main
16
17 import (
18 "bytes"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "go/ast"
23 "go/doc/comment"
24 "go/token"
25 "go/types"
26 "log"
27 "maps"
28 "os"
29 "os/exec"
30 "path/filepath"
31 "reflect"
32 "regexp"
33 "slices"
34 "sort"
35 "strconv"
36 "strings"
37 "time"
38 "unicode"
39
40 goastutil "golang.org/x/tools/go/ast/astutil"
41 "golang.org/x/tools/go/packages"
42 "golang.org/x/tools/gopls/internal/cache"
43 "golang.org/x/tools/gopls/internal/doc"
44 "golang.org/x/tools/gopls/internal/golang"
45 "golang.org/x/tools/gopls/internal/mod"
46 "golang.org/x/tools/gopls/internal/settings"
47 "golang.org/x/tools/gopls/internal/util/safetoken"
48 "golang.org/x/tools/internal/astutil"
49 )
50
51 func main() {
52 if _, err := doMain(true); err != nil {
53 fmt.Fprintf(os.Stderr, "Generation failed: %v\n", err)
54 os.Exit(1)
55 }
56 }
57
58 // doMain regenerates the output files. On success:
59 // - if write, it updates them;
60 // - if !write, it reports whether they would change.
61 func doMain(write bool) (bool, error) {
62 api, err := loadAPI()
63 if err != nil {
64 return false, err
65 }
66
67 goplsDir, err := pkgDir("golang.org/x/tools/gopls")
68 if err != nil {
69 return false, err
70 }
71
72 // TODO(adonovan): consider using HTML, not Markdown, for the
73 // generated reference documents. It's not more difficult, the
74 // layout is easier to read, and we can use go/doc-comment
75 // rendering logic.
76
77 for _, f := range []struct {
78 name string // relative to gopls
79 rewrite rewriter
80 }{
81 {"internal/doc/api.json", rewriteAPI},
82 {"doc/settings.md", rewriteSettings},
83 {"doc/codelenses.md", rewriteCodeLenses},
84 {"doc/analyzers.md", rewriteAnalyzers},
85 {"doc/inlayHints.md", rewriteInlayHints},
86 } {
87 file := filepath.Join(goplsDir, f.name)
88 old, err := os.ReadFile(file)
89 if err != nil {
90 return false, err
91 }
92
93 new, err := f.rewrite(old, api)
94 if err != nil {
95 return false, fmt.Errorf("rewriting %q: %v", file, err)
96 }
97
98 if write {
99 if err := os.WriteFile(file, new, 0); err != nil {
100 return false, err
101 }
102 } else if !bytes.Equal(old, new) {
103 return false, nil // files would change
104 }
105 }
106 return true, nil
107 }
108
109 // A rewriter is a function that transforms the content of a file.
110 type rewriter = func([]byte, *doc.API) ([]byte, error)
111
112 // pkgDir returns the directory corresponding to the import path pkgPath.
113 func pkgDir(pkgPath string) (string, error) {
114 cmd := exec.Command("go", "list", "-f", "{{.Dir}}", pkgPath)
115 out, err := cmd.Output()
116 if err != nil {
117 if ee, _ := err.(*exec.ExitError); ee != nil && len(ee.Stderr) > 0 {
118 return "", fmt.Errorf("%v: %w\n%s", cmd, err, ee.Stderr)
119 }
120 return "", fmt.Errorf("%v: %w", cmd, err)
121 }
122 return strings.TrimSpace(string(out)), nil
123 }
124
125 // loadAPI computes the JSON-encodable value that describes gopls'
126 // interfaces, by a combination of static and dynamic analysis.
127 func loadAPI() (*doc.API, error) {
128 pkgs, err := packages.Load(
129 &packages.Config{
130 Mode: packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax | packages.NeedDeps,
131 },
132 "golang.org/x/tools/gopls/internal/settings",
133 )
134 if err != nil {
135 return nil, err
136 }
137 settingsPkg := pkgs[0]
138
139 defaults := settings.DefaultOptions()
140 api := &doc.API{
141 Options: map[string][]*doc.Option{},
142 Analyzers: loadAnalyzers(settings.AllAnalyzers, defaults),
143 }
144
145 api.Lenses, err = loadLenses(settingsPkg, defaults.Codelenses)
146 if err != nil {
147 return nil, err
148 }
149 api.Hints, err = loadHints(settingsPkg)
150 if err != nil {
151 return nil, err
152 }
153
154 for _, category := range []reflect.Value{
155 reflect.ValueOf(defaults.UserOptions),
156 } {
157 // Find the type information and ast.File corresponding to the category.
158 optsType := settingsPkg.Types.Scope().Lookup(category.Type().Name())
159 if optsType == nil {
160 return nil, fmt.Errorf("could not find %v in scope %v", category.Type().Name(), settingsPkg.Types.Scope())
161 }
162 opts, err := loadOptions(category, optsType, settingsPkg, "")
163 if err != nil {
164 return nil, err
165 }
166
167 // Edge case for "analyses": populate its enum keys from
168 // the analyzer list, since its map keys are strings, not enums.
169 // Also, set its EnumKeys.ValueType for historical reasons.
170 for _, opt := range opts {
171 if opt.Name == "analyses" {
172 opt.EnumKeys.ValueType = "bool"
173 for _, a := range api.Analyzers {
174 opt.EnumKeys.Keys = append(opt.EnumKeys.Keys, doc.EnumKey{
175 Name: fmt.Sprintf("%q", a.Name),
176 Doc: a.Doc,
177 Default: strconv.FormatBool(a.Default),
178 })
179 }
180 }
181 }
182
183 catName := strings.TrimSuffix(category.Type().Name(), "Options")
184 api.Options[catName] = opts
185 }
186 return api, nil
187 }
188
189 // loadOptions computes a single category of settings by a combination
190 // of static analysis and reflection over gopls internal types.
191 func loadOptions(category reflect.Value, optsType types.Object, pkg *packages.Package, hierarchy string) ([]*doc.Option, error) {
192 file, err := fileForPos(pkg, optsType.Pos())
193 if err != nil {
194 return nil, err
195 }
196
197 enums, err := loadEnums(pkg) // TODO(adonovan): do this only once at toplevel.
198 if err != nil {
199 return nil, err
200 }
201
202 var opts []*doc.Option
203 optsStruct := optsType.Type().Underlying().(*types.Struct)
204 for typesField := range optsStruct.Fields() {
205 // The types field gives us the type.
206
207 // If the field name ends with "Options", assume it is a struct with
208 // additional options and process it recursively.
209 if h, ok := strings.CutSuffix(typesField.Name(), "Options"); ok {
210 // Keep track of the parent structs.
211 if hierarchy != "" {
212 h = hierarchy + "." + h
213 }
214 options, err := loadOptions(category, typesField, pkg, strings.ToLower(h))
215 if err != nil {
216 return nil, err
217 }
218 opts = append(opts, options...)
219 continue
220 }
221 path, _ := goastutil.PathEnclosingInterval(file, typesField.Pos(), typesField.Pos())
222 if len(path) < 2 {
223 return nil, fmt.Errorf("could not find AST node for field %v", typesField)
224 }
225
226 // The AST field gives us the doc.
227 astField, ok := path[1].(*ast.Field)
228 if !ok {
229 return nil, fmt.Errorf("unexpected AST path %v", path)
230 }
231 description, deprecation := astField.Doc.Text(), astutil.Deprecation(astField.Doc)
232
233 // The reflect field gives us the default value.
234 reflectField := category.FieldByName(typesField.Name())
235 if !reflectField.IsValid() {
236 return nil, fmt.Errorf("could not find reflect field for %v", typesField.Name())
237 }
238
239 def, err := formatDefault(reflectField)
240 if err != nil {
241 return nil, err
242 }
243
244 // Derive the doc-and-api.json type from the Go field type.
245 //
246 // In principle, we should use JSON nomenclature here
247 // (number, array, object, etc; see #68057), but in
248 // practice we use the Go type string ([]T, map[K]V,
249 // etc) with only one tweak: enumeration types are
250 // replaced by "enum", including when they appear as
251 // map keys.
252 //
253 // Notable edge cases:
254 // - any (e.g. in linksInHover) is really a sum of false | true | "internal".
255 // - time.Duration is really a string with a particular syntax.
256 typ := typesField.Type().String()
257 if _, ok := enums[typesField.Type()]; ok {
258 typ = "enum"
259 }
260 name := lowerFirst(typesField.Name())
261
262 // enum-keyed maps
263 var enumKeys doc.EnumKeys
264 if m, ok := typesField.Type().Underlying().(*types.Map); ok {
265 if values, ok := enums[m.Key()]; ok {
266 // Update type name: "map[CodeLensSource]T" -> "map[enum]T"
267 // hack: assumes key substring is unique!
268 typ = strings.Replace(typ, m.Key().String(), "enum", 1)
269
270 enumKeys.ValueType = m.Elem().String() // e.g. bool
271
272 // For map[enum]T fields, gather the set of valid
273 // EnumKeys (from type information). If T=bool, also
274 // record the default value (from reflection).
275 keys, err := collectEnumKeys(m, reflectField, values)
276 if err != nil {
277 return nil, err
278 }
279 enumKeys.Keys = keys
280 }
281 }
282
283 // Get the status of the field by checking its struct tags.
284 reflectStructField, ok := category.Type().FieldByName(typesField.Name())
285 if !ok {
286 return nil, fmt.Errorf("no struct field for %s", typesField.Name())
287 }
288 status := reflectStructField.Tag.Get("status")
289
290 opts = append(opts, &doc.Option{
291 Name: name,
292 Type: typ,
293 Doc: lowerFirst(description),
294 Default: def,
295 EnumKeys: enumKeys,
296 EnumValues: enums[typesField.Type()],
297 Status: status,
298 Hierarchy: hierarchy,
299 DeprecationMessage: lowerFirst(strings.TrimPrefix(deprecation, "Deprecated: ")),
300 })
301 }
302 return opts, nil
303 }
304
305 // loadEnums returns a description of gopls' settings enum types based on static analysis.
306 func loadEnums(pkg *packages.Package) (map[types.Type][]doc.EnumValue, error) {
307 enums := make(map[types.Type][]doc.EnumValue)
308 for _, name := range pkg.Types.Scope().Names() {
309 obj := pkg.Types.Scope().Lookup(name)
310 cnst, ok := obj.(*types.Const)
311 if !ok {
312 continue
313 }
314 f, err := fileForPos(pkg, cnst.Pos())
315 if err != nil {
316 return nil, fmt.Errorf("finding file for %q: %v", cnst.Name(), err)
317 }
318 path, _ := goastutil.PathEnclosingInterval(f, cnst.Pos(), cnst.Pos())
319 spec := path[1].(*ast.ValueSpec)
320 value := cnst.Val().ExactString()
321 docstring := valueDoc(cnst.Name(), value, spec.Doc.Text())
322 var status string
323 for _, d := range astutil.Directives(spec.Doc) {
324 if d.Tool == "gopls" && d.Name == "status" {
325 status = d.Args
326 break
327 }
328 }
329 v := doc.EnumValue{
330 Value: value,
331 Doc: docstring,
332 Status: status,
333 }
334 enums[obj.Type()] = append(enums[obj.Type()], v)
335 }
336
337 // linksInHover is a one-off edge case (true | false | "gopls")
338 // that doesn't warrant a general solution (e.g. struct tag).
339 enums[pkg.Types.Scope().Lookup("LinksInHoverEnum").Type()] = []doc.EnumValue{
340 {Value: "false", Doc: "false: do not show links"},
341 {Value: "true", Doc: "true: show links to the `linkTarget` domain"},
342 {Value: `"gopls"`, Doc: "`\"gopls\"`: show links to gopls' internal documentation viewer"},
343 }
344
345 return enums, nil
346 }
347
348 func collectEnumKeys(m *types.Map, reflectField reflect.Value, enumValues []doc.EnumValue) ([]doc.EnumKey, error) {
349 // We can get default values for enum -> bool maps.
350 var isEnumBoolMap bool
351 if basic, ok := m.Elem().Underlying().(*types.Basic); ok && basic.Kind() == types.Bool {
352 isEnumBoolMap = true
353 }
354 var keys []doc.EnumKey
355 for _, v := range enumValues {
356 var def string
357 if isEnumBoolMap {
358 var err error
359 def, err = formatDefaultFromEnumBoolMap(reflectField, v.Value)
360 if err != nil {
361 return nil, err
362 }
363 }
364 keys = append(keys, doc.EnumKey{
365 Name: v.Value,
366 Doc: v.Doc,
367 Status: v.Status,
368 Default: def,
369 })
370 }
371 return keys, nil
372 }
373
374 func formatDefaultFromEnumBoolMap(reflectMap reflect.Value, enumKey string) (string, error) {
375 if reflectMap.Kind() != reflect.Map {
376 return "", nil
377 }
378 name := enumKey
379 if unquoted, err := strconv.Unquote(name); err == nil {
380 name = unquoted
381 }
382 for _, e := range reflectMap.MapKeys() {
383 if e.String() == name {
384 value := reflectMap.MapIndex(e)
385 if value.Type().Kind() == reflect.Bool {
386 return formatDefault(value)
387 }
388 }
389 }
390 // Assume that if the value isn't mentioned in the map, it defaults to
391 // the default value, false.
392 return formatDefault(reflect.ValueOf(false))
393 }
394
395 // formatDefault formats the default value into a JSON-like string.
396 // VS Code exposes settings as JSON, so showing them as JSON is reasonable.
397 // TODO(rstambler): Reconsider this approach, as the VS Code Go generator now
398 // marshals to JSON.
399 func formatDefault(reflectField reflect.Value) (string, error) {
400 def := reflectField.Interface()
401
402 // Durations marshal as nanoseconds, but we want the stringy versions,
403 // e.g. "100ms".
404 if t, ok := def.(time.Duration); ok {
405 def = t.String()
406 }
407 defBytes, err := json.Marshal(def)
408 if err != nil {
409 return "", err
410 }
411
412 // Nil values format as "null" so print them as hardcoded empty values.
413 switch reflectField.Type().Kind() {
414 case reflect.Map:
415 if reflectField.IsNil() {
416 defBytes = []byte("{}")
417 }
418 case reflect.Slice:
419 if reflectField.IsNil() {
420 defBytes = []byte("[]")
421 }
422 }
423 return string(defBytes), err
424 }
425
426 // valueDoc transforms a docstring documenting a constant identifier to a
427 // docstring documenting its value.
428 //
429 // If doc is of the form "Foo is a bar", it returns '`"fooValue"` is a bar'. If
430 // doc is non-standard ("this value is a bar"), it returns '`"fooValue"`: this
431 // value is a bar'.
432 func valueDoc(name, value, doc string) string {
433 if doc == "" {
434 return ""
435 }
436 if strings.HasPrefix(doc, name) {
437 // docstring in standard form. Replace the subject with value.
438 return fmt.Sprintf("`%s`%s", value, doc[len(name):])
439 }
440 return fmt.Sprintf("`%s`: %s", value, doc)
441 }
442
443 // loadLenses combines the syntactic comments from the settings
444 // package with the default values from settings.DefaultOptions(), and
445 // returns a list of Code Lens descriptors.
446 func loadLenses(settingsPkg *packages.Package, defaults map[settings.CodeLensSource]bool) ([]*doc.Lens, error) {
447 // Find the CodeLensSource enums among the files of the protocol package.
448 // Map each enum value to its doc comment.
449 enumDoc := make(map[string]string)
450 enumStatus := make(map[string]string)
451 for _, f := range settingsPkg.Syntax {
452 for _, decl := range f.Decls {
453 if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.CONST {
454 for _, spec := range decl.Specs {
455 spec := spec.(*ast.ValueSpec)
456 posn := safetoken.StartPosition(settingsPkg.Fset, spec.Pos())
457 if id, ok := spec.Type.(*ast.Ident); ok && id.Name == "CodeLensSource" {
458 if len(spec.Names) != 1 || len(spec.Values) != 1 {
459 return nil, fmt.Errorf("%s: declare one CodeLensSource per line", posn)
460 }
461 lit, ok := spec.Values[0].(*ast.BasicLit)
462 if !ok || lit.Kind != token.STRING {
463 return nil, fmt.Errorf("%s: CodeLensSource value is not a string literal", posn)
464 }
465 value, _ := strconv.Unquote(lit.Value) // ignore error: AST is well-formed
466 if spec.Doc == nil {
467 return nil, fmt.Errorf("%s: %s lacks doc comment", posn, spec.Names[0].Name)
468 }
469 enumDoc[value] = spec.Doc.Text()
470 for _, d := range astutil.Directives(spec.Doc) {
471 if d.Tool == "gopls" && d.Name == "status" {
472 enumStatus[value] = d.Args
473 break
474 }
475 }
476 }
477 }
478 }
479 }
480 }
481 if len(enumDoc) == 0 {
482 return nil, fmt.Errorf("failed to extract any CodeLensSource declarations")
483 }
484
485 // Build list of Lens descriptors.
486 var lenses []*doc.Lens
487 addAll := func(sources map[settings.CodeLensSource]cache.CodeLensSourceFunc, fileType string) error {
488 for _, source := range slices.Sorted(maps.Keys(sources)) {
489 docText, ok := enumDoc[string(source)]
490 if !ok {
491 return fmt.Errorf("missing CodeLensSource declaration for %s", source)
492 }
493 title, docText, _ := strings.Cut(docText, "\n") // first line is title
494 lenses = append(lenses, &doc.Lens{
495 FileType: fileType,
496 Lens: string(source),
497 Title: title,
498 Doc: docText,
499 Default: defaults[source],
500 Status: enumStatus[string(source)],
501 })
502 }
503 return nil
504 }
505 err := errors.Join(
506 addAll(golang.CodeLensSources(), "Go"),
507 addAll(mod.CodeLensSources(), "go.mod"))
508 return lenses, err
509 }
510
511 func loadAnalyzers(analyzers []*settings.Analyzer, defaults *settings.Options) []*doc.Analyzer {
512 slices.SortFunc(analyzers, func(x, y *settings.Analyzer) int {
513 return strings.Compare(x.Analyzer().Name, y.Analyzer().Name)
514 })
515 var json []*doc.Analyzer
516 for _, a := range analyzers {
517 json = append(json, &doc.Analyzer{
518 Name: a.Analyzer().Name,
519 Doc: a.Analyzer().Doc,
520 URL: a.Analyzer().URL,
521 Default: a.Enabled(defaults),
522 })
523 }
524 return json
525 }
526
527 // loadHints derives and returns the inlay hints metadata from the settings.InlayHint type.
528 func loadHints(settingsPkg *packages.Package) ([]*doc.Hint, error) {
529 enums, err := loadEnums(settingsPkg) // TODO(adonovan): call loadEnums exactly once
530 if err != nil {
531 return nil, err
532 }
533 inlayHint := settingsPkg.Types.Scope().Lookup("InlayHint").Type()
534 var hints []*doc.Hint
535 for _, enumVal := range enums[inlayHint] {
536 name, _ := strconv.Unquote(enumVal.Value)
537 hints = append(hints, &doc.Hint{
538 Name: name,
539 Doc: enumVal.Doc,
540 Status: enumVal.Status,
541 })
542 }
543 return hints, nil
544 }
545
546 func lowerFirst(x string) string {
547 if x == "" {
548 return x
549 }
550 return strings.ToLower(x[:1]) + x[1:]
551 }
552
553 func fileForPos(pkg *packages.Package, pos token.Pos) (*ast.File, error) {
554 fset := pkg.Fset
555 for _, f := range pkg.Syntax {
556 if safetoken.StartPosition(fset, f.FileStart).Filename == safetoken.StartPosition(fset, pos).Filename {
557 return f, nil
558 }
559 }
560 return nil, fmt.Errorf("no file for pos %v", pos)
561 }
562
563 func rewriteAPI(_ []byte, api *doc.API) ([]byte, error) {
564 return json.MarshalIndent(api, "", "\t")
565 }
566
567 type optionsGroup struct {
568 title string // dotted path (e.g. "ui.documentation")
569 final string // final segment of title (e.g. "documentation")
570 level int
571 options []*doc.Option
572 }
573
574 func rewriteSettings(prevContent []byte, api *doc.API) ([]byte, error) {
575 content := prevContent
576 for category, opts := range api.Options {
577 groups := collectGroups(opts)
578
579 var buf bytes.Buffer
580
581 // First, print a table of contents (ToC).
582 fmt.Fprintln(&buf)
583 for _, h := range groups {
584 title := h.final
585 if title != "" {
586 fmt.Fprintf(&buf, "%s* [%s](#%s)\n",
587 strings.Repeat(" ", h.level),
588 capitalize(title),
589 strings.ToLower(title))
590 }
591 }
592
593 // Section titles are h2, options are h3.
594 // This is independent of the option hierarchy.
595 // (Nested options should not be smaller!)
596 fmt.Fprintln(&buf)
597 for _, h := range groups {
598 title := h.final
599 if title != "" {
600 // Emit HTML anchor as GitHub markdown doesn't support
601 // "# Heading {#anchor}" syntax.
602 fmt.Fprintf(&buf, "<a id='%s'></a>\n", strings.ToLower(title))
603
604 fmt.Fprintf(&buf, "## %s\n\n", capitalize(title))
605 }
606 for _, opt := range h.options {
607 // Emit HTML anchor as GitHub markdown doesn't support
608 // "# Heading {#anchor}" syntax.
609 //
610 // (Each option name is the camelCased name of a field of
611 // settings.UserOptions or one of its FooOptions subfields.)
612 fmt.Fprintf(&buf, "<a id='%s'></a>\n", opt.Name)
613
614 // heading
615 //
616 // We do not display the undocumented dotted-path alias
617 // (h.title + "." + opt.Name) used by VS Code only.
618 fmt.Fprintf(&buf, "### `%s %s`\n\n", opt.Name, opt.Type)
619
620 // status
621 writeStatus(&buf, opt.Status)
622
623 // doc comment
624 buf.WriteString(opt.Doc)
625
626 // enums
627 write := func(name, doc string) {
628 if doc != "" {
629 unbroken := parBreakRE.ReplaceAllString(doc, "\\\n")
630 fmt.Fprintf(&buf, "* %s\n", strings.TrimSpace(unbroken))
631 } else {
632 fmt.Fprintf(&buf, "* `%s`\n", name)
633 }
634 }
635 if len(opt.EnumValues) > 0 && opt.Type == "enum" {
636 // enum as top-level type constructor
637 buf.WriteString("\nMust be one of:\n\n")
638 for _, val := range opt.EnumValues {
639 write(val.Value, val.Doc)
640 }
641 } else if len(opt.EnumKeys.Keys) > 0 && shouldShowEnumKeysInSettings(opt.Name) {
642 // enum as map key (currently just "annotations")
643 buf.WriteString("\nEach enum must be one of:\n\n")
644 for _, val := range opt.EnumKeys.Keys {
645 write(val.Name, val.Doc)
646 }
647 }
648
649 // default value
650 fmt.Fprintf(&buf, "\nDefault: `%v`.\n\n", opt.Default)
651 }
652 }
653 newContent, err := replaceSection(content, category, buf.Bytes())
654 if err != nil {
655 return nil, err
656 }
657 content = newContent
658 }
659 return content, nil
660 }
661
662 // writeStatus emits a Markdown paragraph to buf about the status of a feature,
663 // if nonempty.
664 func writeStatus(buf *bytes.Buffer, status string) {
665 switch status {
666 case "":
667 case "advanced":
668 fmt.Fprint(buf, "**This is an advanced setting and should not be configured by most `gopls` users.**\n\n")
669 case "debug":
670 fmt.Fprint(buf, "**This setting is for debugging purposes only.**\n\n")
671 case "experimental":
672 fmt.Fprint(buf, "**This setting is experimental and may be deleted.**\n\n")
673 default:
674 fmt.Fprintf(buf, "**Status: %s.**\n\n", status)
675 }
676 }
677
678 var parBreakRE = regexp.MustCompile("\n{2,}")
679
680 func shouldShowEnumKeysInSettings(name string) bool {
681 // These fields have too many possible options,
682 // or too voluminous documentation, to render as enums.
683 // Instead they each get their own page in the manual.
684 return !(name == "analyses" || name == "codelenses" || name == "hints")
685 }
686
687 func collectGroups(opts []*doc.Option) []optionsGroup {
688 optsByHierarchy := map[string][]*doc.Option{}
689 for _, opt := range opts {
690 optsByHierarchy[opt.Hierarchy] = append(optsByHierarchy[opt.Hierarchy], opt)
691 }
692
693 // As a hack, assume that uncategorized items are less important to
694 // users and force the empty string to the end of the list.
695 var containsEmpty bool
696 var sorted []string
697 for h := range optsByHierarchy {
698 if h == "" {
699 containsEmpty = true
700 continue
701 }
702 sorted = append(sorted, h)
703 }
704 sort.Strings(sorted)
705 if containsEmpty {
706 sorted = append(sorted, "")
707 }
708 var groups []optionsGroup
709 baseLevel := 0
710 for _, h := range sorted {
711 split := strings.SplitAfter(h, ".")
712 last := split[len(split)-1]
713 // Hack to capitalize all of UI.
714 if last == "ui" {
715 last = "UI"
716 }
717 // A hierarchy may look like "ui.formatting". If "ui" has no
718 // options of its own, it may not be added to the map, but it
719 // still needs a heading.
720 components := strings.Split(h, ".")
721 for i := 1; i < len(components); i++ {
722 parent := strings.Join(components[0:i], ".")
723 if _, ok := optsByHierarchy[parent]; !ok {
724 groups = append(groups, optionsGroup{
725 title: parent,
726 final: last,
727 level: baseLevel + i,
728 })
729 }
730 }
731 groups = append(groups, optionsGroup{
732 title: h,
733 final: last,
734 level: baseLevel + strings.Count(h, "."),
735 options: optsByHierarchy[h],
736 })
737 }
738 return groups
739 }
740
741 func capitalize(s string) string {
742 return string(unicode.ToUpper(rune(s[0]))) + s[1:]
743 }
744
745 func rewriteCodeLenses(prevContent []byte, api *doc.API) ([]byte, error) {
746 var buf bytes.Buffer
747 for _, lens := range api.Lenses {
748 fmt.Fprintf(&buf, "## `%s`: %s\n\n", lens.Lens, lens.Title)
749 writeStatus(&buf, lens.Status)
750 fmt.Fprintf(&buf, "%s\n\n", lens.Doc)
751 fmt.Fprintf(&buf, "Default: %v\n\n", onOff(lens.Default))
752 fmt.Fprintf(&buf, "File type: %s\n\n", lens.FileType)
753 }
754 return replaceSection(prevContent, "Lenses", buf.Bytes())
755 }
756
757 func rewriteAnalyzers(prevContent []byte, api *doc.API) ([]byte, error) {
758 seen := make(map[string]string) // name->doc, for reporting dups
759
760 var buf bytes.Buffer
761 for _, analyzer := range api.Analyzers {
762 if prevDoc, ok := seen[analyzer.Name]; ok {
763 log.Fatalf("duplicate analyzer name %q\n===1===\n%s\n===2===\n%s", analyzer.Name, analyzer.Doc, prevDoc)
764 }
765 seen[analyzer.Name] = analyzer.Doc
766
767 fmt.Fprintf(&buf, "<a id='%s'></a>\n", analyzer.Name)
768 title, doc, _ := strings.Cut(analyzer.Doc, "\n")
769 title = strings.TrimPrefix(title, analyzer.Name+": ")
770 fmt.Fprintf(&buf, "## `%s`: %s\n\n", analyzer.Name, title)
771
772 // Convert Analyzer.Doc from go/doc/comment form to Markdown.
773 // Headings in doc comments are converted to ### (HeadingLevel=3).
774 //
775 // Some Analyzers (e.g. go/analysis/passes/inline) use ## to indicate subheadings
776 // Although this is valid Markdown, it is not valid go/doc/comment,
777 // nor is it rendered as a subheading by pkg.go.dev or gopls's doc viewer.
778 // Perhaps it will be supported in future; see
779 // https://github.com/golang/go/issues/51082#issuecomment-1033116430 et seq.
780 //
781 // In the meantime, the go/doc/comment processing will escape them so
782 // that the ## appears literally in analyzers.md just as it does in
783 // the two viewers mentioned above. The meaning is clear enough.
784 doctree := new(comment.Parser).Parse(doc)
785 buf.Write((&comment.Printer{HeadingLevel: 3}).Markdown(doctree))
786 buf.WriteString("\n\n")
787
788 fmt.Fprintf(&buf, "Default: %s.", onOff(analyzer.Default))
789 if !analyzer.Default {
790 fmt.Fprintf(&buf, " Enable by setting `\"analyses\": {\"%s\": true}`.", analyzer.Name)
791 }
792 fmt.Fprintf(&buf, "\n\n")
793 if analyzer.URL != "" {
794 // TODO(adonovan): currently the URL provides the same information
795 // as 'doc' above, though that may change due to
796 // https://github.com/golang/go/issues/61315#issuecomment-1841350181.
797 // In that case, update this to something like "Complete documentation".
798 fmt.Fprintf(&buf, "Package documentation: [%s](%s)\n\n",
799 analyzer.Name, analyzer.URL)
800 }
801 }
802 return replaceSection(prevContent, "Analyzers", buf.Bytes())
803 }
804
805 func rewriteInlayHints(prevContent []byte, api *doc.API) ([]byte, error) {
806 var buf bytes.Buffer
807 for _, hint := range api.Hints {
808 fmt.Fprintf(&buf, "## **%v**\n\n", hint.Name)
809 fmt.Fprintf(&buf, "%s\n\n", hint.Doc)
810 switch hint.Default {
811 case true:
812 fmt.Fprintf(&buf, "**Enabled by default.**\n\n")
813 case false:
814 fmt.Fprintf(&buf, "**Disabled by default. Enable it by setting `\"hints\": {\"%s\": true}`.**\n\n", hint.Name)
815 }
816 }
817 return replaceSection(prevContent, "Hints", buf.Bytes())
818 }
819
820 // replaceSection replaces the portion of a file delimited by comments of the form:
821 //
822 // <!-- BEGIN sectionName -->
823 // <!-- END section Name -->
824 func replaceSection(content []byte, sectionName string, replacement []byte) ([]byte, error) {
825 re := regexp.MustCompile(fmt.Sprintf(`(?s)<!-- BEGIN %v.* -->\n(.*?)<!-- END %v.* -->`, sectionName, sectionName))
826 idx := re.FindSubmatchIndex(content)
827 if idx == nil {
828 return nil, fmt.Errorf("could not find section %q", sectionName)
829 }
830 result := slices.Clone(content[:idx[2]])
831 result = append(result, replacement...)
832 result = append(result, content[idx[3]:]...)
833 return result, nil
834 }
835
836 type onOff bool
837
838 func (o onOff) String() string {
839 if o {
840 return "on"
841 } else {
842 return "off"
843 }
844 }