...
Run Format

Source file src/go/doc/example.go

Documentation: go/doc

     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  	"go/ast"
    11  	"go/token"
    12  	"path"
    13  	"regexp"
    14  	"sort"
    15  	"strconv"
    16  	"strings"
    17  	"unicode"
    18  	"unicode/utf8"
    19  )
    20  
    21  // An Example represents an example function found in a source files.
    22  type Example struct {
    23  	Name        string // name of the item being exemplified
    24  	Doc         string // example function doc string
    25  	Code        ast.Node
    26  	Play        *ast.File // a whole program version of the example
    27  	Comments    []*ast.CommentGroup
    28  	Output      string // expected output
    29  	Unordered   bool
    30  	EmptyOutput bool // expect empty output
    31  	Order       int  // original source code order
    32  }
    33  
    34  // Examples returns the examples found in the files, sorted by Name field.
    35  // The Order fields record the order in which the examples were encountered.
    36  //
    37  // Playable Examples must be in a package whose name ends in "_test".
    38  // An Example is "playable" (the Play field is non-nil) in either of these
    39  // circumstances:
    40  //   - The example function is self-contained: the function references only
    41  //     identifiers from other packages (or predeclared identifiers, such as
    42  //     "int") and the test file does not include a dot import.
    43  //   - The entire test file is the example: the file contains exactly one
    44  //     example function, zero test or benchmark functions, and at least one
    45  //     top-level function, type, variable, or constant declaration other
    46  //     than the example function.
    47  func Examples(files ...*ast.File) []*Example {
    48  	var list []*Example
    49  	for _, file := range files {
    50  		hasTests := false // file contains tests or benchmarks
    51  		numDecl := 0      // number of non-import declarations in the file
    52  		var flist []*Example
    53  		for _, decl := range file.Decls {
    54  			if g, ok := decl.(*ast.GenDecl); ok && g.Tok != token.IMPORT {
    55  				numDecl++
    56  				continue
    57  			}
    58  			f, ok := decl.(*ast.FuncDecl)
    59  			if !ok || f.Recv != nil {
    60  				continue
    61  			}
    62  			numDecl++
    63  			name := f.Name.Name
    64  			if isTest(name, "Test") || isTest(name, "Benchmark") {
    65  				hasTests = true
    66  				continue
    67  			}
    68  			if !isTest(name, "Example") {
    69  				continue
    70  			}
    71  			var doc string
    72  			if f.Doc != nil {
    73  				doc = f.Doc.Text()
    74  			}
    75  			output, unordered, hasOutput := exampleOutput(f.Body, file.Comments)
    76  			flist = append(flist, &Example{
    77  				Name:        name[len("Example"):],
    78  				Doc:         doc,
    79  				Code:        f.Body,
    80  				Play:        playExample(file, f),
    81  				Comments:    file.Comments,
    82  				Output:      output,
    83  				Unordered:   unordered,
    84  				EmptyOutput: output == "" && hasOutput,
    85  				Order:       len(flist),
    86  			})
    87  		}
    88  		if !hasTests && numDecl > 1 && len(flist) == 1 {
    89  			// If this file only has one example function, some
    90  			// other top-level declarations, and no tests or
    91  			// benchmarks, use the whole file as the example.
    92  			flist[0].Code = file
    93  			flist[0].Play = playExampleFile(file)
    94  		}
    95  		list = append(list, flist...)
    96  	}
    97  	// sort by name
    98  	sort.Slice(list, func(i, j int) bool {
    99  		return list[i].Name < list[j].Name
   100  	})
   101  	return list
   102  }
   103  
   104  var outputPrefix = regexp.MustCompile(`(?i)^[[:space:]]*(unordered )?output:`)
   105  
   106  // Extracts the expected output and whether there was a valid output comment
   107  func exampleOutput(b *ast.BlockStmt, comments []*ast.CommentGroup) (output string, unordered, ok bool) {
   108  	if _, last := lastComment(b, comments); last != nil {
   109  		// test that it begins with the correct prefix
   110  		text := last.Text()
   111  		if loc := outputPrefix.FindStringSubmatchIndex(text); loc != nil {
   112  			if loc[2] != -1 {
   113  				unordered = true
   114  			}
   115  			text = text[loc[1]:]
   116  			// Strip zero or more spaces followed by \n or a single space.
   117  			text = strings.TrimLeft(text, " ")
   118  			if len(text) > 0 && text[0] == '\n' {
   119  				text = text[1:]
   120  			}
   121  			return text, unordered, true
   122  		}
   123  	}
   124  	return "", false, false // no suitable comment found
   125  }
   126  
   127  // isTest tells whether name looks like a test, example, or benchmark.
   128  // It is a Test (say) if there is a character after Test that is not a
   129  // lower-case letter. (We don't want Testiness.)
   130  func isTest(name, prefix string) bool {
   131  	if !strings.HasPrefix(name, prefix) {
   132  		return false
   133  	}
   134  	if len(name) == len(prefix) { // "Test" is ok
   135  		return true
   136  	}
   137  	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
   138  	return !unicode.IsLower(rune)
   139  }
   140  
   141  // playExample synthesizes a new *ast.File based on the provided
   142  // file with the provided function body as the body of main.
   143  func playExample(file *ast.File, f *ast.FuncDecl) *ast.File {
   144  	body := f.Body
   145  
   146  	if !strings.HasSuffix(file.Name.Name, "_test") {
   147  		// We don't support examples that are part of the
   148  		// greater package (yet).
   149  		return nil
   150  	}
   151  
   152  	// Collect top-level declarations in the file.
   153  	topDecls := make(map[*ast.Object]ast.Decl)
   154  	typMethods := make(map[string][]ast.Decl)
   155  
   156  	for _, decl := range file.Decls {
   157  		switch d := decl.(type) {
   158  		case *ast.FuncDecl:
   159  			if d.Recv == nil {
   160  				topDecls[d.Name.Obj] = d
   161  			} else {
   162  				if len(d.Recv.List) == 1 {
   163  					t := d.Recv.List[0].Type
   164  					tname, _ := baseTypeName(t)
   165  					typMethods[tname] = append(typMethods[tname], d)
   166  				}
   167  			}
   168  		case *ast.GenDecl:
   169  			for _, spec := range d.Specs {
   170  				switch s := spec.(type) {
   171  				case *ast.TypeSpec:
   172  					topDecls[s.Name.Obj] = d
   173  				case *ast.ValueSpec:
   174  					for _, name := range s.Names {
   175  						topDecls[name.Obj] = d
   176  					}
   177  				}
   178  			}
   179  		}
   180  	}
   181  
   182  	// Find unresolved identifiers and uses of top-level declarations.
   183  	unresolved := make(map[string]bool)
   184  	var depDecls []ast.Decl
   185  	hasDepDecls := make(map[ast.Decl]bool)
   186  
   187  	var inspectFunc func(ast.Node) bool
   188  	inspectFunc = func(n ast.Node) bool {
   189  		switch e := n.(type) {
   190  		case *ast.Ident:
   191  			if e.Obj == nil && e.Name != "_" {
   192  				unresolved[e.Name] = true
   193  			} else if d := topDecls[e.Obj]; d != nil {
   194  				if !hasDepDecls[d] {
   195  					hasDepDecls[d] = true
   196  					depDecls = append(depDecls, d)
   197  				}
   198  			}
   199  			return true
   200  		case *ast.SelectorExpr:
   201  			// For selector expressions, only inspect the left hand side.
   202  			// (For an expression like fmt.Println, only add "fmt" to the
   203  			// set of unresolved names, not "Println".)
   204  			ast.Inspect(e.X, inspectFunc)
   205  			return false
   206  		case *ast.KeyValueExpr:
   207  			// For key value expressions, only inspect the value
   208  			// as the key should be resolved by the type of the
   209  			// composite literal.
   210  			ast.Inspect(e.Value, inspectFunc)
   211  			return false
   212  		}
   213  		return true
   214  	}
   215  	ast.Inspect(body, inspectFunc)
   216  	for i := 0; i < len(depDecls); i++ {
   217  		switch d := depDecls[i].(type) {
   218  		case *ast.FuncDecl:
   219  			ast.Inspect(d.Body, inspectFunc)
   220  		case *ast.GenDecl:
   221  			for _, spec := range d.Specs {
   222  				switch s := spec.(type) {
   223  				case *ast.TypeSpec:
   224  					ast.Inspect(s.Type, inspectFunc)
   225  
   226  					depDecls = append(depDecls, typMethods[s.Name.Name]...)
   227  				case *ast.ValueSpec:
   228  					if s.Type != nil {
   229  						ast.Inspect(s.Type, inspectFunc)
   230  					}
   231  					for _, val := range s.Values {
   232  						ast.Inspect(val, inspectFunc)
   233  					}
   234  				}
   235  			}
   236  		}
   237  	}
   238  
   239  	// Remove predeclared identifiers from unresolved list.
   240  	for n := range unresolved {
   241  		if predeclaredTypes[n] || predeclaredConstants[n] || predeclaredFuncs[n] {
   242  			delete(unresolved, n)
   243  		}
   244  	}
   245  
   246  	// Use unresolved identifiers to determine the imports used by this
   247  	// example. The heuristic assumes package names match base import
   248  	// paths for imports w/o renames (should be good enough most of the time).
   249  	namedImports := make(map[string]string) // [name]path
   250  	var blankImports []ast.Spec             // _ imports
   251  	for _, s := range file.Imports {
   252  		p, err := strconv.Unquote(s.Path.Value)
   253  		if err != nil {
   254  			continue
   255  		}
   256  		n := path.Base(p)
   257  		if s.Name != nil {
   258  			n = s.Name.Name
   259  			switch n {
   260  			case "_":
   261  				blankImports = append(blankImports, s)
   262  				continue
   263  			case ".":
   264  				// We can't resolve dot imports (yet).
   265  				return nil
   266  			}
   267  		}
   268  		if unresolved[n] {
   269  			namedImports[n] = p
   270  			delete(unresolved, n)
   271  		}
   272  	}
   273  
   274  	// If there are other unresolved identifiers, give up because this
   275  	// synthesized file is not going to build.
   276  	if len(unresolved) > 0 {
   277  		return nil
   278  	}
   279  
   280  	// Include documentation belonging to blank imports.
   281  	var comments []*ast.CommentGroup
   282  	for _, s := range blankImports {
   283  		if c := s.(*ast.ImportSpec).Doc; c != nil {
   284  			comments = append(comments, c)
   285  		}
   286  	}
   287  
   288  	// Include comments that are inside the function body.
   289  	for _, c := range file.Comments {
   290  		if body.Pos() <= c.Pos() && c.End() <= body.End() {
   291  			comments = append(comments, c)
   292  		}
   293  	}
   294  
   295  	// Strip the "Output:" or "Unordered output:" comment and adjust body
   296  	// end position.
   297  	body, comments = stripOutputComment(body, comments)
   298  
   299  	// Include documentation belonging to dependent declarations.
   300  	for _, d := range depDecls {
   301  		switch d := d.(type) {
   302  		case *ast.GenDecl:
   303  			if d.Doc != nil {
   304  				comments = append(comments, d.Doc)
   305  			}
   306  		case *ast.FuncDecl:
   307  			if d.Doc != nil {
   308  				comments = append(comments, d.Doc)
   309  			}
   310  		}
   311  	}
   312  
   313  	// Synthesize import declaration.
   314  	importDecl := &ast.GenDecl{
   315  		Tok:    token.IMPORT,
   316  		Lparen: 1, // Need non-zero Lparen and Rparen so that printer
   317  		Rparen: 1, // treats this as a factored import.
   318  	}
   319  	for n, p := range namedImports {
   320  		s := &ast.ImportSpec{Path: &ast.BasicLit{Value: strconv.Quote(p)}}
   321  		if path.Base(p) != n {
   322  			s.Name = ast.NewIdent(n)
   323  		}
   324  		importDecl.Specs = append(importDecl.Specs, s)
   325  	}
   326  	importDecl.Specs = append(importDecl.Specs, blankImports...)
   327  
   328  	// Synthesize main function.
   329  	funcDecl := &ast.FuncDecl{
   330  		Name: ast.NewIdent("main"),
   331  		Type: f.Type,
   332  		Body: body,
   333  	}
   334  
   335  	decls := make([]ast.Decl, 0, 2+len(depDecls))
   336  	decls = append(decls, importDecl)
   337  	decls = append(decls, depDecls...)
   338  	decls = append(decls, funcDecl)
   339  
   340  	sort.Slice(decls, func(i, j int) bool {
   341  		return decls[i].Pos() < decls[j].Pos()
   342  	})
   343  
   344  	sort.Slice(comments, func(i, j int) bool {
   345  		return comments[i].Pos() < comments[j].Pos()
   346  	})
   347  
   348  	// Synthesize file.
   349  	return &ast.File{
   350  		Name:     ast.NewIdent("main"),
   351  		Decls:    decls,
   352  		Comments: comments,
   353  	}
   354  }
   355  
   356  // playExampleFile takes a whole file example and synthesizes a new *ast.File
   357  // such that the example is function main in package main.
   358  func playExampleFile(file *ast.File) *ast.File {
   359  	// Strip copyright comment if present.
   360  	comments := file.Comments
   361  	if len(comments) > 0 && strings.HasPrefix(comments[0].Text(), "Copyright") {
   362  		comments = comments[1:]
   363  	}
   364  
   365  	// Copy declaration slice, rewriting the ExampleX function to main.
   366  	var decls []ast.Decl
   367  	for _, d := range file.Decls {
   368  		if f, ok := d.(*ast.FuncDecl); ok && isTest(f.Name.Name, "Example") {
   369  			// Copy the FuncDecl, as it may be used elsewhere.
   370  			newF := *f
   371  			newF.Name = ast.NewIdent("main")
   372  			newF.Body, comments = stripOutputComment(f.Body, comments)
   373  			d = &newF
   374  		}
   375  		decls = append(decls, d)
   376  	}
   377  
   378  	// Copy the File, as it may be used elsewhere.
   379  	f := *file
   380  	f.Name = ast.NewIdent("main")
   381  	f.Decls = decls
   382  	f.Comments = comments
   383  	return &f
   384  }
   385  
   386  // stripOutputComment finds and removes the "Output:" or "Unordered output:"
   387  // comment from body and comments, and adjusts the body block's end position.
   388  func stripOutputComment(body *ast.BlockStmt, comments []*ast.CommentGroup) (*ast.BlockStmt, []*ast.CommentGroup) {
   389  	// Do nothing if there is no "Output:" or "Unordered output:" comment.
   390  	i, last := lastComment(body, comments)
   391  	if last == nil || !outputPrefix.MatchString(last.Text()) {
   392  		return body, comments
   393  	}
   394  
   395  	// Copy body and comments, as the originals may be used elsewhere.
   396  	newBody := &ast.BlockStmt{
   397  		Lbrace: body.Lbrace,
   398  		List:   body.List,
   399  		Rbrace: last.Pos(),
   400  	}
   401  	newComments := make([]*ast.CommentGroup, len(comments)-1)
   402  	copy(newComments, comments[:i])
   403  	copy(newComments[i:], comments[i+1:])
   404  	return newBody, newComments
   405  }
   406  
   407  // lastComment returns the last comment inside the provided block.
   408  func lastComment(b *ast.BlockStmt, c []*ast.CommentGroup) (i int, last *ast.CommentGroup) {
   409  	pos, end := b.Pos(), b.End()
   410  	for j, cg := range c {
   411  		if cg.Pos() < pos {
   412  			continue
   413  		}
   414  		if cg.End() > end {
   415  			break
   416  		}
   417  		i, last = j, cg
   418  	}
   419  	return
   420  }
   421  

View as plain text