...
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 {
    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.Body),
    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, body *ast.BlockStmt) *ast.File {
   144  	if !strings.HasSuffix(file.Name.Name, "_test") {
   145  		// We don't support examples that are part of the
   146  		// greater package (yet).
   147  		return nil
   148  	}
   149  
   150  	// Find top-level declarations in the file.
   151  	topDecls := make(map[*ast.Object]bool)
   152  	for _, decl := range file.Decls {
   153  		switch d := decl.(type) {
   154  		case *ast.FuncDecl:
   155  			topDecls[d.Name.Obj] = true
   156  		case *ast.GenDecl:
   157  			for _, spec := range d.Specs {
   158  				switch s := spec.(type) {
   159  				case *ast.TypeSpec:
   160  					topDecls[s.Name.Obj] = true
   161  				case *ast.ValueSpec:
   162  					for _, id := range s.Names {
   163  						topDecls[id.Obj] = true
   164  					}
   165  				}
   166  			}
   167  		}
   168  	}
   169  
   170  	// Find unresolved identifiers and uses of top-level declarations.
   171  	unresolved := make(map[string]bool)
   172  	usesTopDecl := false
   173  	var inspectFunc func(ast.Node) bool
   174  	inspectFunc = func(n ast.Node) bool {
   175  		// For selector expressions, only inspect the left hand side.
   176  		// (For an expression like fmt.Println, only add "fmt" to the
   177  		// set of unresolved names, not "Println".)
   178  		if e, ok := n.(*ast.SelectorExpr); ok {
   179  			ast.Inspect(e.X, inspectFunc)
   180  			return false
   181  		}
   182  		// For key value expressions, only inspect the value
   183  		// as the key should be resolved by the type of the
   184  		// composite literal.
   185  		if e, ok := n.(*ast.KeyValueExpr); ok {
   186  			ast.Inspect(e.Value, inspectFunc)
   187  			return false
   188  		}
   189  		if id, ok := n.(*ast.Ident); ok {
   190  			if id.Obj == nil {
   191  				unresolved[id.Name] = true
   192  			} else if topDecls[id.Obj] {
   193  				usesTopDecl = true
   194  			}
   195  		}
   196  		return true
   197  	}
   198  	ast.Inspect(body, inspectFunc)
   199  	if usesTopDecl {
   200  		// We don't support examples that are not self-contained (yet).
   201  		return nil
   202  	}
   203  
   204  	// Remove predeclared identifiers from unresolved list.
   205  	for n := range unresolved {
   206  		if predeclaredTypes[n] || predeclaredConstants[n] || predeclaredFuncs[n] {
   207  			delete(unresolved, n)
   208  		}
   209  	}
   210  
   211  	// Use unresolved identifiers to determine the imports used by this
   212  	// example. The heuristic assumes package names match base import
   213  	// paths for imports w/o renames (should be good enough most of the time).
   214  	namedImports := make(map[string]string) // [name]path
   215  	var blankImports []ast.Spec             // _ imports
   216  	for _, s := range file.Imports {
   217  		p, err := strconv.Unquote(s.Path.Value)
   218  		if err != nil {
   219  			continue
   220  		}
   221  		n := path.Base(p)
   222  		if s.Name != nil {
   223  			n = s.Name.Name
   224  			switch n {
   225  			case "_":
   226  				blankImports = append(blankImports, s)
   227  				continue
   228  			case ".":
   229  				// We can't resolve dot imports (yet).
   230  				return nil
   231  			}
   232  		}
   233  		if unresolved[n] {
   234  			namedImports[n] = p
   235  			delete(unresolved, n)
   236  		}
   237  	}
   238  
   239  	// If there are other unresolved identifiers, give up because this
   240  	// synthesized file is not going to build.
   241  	if len(unresolved) > 0 {
   242  		return nil
   243  	}
   244  
   245  	// Include documentation belonging to blank imports.
   246  	var comments []*ast.CommentGroup
   247  	for _, s := range blankImports {
   248  		if c := s.(*ast.ImportSpec).Doc; c != nil {
   249  			comments = append(comments, c)
   250  		}
   251  	}
   252  
   253  	// Include comments that are inside the function body.
   254  	for _, c := range file.Comments {
   255  		if body.Pos() <= c.Pos() && c.End() <= body.End() {
   256  			comments = append(comments, c)
   257  		}
   258  	}
   259  
   260  	// Strip the "Output:" or "Unordered output:" comment and adjust body
   261  	// end position.
   262  	body, comments = stripOutputComment(body, comments)
   263  
   264  	// Synthesize import declaration.
   265  	importDecl := &ast.GenDecl{
   266  		Tok:    token.IMPORT,
   267  		Lparen: 1, // Need non-zero Lparen and Rparen so that printer
   268  		Rparen: 1, // treats this as a factored import.
   269  	}
   270  	for n, p := range namedImports {
   271  		s := &ast.ImportSpec{Path: &ast.BasicLit{Value: strconv.Quote(p)}}
   272  		if path.Base(p) != n {
   273  			s.Name = ast.NewIdent(n)
   274  		}
   275  		importDecl.Specs = append(importDecl.Specs, s)
   276  	}
   277  	importDecl.Specs = append(importDecl.Specs, blankImports...)
   278  
   279  	// Synthesize main function.
   280  	funcDecl := &ast.FuncDecl{
   281  		Name: ast.NewIdent("main"),
   282  		Type: &ast.FuncType{Params: &ast.FieldList{}}, // FuncType.Params must be non-nil
   283  		Body: body,
   284  	}
   285  
   286  	// Synthesize file.
   287  	return &ast.File{
   288  		Name:     ast.NewIdent("main"),
   289  		Decls:    []ast.Decl{importDecl, funcDecl},
   290  		Comments: comments,
   291  	}
   292  }
   293  
   294  // playExampleFile takes a whole file example and synthesizes a new *ast.File
   295  // such that the example is function main in package main.
   296  func playExampleFile(file *ast.File) *ast.File {
   297  	// Strip copyright comment if present.
   298  	comments := file.Comments
   299  	if len(comments) > 0 && strings.HasPrefix(comments[0].Text(), "Copyright") {
   300  		comments = comments[1:]
   301  	}
   302  
   303  	// Copy declaration slice, rewriting the ExampleX function to main.
   304  	var decls []ast.Decl
   305  	for _, d := range file.Decls {
   306  		if f, ok := d.(*ast.FuncDecl); ok && isTest(f.Name.Name, "Example") {
   307  			// Copy the FuncDecl, as it may be used elsewhere.
   308  			newF := *f
   309  			newF.Name = ast.NewIdent("main")
   310  			newF.Body, comments = stripOutputComment(f.Body, comments)
   311  			d = &newF
   312  		}
   313  		decls = append(decls, d)
   314  	}
   315  
   316  	// Copy the File, as it may be used elsewhere.
   317  	f := *file
   318  	f.Name = ast.NewIdent("main")
   319  	f.Decls = decls
   320  	f.Comments = comments
   321  	return &f
   322  }
   323  
   324  // stripOutputComment finds and removes the "Output:" or "Unordered output:"
   325  // comment from body and comments, and adjusts the body block's end position.
   326  func stripOutputComment(body *ast.BlockStmt, comments []*ast.CommentGroup) (*ast.BlockStmt, []*ast.CommentGroup) {
   327  	// Do nothing if there is no "Output:" or "Unordered output:" comment.
   328  	i, last := lastComment(body, comments)
   329  	if last == nil || !outputPrefix.MatchString(last.Text()) {
   330  		return body, comments
   331  	}
   332  
   333  	// Copy body and comments, as the originals may be used elsewhere.
   334  	newBody := &ast.BlockStmt{
   335  		Lbrace: body.Lbrace,
   336  		List:   body.List,
   337  		Rbrace: last.Pos(),
   338  	}
   339  	newComments := make([]*ast.CommentGroup, len(comments)-1)
   340  	copy(newComments, comments[:i])
   341  	copy(newComments[i:], comments[i+1:])
   342  	return newBody, newComments
   343  }
   344  
   345  // lastComment returns the last comment inside the provided block.
   346  func lastComment(b *ast.BlockStmt, c []*ast.CommentGroup) (i int, last *ast.CommentGroup) {
   347  	pos, end := b.Pos(), b.End()
   348  	for j, cg := range c {
   349  		if cg.Pos() < pos {
   350  			continue
   351  		}
   352  		if cg.End() > end {
   353  			break
   354  		}
   355  		i, last = j, cg
   356  	}
   357  	return
   358  }
   359  

View as plain text