Movatterモバイル変換


[0]ホーム

URL:


doc

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:13Imported by:3,578

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package doc extracts source code documentation from a Go AST.

Index

Examples

Constants

This section is empty.

Variables

View Source
var IllegalPrefixes = []string{"copyright","all rights","author",}

IllegalPrefixes is a list of lower-case prefixes that identifya comment as not being a doc comment.This helps to avoid misinterpreting the common mistakeof a copyright notice immediately before a package statementas being a doc comment.

Functions

funcIsPredeclaredadded ingo1.8

func IsPredeclared(sstring)bool

IsPredeclared reports whether s is a predeclared identifier.

funcSynopsisdeprecated

func Synopsis(textstring)string

Synopsis returns a cleaned version of the first sentence in text.

Deprecated: New programs should usePackage.Synopsis instead,which handles links in text properly.

funcToHTMLdeprecated

func ToHTML(wio.Writer, textstring, words map[string]string)

ToHTML converts comment text to formatted HTML.

Deprecated: ToHTML cannot identify documentation linksin the doc comment, because they depend on knowing whatpackage the text came from, which is not included in this API.

Given the *doc.Package p where text was found,ToHTML(w, text, nil) can be replaced by:

w.Write(p.HTML(text))

which is in turn shorthand for:

w.Write(p.Printer().HTML(p.Parser().Parse(text)))

If words may be non-nil, the longer replacement is:

parser := p.Parser()parser.Words = wordsw.Write(p.Printer().HTML(parser.Parse(d)))

funcToTextdeprecated

func ToText(wio.Writer, textstring, prefix, codePrefixstring, widthint)

ToText converts comment text to formatted text.

Deprecated: ToText cannot identify documentation linksin the doc comment, because they depend on knowing whatpackage the text came from, which is not included in this API.

Given the *doc.Package p where text was found,ToText(w, text, "", "\t", 80) can be replaced by:

w.Write(p.Text(text))

In the general case, ToText(w, text, prefix, codePrefix, width)can be replaced by:

d := p.Parser().Parse(text)pr := p.Printer()pr.TextPrefix = prefixpr.TextCodePrefix = codePrefixpr.TextWidth = widthw.Write(pr.Text(d))

See the documentation forPackage.Text andcomment.Printer.Textfor more details.

Types

typeExample

