Source file src/go/doc/example.go

     1  // Copyright 2011 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  // Extract example functions from file ASTs.
     6  
     7  package doc
     8  
     9  import (
    10  	"cmp"
    11  	"go/ast"
    12  	"go/token"
    13  	"internal/lazyregexp"
    14  	"path"
    15  	"slices"
    16  	"strconv"
    17  	"strings"
    18  	"unicode"
    19  	"unicode/utf8"
    20  )
    21  
    22  // An Example represents an example function found in a test source file.
    23  type Example struct {
    24  	Name        string // name of the item being exemplified (including optional suffix)
    25  	Suffix      string // example suffix, without leading '_' (only populated by NewFromFiles)
    26  	Doc         string // example function doc string
    27  	Code        ast.Node
    28  	Play        *ast.File // a whole program version of the example
    29  	Comments    []*ast.CommentGroup
    30  	Output      string // expected output
    31  	Unordered   bool
    32  	EmptyOutput bool // expect empty output
    33  	Order       int  // original source code order
    34  }
    35  
    36  // Examples returns the examples found in testFiles, sorted by Name field.
    37  // The Order fields record the order in which the examples were encountered.
    38  // The Suffix field is not populated when Examples is called directly, it is
    39  // only populated by [NewFromFiles] for examples it finds in _test.go files.
    40  //
    41  // Playable Examples must be in a package whose name ends in "_test".
    42  // An Example is "playable" (the Play field is non-nil) in either of these
    43  // circumstances:
    44  //   - The example function is self-contained: the function references only
    45  //     identifiers from other packages (or predeclared identifiers, such as
    46  //     "int") and the test file does not include a dot import.
    47  //   - The entire test file is the example: the file contains exactly one
    48  //     example function, zero test, fuzz test, or benchmark function, and at
    49  //     least one top-level function, type, variable, or constant declaration
    50  //     other than the example function.
    51  func Examples(testFiles ...*ast.File) []*Example {
    52  	var list []*Example
    53  	for _, file := range testFiles {
    54  		hasTests := false // file contains tests, fuzz test, or benchmarks
    55  		numDecl := 0      // number of non-import declarations in the file
    56  		var flist []*Example
    57  		for _, decl := range file.Decls {
    58  			if g, ok := decl.(*ast.GenDecl); ok && g.Tok != token.IMPORT {
    59  				numDecl++
    60  				continue
    61  			}
    62  			f, ok := decl.(*ast.FuncDecl)
    63  			if !ok || f.Recv != nil {
    64  				continue
    65  			}
    66  			numDecl++
    67  			name := f.Name.Name
    68  			if isTest(name, "Test") || isTest(name, "Benchmark") || isTest(name, "Fuzz") {
    69  				hasTests = true
    70  				continue
    71  			}
    72  			if !isTest(name, "Example") {
    73  				continue
    74  			}
    75  			if params := f.Type.Params; len(params.List) != 0 {
    76  				continue // function has params; not a valid example
    77  			}
    78  			if f.Body == nil { // ast.File.Body nil dereference (see issue 28044)
    79  				continue
    80  			}
    81  			var doc string
    82  			if f.Doc != nil {
    83  				doc = f.Doc.Text()
    84  			}
    85  			output, unordered, hasOutput := exampleOutput(f.Body, file.Comments)
    86  			flist = append(flist, &Example{
    87  				Name:        name[len("Example"):],
    88  				Doc:         doc,
    89  				Code:        f.Body,
    90  				Play:        playExample(file, f),
    91  				Comments:    file.Comments,
    92  				Output:      output,
    93  				Unordered:   unordered,
    94  				EmptyOutput: output == "" && hasOutput,
    95  				Order:       len(flist),
    96  			})
    97  		}
    98  		if !hasTests && numDecl > 1 && len(flist) == 1 {
    99  			// If this file only has one example function, some
   100  			// other top-level declarations, and no tests or
   101  			// benchmarks, use the whole file as the example.
   102  			flist[0].Code = file
   103  			flist[0].Play = playExampleFile(file)
   104  		}
   105  		list = append(list, flist...)
   106  	}
   107  	// sort by name
   108  	slices.SortFunc(list, func(a, b *Example) int {
   109  		return cmp.Compare(a.Name, b.Name)
   110  	})
   111  	return list
   112  }
   113  
   114  var outputPrefix = lazyregexp.New(`(?i)^[[:space:]]*(unordered )?output:`)
   115  
   116  // Extracts the expected output and whether there was a valid output comment.
   117  func exampleOutput(b *ast.BlockStmt, comments []*ast.CommentGroup) (output string, unordered, ok bool) {
   118  	if _, last := lastComment(b, comments); last != nil {
   119  		// test that it begins with the correct prefix
   120  		text := last.Text()
   121  		if loc := outputPrefix.FindStringSubmatchIndex(text); loc != nil {
   122  			if loc[2] != -1 {
   123  				unordered = true
   124  			}
   125  			text = text[loc[1]:]
   126  			// Strip zero or more spaces followed by \n or a single space.
   127  			text = strings.TrimLeft(text, " ")
   128  			if len(text) > 0 && text[0] == '\n' {
   129  				text = text[1:]
   130  			}
   131  			return text, unordered, true
   132  		}
   133  	}
   134  	return "", false, false // no suitable comment found
   135  }
   136  
   137  // isTest tells whether name looks like a test, example, fuzz test, or
   138  // benchmark. It is a Test (say) if there is a character after Test that is not
   139  // a lower-case letter. (We don't want Testiness.)
   140  func isTest(name, prefix string) bool {
   141  	if !strings.HasPrefix(name, prefix) {
   142  		return false
   143  	}
   144  	if len(name) == len(prefix) { // "Test" is ok
   145  		return true
   146  	}
   147  	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
   148  	return !unicode.IsLower(rune)
   149  }
   150  
   151  // playExample synthesizes a new *ast.File based on the provided
   152  // file with the provided function body as the body of main.
   153  func playExample(file *ast.File, f *ast.FuncDecl) *ast.File {
   154  	body := f.Body
   155  
   156  	if !strings.HasSuffix(file.Name.Name, "_test") {
   157  		// We don't support examples that are part of the
   158  		// greater package (yet).
   159  		return nil
   160  	}
   161  
   162  	// Collect top-level declarations in the file.
   163  	topDecls := make(map[*ast.Object]ast.Decl)
   164  	typMethods := make(map[string][]ast.Decl)
   165  
   166  	for _, decl := range file.Decls {
   167  		switch d := decl.(type) {
   168  		case *ast.FuncDecl:
   169  			if d.Recv == nil {
   170  				topDecls[d.Name.Obj] = d
   171  			} else {
   172  				if len(d.Recv.List) == 1 {
   173  					t := d.Recv.List[0].Type
   174  					tname, _ := baseTypeName(t)
   175  					typMethods[tname] = append(typMethods[tname], d)
   176  				}
   177  			}
   178  		case *ast.GenDecl:
   179  			for _, spec := range d.Specs {
   180  				switch s := spec.(type) {
   181  				case *ast.TypeSpec:
   182  					topDecls[s.Name.Obj] = d
   183  				case *ast.ValueSpec:
   184  					for _, name := range s.Names {
   185  						topDecls[name.Obj] = d
   186  					}
   187  				}
   188  			}
   189  		}
   190  	}
   191  
   192  	// Find unresolved identifiers and uses of top-level declarations.
   193  	depDecls, unresolved := findDeclsAndUnresolved(body, topDecls, typMethods)
   194  
   195  	// Use unresolved identifiers to determine the imports used by this
   196  	// example. The heuristic assumes package names match base import
   197  	// paths for imports w/o renames (should be good enough most of the time).
   198  	var namedImports []ast.Spec
   199  	var blankImports []ast.Spec // _ imports
   200  
   201  	// To preserve the blank lines between groups of imports, find the
   202  	// start position of each group, and assign that position to all
   203  	// imports from that group.
   204  	groupStarts := findImportGroupStarts(file.Imports)
   205  	groupStart := func(s *ast.ImportSpec) token.Pos {
   206  		for i, start := range groupStarts {
   207  			if s.Path.ValuePos < start {
   208  				return groupStarts[i-1]
   209  			}
   210  		}
   211  		return groupStarts[len(groupStarts)-1]
   212  	}
   213  
   214  	for _, s := range file.Imports {
   215  		p, err := strconv.Unquote(s.Path.Value)
   216  		if err != nil {
   217  			continue
   218  		}
   219  		if p == "syscall/js" {
   220  			// We don't support examples that import syscall/js,
   221  			// because the package syscall/js is not available in the playground.
   222  			return nil
   223  		}
   224  		n := path.Base(p)
   225  		if s.Name != nil {
   226  			n = s.Name.Name
   227  			switch n {
   228  			case "_":
   229  				blankImports = append(blankImports, s)
   230  				continue
   231  			case ".":
   232  				// We can't resolve dot imports (yet).
   233  				return nil
   234  			}
   235  		}
   236  		if unresolved[n] {
   237  			// Copy the spec and its path to avoid modifying the original.
   238  			spec := *s
   239  			path := *s.Path
   240  			spec.Path = &path
   241  			spec.Path.ValuePos = groupStart(&spec)
   242  			namedImports = append(namedImports, &spec)
   243  			delete(unresolved, n)
   244  		}
   245  	}
   246  
   247  	// Remove predeclared identifiers from unresolved list.
   248  	for n := range unresolved {
   249  		if predeclaredTypes[n] || predeclaredConstants[n] || predeclaredFuncs[n] {
   250  			delete(unresolved, n)
   251  		}
   252  	}
   253  
   254  	// If there are other unresolved identifiers, give up because this
   255  	// synthesized file is not going to build.
   256  	if len(unresolved) > 0 {
   257  		return nil
   258  	}
   259  
   260  	// Include documentation belonging to blank imports.
   261  	var comments []*ast.CommentGroup
   262  	for _, s := range blankImports {
   263  		if c := s.(*ast.ImportSpec).Doc; c != nil {
   264  			comments = append(comments, c)
   265  		}
   266  	}
   267  
   268  	// Include comments that are inside the function body.
   269  	for _, c := range file.Comments {
   270  		if body.Pos() <= c.Pos() && c.End() <= body.End() {
   271  			comments = append(comments, c)
   272  		}
   273  	}
   274  
   275  	// Strip the "Output:" or "Unordered output:" comment and adjust body
   276  	// end position.
   277  	body, comments = stripOutputComment(body, comments)
   278  
   279  	// Include documentation belonging to dependent declarations.
   280  	for _, d := range depDecls {
   281  		switch d := d.(type) {
   282  		case *ast.GenDecl:
   283  			if d.Doc != nil {
   284  				comments = append(comments, d.Doc)
   285  			}
   286  		case *ast.FuncDecl:
   287  			if d.Doc != nil {
   288  				comments = append(comments, d.Doc)
   289  			}
   290  		}
   291  	}
   292  
   293  	// Synthesize import declaration.
   294  	importDecl := &ast.GenDecl{
   295  		Tok:    token.IMPORT,
   296  		Lparen: 1, // Need non-zero Lparen and Rparen so that printer
   297  		Rparen: 1, // treats this as a factored import.
   298  	}
   299  	importDecl.Specs = append(namedImports, blankImports...)
   300  
   301  	// Synthesize main function.
   302  	funcDecl := &ast.FuncDecl{
   303  		Name: ast.NewIdent("main"),
   304  		Type: f.Type,
   305  		Body: body,
   306  	}
   307  
   308  	decls := make([]ast.Decl, 0, 2+len(depDecls))
   309  	decls = append(decls, importDecl)
   310  	decls = append(decls, depDecls...)
   311  	decls = append(decls, funcDecl)
   312  
   313  	slices.SortFunc(decls, func(a, b ast.Decl) int {
   314  		return cmp.Compare(a.Pos(), b.Pos())
   315  	})
   316  	slices.SortFunc(comments, func(a, b *ast.CommentGroup) int {
   317  		return cmp.Compare(a.Pos(), b.Pos())
   318  	})
   319  
   320  	// Synthesize file.
   321  	return &ast.File{
   322  		Name:     ast.NewIdent("main"),
   323  		Decls:    decls,
   324  		Comments: comments,
   325  	}
   326  }
   327  
   328  // findDeclsAndUnresolved returns all the top-level declarations mentioned in
   329  // the body, and a set of unresolved symbols (those that appear in the body but
   330  // have no declaration in the program).
   331  //
   332  // topDecls maps objects to the top-level declaration declaring them (not
   333  // necessarily obj.Decl, as obj.Decl will be a Spec for GenDecls, but
   334  // topDecls[obj] will be the GenDecl itself).
   335  func findDeclsAndUnresolved(body ast.Node, topDecls map[*ast.Object]ast.Decl, typMethods map[string][]ast.Decl) ([]ast.Decl, map[string]bool) {
   336  	// This function recursively finds every top-level declaration used
   337  	// transitively by the body, populating usedDecls and usedObjs. Then it
   338  	// trims down the declarations to include only the symbols actually
   339  	// referenced by the body.
   340  
   341  	unresolved := make(map[string]bool)
   342  	var depDecls []ast.Decl
   343  	usedDecls := make(map[ast.Decl]bool)   // set of top-level decls reachable from the body
   344  	usedObjs := make(map[*ast.Object]bool) // set of objects reachable from the body (each declared by a usedDecl)
   345  
   346  	var inspectFunc func(ast.Node) bool
   347  	inspectFunc = func(n ast.Node) bool {
   348  		switch e := n.(type) {
   349  		case *ast.Ident:
   350  			if e.Obj == nil && e.Name != "_" {
   351  				unresolved[e.Name] = true
   352  			} else if d := topDecls[e.Obj]; d != nil {
   353  
   354  				usedObjs[e.Obj] = true
   355  				if !usedDecls[d] {
   356  					usedDecls[d] = true
   357  					depDecls = append(depDecls, d)
   358  				}
   359  			}
   360  			return true
   361  		case *ast.SelectorExpr:
   362  			// For selector expressions, only inspect the left hand side.
   363  			// (For an expression like fmt.Println, only add "fmt" to the
   364  			// set of unresolved names, not "Println".)
   365  			ast.Inspect(e.X, inspectFunc)
   366  			return false
   367  		case *ast.KeyValueExpr:
   368  			// For key value expressions, only inspect the value
   369  			// as the key should be resolved by the type of the
   370  			// composite literal.
   371  			ast.Inspect(e.Value, inspectFunc)
   372  			return false
   373  		}
   374  		return true
   375  	}
   376  
   377  	inspectFieldList := func(fl *ast.FieldList) {
   378  		if fl != nil {
   379  			for _, f := range fl.List {
   380  				ast.Inspect(f.Type, inspectFunc)
   381  			}
   382  		}
   383  	}
   384  
   385  	// Find the decls immediately referenced by body.
   386  	ast.Inspect(body, inspectFunc)
   387  	// Now loop over them, adding to the list when we find a new decl that the
   388  	// body depends on. Keep going until we don't find anything new.
   389  	for i := 0; i < len(depDecls); i++ {
   390  		switch d := depDecls[i].(type) {
   391  		case *ast.FuncDecl:
   392  			// Inspect type parameters.
   393  			inspectFieldList(d.Type.TypeParams)
   394  			// Inspect types of parameters and results. See #28492.
   395  			inspectFieldList(d.Type.Params)
   396  			inspectFieldList(d.Type.Results)
   397  
   398  			// Functions might not have a body. See #42706.
   399  			if d.Body != nil {
   400  				ast.Inspect(d.Body, inspectFunc)
   401  			}
   402  		case *ast.GenDecl:
   403  			for _, spec := range d.Specs {
   404  				switch s := spec.(type) {
   405  				case *ast.TypeSpec:
   406  					inspectFieldList(s.TypeParams)
   407  					ast.Inspect(s.Type, inspectFunc)
   408  					depDecls = append(depDecls, typMethods[s.Name.Name]...)
   409  				case *ast.ValueSpec:
   410  					if s.Type != nil {
   411  						ast.Inspect(s.Type, inspectFunc)
   412  					}
   413  					for _, val := range s.Values {
   414  						ast.Inspect(val, inspectFunc)
   415  					}
   416  				}
   417  			}
   418  		}
   419  	}
   420  
   421  	// Some decls include multiple specs, such as a variable declaration with
   422  	// multiple variables on the same line, or a parenthesized declaration. Trim
   423  	// the declarations to include only the specs that are actually mentioned.
   424  	// However, if there is a constant group with iota, leave it all: later
   425  	// constant declarations in the group may have no value and so cannot stand
   426  	// on their own, and removing any constant from the group could change the
   427  	// values of subsequent ones.
   428  	// See testdata/examples/iota.go for a minimal example.
   429  	var ds []ast.Decl
   430  	for _, d := range depDecls {
   431  		switch d := d.(type) {
   432  		case *ast.FuncDecl:
   433  			ds = append(ds, d)
   434  		case *ast.GenDecl:
   435  			containsIota := false // does any spec have iota?
   436  			// Collect all Specs that were mentioned in the example.
   437  			var specs []ast.Spec
   438  			for _, s := range d.Specs {
   439  				switch s := s.(type) {
   440  				case *ast.TypeSpec:
   441  					if usedObjs[s.Name.Obj] {
   442  						specs = append(specs, s)
   443  					}
   444  				case *ast.ValueSpec:
   445  					if !containsIota {
   446  						containsIota = hasIota(s)
   447  					}
   448  					// A ValueSpec may have multiple names (e.g. "var a, b int").
   449  					// Keep only the names that were mentioned in the example.
   450  					// Exception: the multiple names have a single initializer (which
   451  					// would be a function call with multiple return values). In that
   452  					// case, keep everything.
   453  					if len(s.Names) > 1 && len(s.Values) == 1 {
   454  						specs = append(specs, s)
   455  						continue
   456  					}
   457  					ns := *s
   458  					ns.Names = nil
   459  					ns.Values = nil
   460  					for i, n := range s.Names {
   461  						if usedObjs[n.Obj] {
   462  							ns.Names = append(ns.Names, n)
   463  							if s.Values != nil {
   464  								ns.Values = append(ns.Values, s.Values[i])
   465  							}
   466  						}
   467  					}
   468  					if len(ns.Names) > 0 {
   469  						specs = append(specs, &ns)
   470  					}
   471  				}
   472  			}
   473  			if len(specs) > 0 {
   474  				// Constant with iota? Keep it all.
   475  				if d.Tok == token.CONST && containsIota {
   476  					ds = append(ds, d)
   477  				} else {
   478  					// Synthesize a GenDecl with just the Specs we need.
   479  					nd := *d // copy the GenDecl
   480  					nd.Specs = specs
   481  					if len(specs) == 1 {
   482  						// Remove grouping parens if there is only one spec.
   483  						nd.Lparen = 0
   484  					}
   485  					ds = append(ds, &nd)
   486  				}
   487  			}
   488  		}
   489  	}
   490  	return ds, unresolved
   491  }
   492  
   493  func hasIota(s ast.Spec) bool {
   494  	for n := range ast.Preorder(s) {
   495  		// Check that this is the special built-in "iota" identifier, not
   496  		// a user-defined shadow.
   497  		if id, ok := n.(*ast.Ident); ok && id.Name == "iota" && id.Obj == nil {
   498  			return true
   499  		}
   500  	}
   501  	return false
   502  }
   503  
   504  // findImportGroupStarts finds the start positions of each sequence of import
   505  // specs that are not separated by a blank line.
   506  func findImportGroupStarts(imps []*ast.ImportSpec) []token.Pos {
   507  	startImps := findImportGroupStarts1(imps)
   508  	groupStarts := make([]token.Pos, len(startImps))
   509  	for i, imp := range startImps {
   510  		groupStarts[i] = imp.Pos()
   511  	}
   512  	return groupStarts
   513  }
   514  
   515  // Helper for findImportGroupStarts to ease testing.
   516  func findImportGroupStarts1(origImps []*ast.ImportSpec) []*ast.ImportSpec {
   517  	// Copy to avoid mutation.
   518  	imps := make([]*ast.ImportSpec, len(origImps))
   519  	copy(imps, origImps)
   520  	// Assume the imports are sorted by position.
   521  	slices.SortFunc(imps, func(a, b *ast.ImportSpec) int {
   522  		return cmp.Compare(a.Pos(), b.Pos())
   523  	})
   524  	// Assume gofmt has been applied, so there is a blank line between adjacent imps
   525  	// if and only if they are more than 2 positions apart (newline, tab).
   526  	var groupStarts []*ast.ImportSpec
   527  	prevEnd := token.Pos(-2)
   528  	for _, imp := range imps {
   529  		if imp.Pos()-prevEnd > 2 {
   530  			groupStarts = append(groupStarts, imp)
   531  		}
   532  		prevEnd = imp.End()
   533  		// Account for end-of-line comments.
   534  		if imp.Comment != nil {
   535  			prevEnd = imp.Comment.End()
   536  		}
   537  	}
   538  	return groupStarts
   539  }
   540  
   541  // playExampleFile takes a whole file example and synthesizes a new *ast.File
   542  // such that the example is function main in package main.
   543  func playExampleFile(file *ast.File) *ast.File {
   544  	// Strip copyright comment if present.
   545  	comments := file.Comments
   546  	if len(comments) > 0 && strings.HasPrefix(comments[0].Text(), "Copyright") {
   547  		comments = comments[1:]
   548  	}
   549  
   550  	// Copy declaration slice, rewriting the ExampleX function to main.
   551  	var decls []ast.Decl
   552  	for _, d := range file.Decls {
   553  		if f, ok := d.(*ast.FuncDecl); ok && isTest(f.Name.Name, "Example") {
   554  			// Copy the FuncDecl, as it may be used elsewhere.
   555  			newF := *f
   556  			newF.Name = ast.NewIdent("main")
   557  			newF.Body, comments = stripOutputComment(f.Body, comments)
   558  			d = &newF
   559  		}
   560  		decls = append(decls, d)
   561  	}
   562  
   563  	// Copy the File, as it may be used elsewhere.
   564  	f := *file
   565  	f.Name = ast.NewIdent("main")
   566  	f.Decls = decls
   567  	f.Comments = comments
   568  	return &f
   569  }
   570  
   571  // stripOutputComment finds and removes the "Output:" or "Unordered output:"
   572  // comment from body and comments, and adjusts the body block's end position.
   573  func stripOutputComment(body *ast.BlockStmt, comments []*ast.CommentGroup) (*ast.BlockStmt, []*ast.CommentGroup) {
   574  	// Do nothing if there is no "Output:" or "Unordered output:" comment.
   575  	i, last := lastComment(body, comments)
   576  	if last == nil || !outputPrefix.MatchString(last.Text()) {
   577  		return body, comments
   578  	}
   579  
   580  	// Copy body and comments, as the originals may be used elsewhere.
   581  	newBody := &ast.BlockStmt{
   582  		Lbrace: body.Lbrace,
   583  		List:   body.List,
   584  		Rbrace: last.Pos(),
   585  	}
   586  	newComments := make([]*ast.CommentGroup, len(comments)-1)
   587  	copy(newComments, comments[:i])
   588  	copy(newComments[i:], comments[i+1:])
   589  	return newBody, newComments
   590  }
   591  
   592  // lastComment returns the last comment inside the provided block.
   593  func lastComment(b *ast.BlockStmt, c []*ast.CommentGroup) (i int, last *ast.CommentGroup) {
   594  	if b == nil {
   595  		return
   596  	}
   597  	pos, end := b.Pos(), b.End()
   598  	for j, cg := range c {
   599  		if cg.Pos() < pos {
   600  			continue
   601  		}
   602  		if cg.End() > end {
   603  			break
   604  		}
   605  		i, last = j, cg
   606  	}
   607  	return
   608  }
   609  
   610  // classifyExamples classifies examples and assigns them to the Examples field
   611  // of the relevant Func, Type, or Package that the example is associated with.
   612  //
   613  // The classification process is ambiguous in some cases:
   614  //
   615  //   - ExampleFoo_Bar matches a type named Foo_Bar
   616  //     or a method named Foo.Bar.
   617  //   - ExampleFoo_bar matches a type named Foo_bar
   618  //     or Foo (with a "bar" suffix).
   619  //
   620  // Examples with malformed names are not associated with anything.
   621  func classifyExamples(p *Package, examples []*Example) {
   622  	if len(examples) == 0 {
   623  		return
   624  	}
   625  	// Mapping of names for funcs, types, and methods to the example listing.
   626  	ids := make(map[string]*[]*Example)
   627  	ids[""] = &p.Examples // package-level examples have an empty name
   628  	for _, f := range p.Funcs {
   629  		if !token.IsExported(f.Name) {
   630  			continue
   631  		}
   632  		ids[f.Name] = &f.Examples
   633  	}
   634  	for _, t := range p.Types {
   635  		if !token.IsExported(t.Name) {
   636  			continue
   637  		}
   638  		ids[t.Name] = &t.Examples
   639  		for _, f := range t.Funcs {
   640  			if !token.IsExported(f.Name) {
   641  				continue
   642  			}
   643  			ids[f.Name] = &f.Examples
   644  		}
   645  		for _, m := range t.Methods {
   646  			if !token.IsExported(m.Name) {
   647  				continue
   648  			}
   649  			ids[strings.TrimPrefix(nameWithoutInst(m.Recv), "*")+"_"+m.Name] = &m.Examples
   650  		}
   651  	}
   652  
   653  	// Group each example with the associated func, type, or method.
   654  	for _, ex := range examples {
   655  		// Consider all possible split points for the suffix
   656  		// by starting at the end of string (no suffix case),
   657  		// then trying all positions that contain a '_' character.
   658  		//
   659  		// An association is made on the first successful match.
   660  		// Examples with malformed names that match nothing are skipped.
   661  		for i := len(ex.Name); i >= 0; i = strings.LastIndexByte(ex.Name[:i], '_') {
   662  			prefix, suffix, ok := splitExampleName(ex.Name, i)
   663  			if !ok {
   664  				continue
   665  			}
   666  			exs, ok := ids[prefix]
   667  			if !ok {
   668  				continue
   669  			}
   670  			ex.Suffix = suffix
   671  			*exs = append(*exs, ex)
   672  			break
   673  		}
   674  	}
   675  
   676  	// Sort list of example according to the user-specified suffix name.
   677  	for _, exs := range ids {
   678  		slices.SortFunc(*exs, func(a, b *Example) int {
   679  			return cmp.Compare(a.Suffix, b.Suffix)
   680  		})
   681  	}
   682  }
   683  
   684  // nameWithoutInst returns name if name has no brackets. If name contains
   685  // brackets, then it returns name with all the contents between (and including)
   686  // the outermost left and right bracket removed.
   687  //
   688  // Adapted from debug/gosym/symtab.go:Sym.nameWithoutInst.
   689  func nameWithoutInst(name string) string {
   690  	start := strings.Index(name, "[")
   691  	if start < 0 {
   692  		return name
   693  	}
   694  	end := strings.LastIndex(name, "]")
   695  	if end < 0 {
   696  		// Malformed name, should contain closing bracket too.
   697  		return name
   698  	}
   699  	return name[0:start] + name[end+1:]
   700  }
   701  
   702  // splitExampleName attempts to split example name s at index i,
   703  // and reports if that produces a valid split. The suffix may be
   704  // absent. Otherwise, it must start with a lower-case letter and
   705  // be preceded by '_'.
   706  //
   707  // One of i == len(s) or s[i] == '_' must be true.
   708  func splitExampleName(s string, i int) (prefix, suffix string, ok bool) {
   709  	if i == len(s) {
   710  		return s, "", true
   711  	}
   712  	if i == len(s)-1 {
   713  		return "", "", false
   714  	}
   715  	prefix, suffix = s[:i], s[i+1:]
   716  	return prefix, suffix, isExampleSuffix(suffix)
   717  }
   718  
   719  func isExampleSuffix(s string) bool {
   720  	r, size := utf8.DecodeRuneInString(s)
   721  	return size > 0 && unicode.IsLower(r)
   722  }
   723  

View as plain text