type Example struct {Namestring// name of the item being exemplified (including optional suffix)Suffixstring// example suffix, without leading '_' (only populated by NewFromFiles)Docstring// example function doc stringCodeast.NodePlay        *ast.File// a whole program version of the exampleComments    []*ast.CommentGroupOutputstring// expected outputUnorderedboolEmptyOutputbool// expect empty outputOrderint// original source code order}

An Example represents an example function found in a test source file.

funcExamples

func Examples(testFiles ...*ast.File) []*Example

Examples returns the examples found in testFiles, sorted by Name field.The Order fields record the order in which the examples were encountered.The Suffix field is not populated when Examples is called directly, it isonly populated byNewFromFiles for examples it finds in _test.go files.

Playable Examples must be in a package whose name ends in "_test".An Example is "playable" (the Play field is non-nil) in either of thesecircumstances:

  • The example function is self-contained: the function references onlyidentifiers from other packages (or predeclared identifiers, such as"int") and the test file does not include a dot import.
  • The entire test file is the example: the file contains exactly oneexample function, zero test, fuzz test, or benchmark function, and atleast one top-level function, type, variable, or constant declarationother than the example function.

typeFilter

type Filter func(string)bool

typeFunc

type Func struct {DocstringNamestringDecl *ast.FuncDecl// methods// (for functions, these fields have the respective zero value)Recvstring// actual   receiver "T" or "*T" possibly followed by type parameters [P1, ..., Pn]Origstring// original receiver "T" or "*T"Levelint// embedding level; 0 means not embedded// Examples is a sorted list of examples associated with this// function or method. Examples are extracted from _test.go files// provided to NewFromFiles.Examples []*Example}

Func is the documentation for a func declaration.

typeMode

type Modeint

Mode values control the operation ofNew andNewFromFiles.

const (// AllDecls says to extract documentation for all package-level// declarations, not just exported ones.AllDeclsMode = 1 <<iota// AllMethods says to show all embedded methods, not just the ones of// invisible (unexported) anonymous fields.AllMethods// PreserveAST says to leave the AST unmodified. Originally, pieces of// the AST such as function bodies were nil-ed out to save memory in// godoc, but not all programs want that behavior.PreserveAST)

typeNoteadded ingo1.1

type Note struct {Pos, Endtoken.Pos// position range of the comment containing the markerUIDstring// uid found with the markerBodystring// note body text}

A Note represents a marked comment starting with "MARKER(uid): note body".Any note with a marker of 2 or more upper case [A-Z] letters and a uid ofat least one character is recognized. The ":" following the uid is optional.Notes are collected in the Package.Notes map indexed by the notes marker.

typePackage

type Package struct {DocstringNamestringImportPathstringImports    []stringFilenames  []stringNotes      map[string][]*Note// Deprecated: For backward compatibility Bugs is still populated,// but all new code should use Notes instead.Bugs []string// declarationsConsts []*ValueTypes  []*TypeVars   []*ValueFuncs  []*Func// Examples is a sorted list of examples associated with// the package. Examples are extracted from _test.go files// provided to NewFromFiles.Examples []*Example// contains filtered or unexported fields}

Package is the documentation for an entire package.

funcNew

func New(pkg *ast.Package, importPathstring, modeMode) *Package

New computes the package documentation for the given package AST.New takes ownership of the AST pkg and may edit or overwrite it.To have theExamples fields populated, useNewFromFiles and includethe package's _test.go files.

funcNewFromFilesadded ingo1.14

func NewFromFiles(fset *token.FileSet, files []*ast.File, importPathstring, opts ...any) (*Package,error)

NewFromFiles computes documentation for a package.

The package is specified by a list of *ast.Files and correspondingfile set, which must not be nil.

NewFromFiles uses all provided files when computing documentation,so it is the caller's responsibility to provide only the files thatmatch the desired build context. "go/build".Context.MatchFile canbe used for determining whether a file matches a build context withthe desired GOOS and GOARCH values, and other build constraints.The import path of the package is specified by importPath.

Examples found in _test.go files are associated with the correspondingtype, function, method, or the package, based on their name.If the example has a suffix in its name, it is set in the[Example.Suffix] field.Examples with malformed names are skipped.

Optionally, a single extra argument of typeMode can be provided tocontrol low-level aspects of the documentation extraction behavior.

NewFromFiles takes ownership of the AST files and may edit them,unless the PreserveAST Mode bit is on.

Example

This example illustrates how to use NewFromFilesto compute package documentation with examples.

package mainimport ("fmt""go/ast""go/doc""go/parser""go/token")func main() {// src and test are two source files that make up// a package whose documentation will be computed.const src = `// This is the package comment.package pimport "fmt"// This comment is associated with the Greet function.func Greet(who string) {fmt.Printf("Hello, %s!\n", who)}`const test = `package p_test// This comment is associated with the ExampleGreet_world example.func ExampleGreet_world() {Greet("world")}`// Create the AST by parsing src and test.fset := token.NewFileSet()files := []*ast.File{mustParse(fset, "src.go", src),mustParse(fset, "src_test.go", test),}// Compute package documentation with examples.p, err := doc.NewFromFiles(fset, files, "example.com/p")if err != nil {panic(err)}fmt.Printf("package %s - %s", p.Name, p.Doc)fmt.Printf("func %s - %s", p.Funcs[0].Name, p.Funcs[0].Doc)fmt.Printf(" ⤷ example with suffix %q - %s", p.Funcs[0].Examples[0].Suffix, p.Funcs[0].Examples[0].Doc)}func mustParse(fset *token.FileSet, filename, src string) *ast.File {f, err := parser.ParseFile(fset, filename, src, parser.ParseComments|parser.SkipObjectResolution)if err != nil {panic(err)}return f}
Output:package p - This is the package comment.func Greet - This comment is associated with the Greet function. ⤷ example with suffix "world" - This comment is associated with the ExampleGreet_world example.

func (*Package)Filter

func (p *Package) Filter(fFilter)

Filter eliminates documentation for names that don't pass through the filter f.TODO(gri): Recognize "Type.Method" as a name.

func (*Package)HTMLadded ingo1.19

func (p *Package) HTML(textstring) []byte

HTML returns formatted HTML for the doc comment text.

To customize details of the HTML, usePackage.Printerto obtain acomment.Printer, and configure itbefore calling its HTML method.

func (*Package)Markdownadded ingo1.19

func (p *Package) Markdown(textstring) []byte

Markdown returns formatted Markdown for the doc comment text.

To customize details of the Markdown, usePackage.Printerto obtain acomment.Printer, and configure itbefore calling its Markdown method.

func (*Package)Parseradded ingo1.19

func (p *Package) Parser() *comment.Parser

Parser returns a doc comment parser configuredfor parsing doc comments from package p.Each call returns a new parser, so that the caller maycustomize it before use.

func (*Package)Printeradded ingo1.19

func (p *Package) Printer() *comment.Printer

Printer returns a doc comment printer configuredfor printing doc comments from package p.Each call returns a new printer, so that the caller maycustomize it before use.

func (*Package)Synopsisadded ingo1.19

func (p *Package) Synopsis(textstring)string

Synopsis returns a cleaned version of the first sentence in text.That sentence ends after the first period followed by space and notpreceded by exactly one uppercase letter, or at the first paragraph break.The result string has no \n, \r, or \t characters and uses only singlespaces between words. If text starts with any of theIllegalPrefixes,the result is the empty string.

func (*Package)Textadded ingo1.19

func (p *Package) Text(textstring) []byte

Text returns formatted text for the doc comment text,wrapped to 80 Unicode code points and using tabs forcode block indentation.

To customize details of the formatting, usePackage.Printerto obtain acomment.Printer, and configure itbefore calling its Text method.

typeType

type Type struct {DocstringNamestringDecl *ast.GenDecl// associated declarationsConsts  []*Value// sorted list of constants of (mostly) this typeVars    []*Value// sorted list of variables of (mostly) this typeFuncs   []*Func// sorted list of functions returning this typeMethods []*Func// sorted list of methods (including embedded ones) of this type// Examples is a sorted list of examples associated with// this type. Examples are extracted from _test.go files// provided to NewFromFiles.Examples []*Example}

Type is the documentation for a type declaration.

typeValue

type Value struct {DocstringNames []string// var or const names in declaration orderDecl  *ast.GenDecl// contains filtered or unexported fields}

Value is the documentation for a (possibly grouped) var or const declaration.

Source Files

View all Source files

Directories

PathSynopsis
Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.
Package comment implements parsing and reformatting of Go doc comments, (documentation comments), which are comments that immediately precede a top-level declaration of a package, const, func, type, or var.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp