github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/cmd/cover/cover.go (about)

     1  // Copyright 2013 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  package main
     6  
     7  import (
     8  	"bytes"
     9  	"flag"
    10  	"fmt"
    11  	"go/ast"
    12  	"go/parser"
    13  	"go/printer"
    14  	"go/token"
    15  	"io"
    16  	"io/ioutil"
    17  	"log"
    18  	"os"
    19  	"path/filepath"
    20  	"sort"
    21  	"strconv"
    22  	"strings"
    23  )
    24  
    25  const usageMessage = "" +
    26  	`Usage of 'go tool cover':
    27  Given a coverage profile produced by 'go test':
    28  	go test -coverprofile=c.out
    29  
    30  Open a web browser displaying annotated source code:
    31  	go tool cover -html=c.out
    32  
    33  Write out an HTML file instead of launching a web browser:
    34  	go tool cover -html=c.out -o coverage.html
    35  
    36  Display coverage percentages to stdout for each function:
    37  	go tool cover -func=c.out
    38  
    39  Finally, to generate modified source code with coverage annotations
    40  (what go test -cover does):
    41  	go tool cover -mode=set -var=CoverageVariableName program.go
    42  `
    43  
    44  func usage() {
    45  	fmt.Fprintln(os.Stderr, usageMessage)
    46  	fmt.Fprintln(os.Stderr, "Flags:")
    47  	flag.PrintDefaults()
    48  	fmt.Fprintln(os.Stderr, "\n  Only one of -html, -func, or -mode may be set.")
    49  	os.Exit(2)
    50  }
    51  
    52  var (
    53  	mode    = flag.String("mode", "", "coverage mode: set, count, atomic")
    54  	varVar  = flag.String("var", "GoCover", "name of coverage variable to generate")
    55  	output  = flag.String("o", "", "file for output; default: stdout")
    56  	htmlOut = flag.String("html", "", "generate HTML representation of coverage profile")
    57  	funcOut = flag.String("func", "", "output coverage profile information for each function")
    58  )
    59  
    60  var profile string // The profile to read; the value of -html or -func
    61  
    62  var counterStmt func(*File, ast.Expr) ast.Stmt
    63  
    64  const (
    65  	atomicPackagePath = "sync/atomic"
    66  	atomicPackageName = "_cover_atomic_"
    67  )
    68  
    69  func main() {
    70  	flag.Usage = usage
    71  	flag.Parse()
    72  
    73  	// Usage information when no arguments.
    74  	if flag.NFlag() == 0 && flag.NArg() == 0 {
    75  		flag.Usage()
    76  	}
    77  
    78  	err := parseFlags()
    79  	if err != nil {
    80  		fmt.Fprintln(os.Stderr, err)
    81  		fmt.Fprintln(os.Stderr, `For usage information, run "go tool cover -help"`)
    82  		os.Exit(2)
    83  	}
    84  
    85  	// Generate coverage-annotated source.
    86  	if *mode != "" {
    87  		annotate(flag.Arg(0))
    88  		return
    89  	}
    90  
    91  	// Output HTML or function coverage information.
    92  	if *htmlOut != "" {
    93  		err = htmlOutput(profile, *output)
    94  	} else {
    95  		err = funcOutput(profile, *output)
    96  	}
    97  
    98  	if err != nil {
    99  		fmt.Fprintf(os.Stderr, "cover: %v\n", err)
   100  		os.Exit(2)
   101  	}
   102  }
   103  
   104  // parseFlags sets the profile and counterStmt globals and performs validations.
   105  func parseFlags() error {
   106  	profile = *htmlOut
   107  	if *funcOut != "" {
   108  		if profile != "" {
   109  			return fmt.Errorf("too many options")
   110  		}
   111  		profile = *funcOut
   112  	}
   113  
   114  	// Must either display a profile or rewrite Go source.
   115  	if (profile == "") == (*mode == "") {
   116  		return fmt.Errorf("too many options")
   117  	}
   118  
   119  	if *mode != "" {
   120  		switch *mode {
   121  		case "set":
   122  			counterStmt = setCounterStmt
   123  		case "count":
   124  			counterStmt = incCounterStmt
   125  		case "atomic":
   126  			counterStmt = atomicCounterStmt
   127  		default:
   128  			return fmt.Errorf("unknown -mode %v", *mode)
   129  		}
   130  
   131  		if flag.NArg() == 0 {
   132  			return fmt.Errorf("missing source file")
   133  		} else if flag.NArg() == 1 {
   134  			return nil
   135  		}
   136  	} else if flag.NArg() == 0 {
   137  		return nil
   138  	}
   139  	return fmt.Errorf("too many arguments")
   140  }
   141  
   142  // Block represents the information about a basic block to be recorded in the analysis.
   143  // Note: Our definition of basic block is based on control structures; we don't break
   144  // apart && and ||. We could but it doesn't seem important enough to bother.
   145  type Block struct {
   146  	startByte token.Pos
   147  	endByte   token.Pos
   148  	numStmt   int
   149  }
   150  
   151  // File is a wrapper for the state of a file used in the parser.
   152  // The basic parse tree walker is a method of this type.
   153  type File struct {
   154  	fset      *token.FileSet
   155  	name      string // Name of file.
   156  	astFile   *ast.File
   157  	blocks    []Block
   158  	atomicPkg string // Package name for "sync/atomic" in this file.
   159  }
   160  
   161  // Visit implements the ast.Visitor interface.
   162  func (f *File) Visit(node ast.Node) ast.Visitor {
   163  	switch n := node.(type) {
   164  	case *ast.BlockStmt:
   165  		// If it's a switch or select, the body is a list of case clauses; don't tag the block itself.
   166  		if len(n.List) > 0 {
   167  			switch n.List[0].(type) {
   168  			case *ast.CaseClause: // switch
   169  				for _, n := range n.List {
   170  					clause := n.(*ast.CaseClause)
   171  					clause.Body = f.addCounters(clause.Colon+1, clause.End(), clause.Body, false)
   172  				}
   173  				return f
   174  			case *ast.CommClause: // select
   175  				for _, n := range n.List {
   176  					clause := n.(*ast.CommClause)
   177  					clause.Body = f.addCounters(clause.Colon+1, clause.End(), clause.Body, false)
   178  				}
   179  				return f
   180  			}
   181  		}
   182  		n.List = f.addCounters(n.Lbrace, n.Rbrace+1, n.List, true) // +1 to step past closing brace.
   183  	case *ast.IfStmt:
   184  		if n.Init != nil {
   185  			ast.Walk(f, n.Init)
   186  		}
   187  		ast.Walk(f, n.Cond)
   188  		ast.Walk(f, n.Body)
   189  		if n.Else == nil {
   190  			return nil
   191  		}
   192  		// The elses are special, because if we have
   193  		//	if x {
   194  		//	} else if y {
   195  		//	}
   196  		// we want to cover the "if y". To do this, we need a place to drop the counter,
   197  		// so we add a hidden block:
   198  		//	if x {
   199  		//	} else {
   200  		//		if y {
   201  		//		}
   202  		//	}
   203  		switch stmt := n.Else.(type) {
   204  		case *ast.IfStmt:
   205  			block := &ast.BlockStmt{
   206  				Lbrace: n.Body.End(), // Start at end of the "if" block so the covered part looks like it starts at the "else".
   207  				List:   []ast.Stmt{stmt},
   208  				Rbrace: stmt.End(),
   209  			}
   210  			n.Else = block
   211  		case *ast.BlockStmt:
   212  			stmt.Lbrace = n.Body.End() // Start at end of the "if" block so the covered part looks like it starts at the "else".
   213  		default:
   214  			panic("unexpected node type in if")
   215  		}
   216  		ast.Walk(f, n.Else)
   217  		return nil
   218  	case *ast.SelectStmt:
   219  		// Don't annotate an empty select - creates a syntax error.
   220  		if n.Body == nil || len(n.Body.List) == 0 {
   221  			return nil
   222  		}
   223  	case *ast.SwitchStmt:
   224  		// Don't annotate an empty switch - creates a syntax error.
   225  		if n.Body == nil || len(n.Body.List) == 0 {
   226  			if n.Init != nil {
   227  				ast.Walk(f, n.Init)
   228  			}
   229  			if n.Tag != nil {
   230  				ast.Walk(f, n.Tag)
   231  			}
   232  			return nil
   233  		}
   234  	case *ast.TypeSwitchStmt:
   235  		// Don't annotate an empty type switch - creates a syntax error.
   236  		if n.Body == nil || len(n.Body.List) == 0 {
   237  			if n.Init != nil {
   238  				ast.Walk(f, n.Init)
   239  			}
   240  			ast.Walk(f, n.Assign)
   241  			return nil
   242  		}
   243  	case *ast.CommentGroup:
   244  		var list []*ast.Comment
   245  		// Drop all but the //go: comments, some of which are semantically important.
   246  		// We drop all others because they can appear in places that cause our counters
   247  		// to appear in syntactically incorrect places. //go: appears at the beginning of
   248  		// the line and is syntactically safe.
   249  		for _, c := range n.List {
   250  			if strings.HasPrefix(c.Text, "//go:") && f.fset.Position(c.Slash).Column == 1 {
   251  				list = append(list, c)
   252  			}
   253  		}
   254  		n.List = list
   255  	}
   256  	return f
   257  }
   258  
   259  // unquote returns the unquoted string.
   260  func unquote(s string) string {
   261  	t, err := strconv.Unquote(s)
   262  	if err != nil {
   263  		log.Fatalf("cover: improperly quoted string %q\n", s)
   264  	}
   265  	return t
   266  }
   267  
   268  // addImport adds an import for the specified path, if one does not already exist, and returns
   269  // the local package name.
   270  func (f *File) addImport(path string) string {
   271  	// Does the package already import it?
   272  	for _, s := range f.astFile.Imports {
   273  		if unquote(s.Path.Value) == path {
   274  			if s.Name != nil {
   275  				return s.Name.Name
   276  			}
   277  			return filepath.Base(path)
   278  		}
   279  	}
   280  	newImport := &ast.ImportSpec{
   281  		Name: ast.NewIdent(atomicPackageName),
   282  		Path: &ast.BasicLit{
   283  			Kind:  token.STRING,
   284  			Value: fmt.Sprintf("%q", path),
   285  		},
   286  	}
   287  	impDecl := &ast.GenDecl{
   288  		Tok: token.IMPORT,
   289  		Specs: []ast.Spec{
   290  			newImport,
   291  		},
   292  	}
   293  	// Make the new import the first Decl in the file.
   294  	astFile := f.astFile
   295  	astFile.Decls = append(astFile.Decls, nil)
   296  	copy(astFile.Decls[1:], astFile.Decls[0:])
   297  	astFile.Decls[0] = impDecl
   298  	astFile.Imports = append(astFile.Imports, newImport)
   299  
   300  	// Now refer to the package, just in case it ends up unused.
   301  	// That is, append to the end of the file the declaration
   302  	//	var _ = _cover_atomic_.AddUint32
   303  	reference := &ast.GenDecl{
   304  		Tok: token.VAR,
   305  		Specs: []ast.Spec{
   306  			&ast.ValueSpec{
   307  				Names: []*ast.Ident{
   308  					ast.NewIdent("_"),
   309  				},
   310  				Values: []ast.Expr{
   311  					&ast.SelectorExpr{
   312  						X:   ast.NewIdent(atomicPackageName),
   313  						Sel: ast.NewIdent("AddUint32"),
   314  					},
   315  				},
   316  			},
   317  		},
   318  	}
   319  	astFile.Decls = append(astFile.Decls, reference)
   320  	return atomicPackageName
   321  }
   322  
   323  var slashslash = []byte("//")
   324  
   325  // initialComments returns the prefix of content containing only
   326  // whitespace and line comments. Any +build directives must appear
   327  // within this region. This approach is more reliable than using
   328  // go/printer to print a modified AST containing comments.
   329  //
   330  func initialComments(content []byte) []byte {
   331  	// Derived from go/build.Context.shouldBuild.
   332  	end := 0
   333  	p := content
   334  	for len(p) > 0 {
   335  		line := p
   336  		if i := bytes.IndexByte(line, '\n'); i >= 0 {
   337  			line, p = line[:i], p[i+1:]
   338  		} else {
   339  			p = p[len(p):]
   340  		}
   341  		line = bytes.TrimSpace(line)
   342  		if len(line) == 0 { // Blank line.
   343  			end = len(content) - len(p)
   344  			continue
   345  		}
   346  		if !bytes.HasPrefix(line, slashslash) { // Not comment line.
   347  			break
   348  		}
   349  	}
   350  	return content[:end]
   351  }
   352  
   353  func annotate(name string) {
   354  	fset := token.NewFileSet()
   355  	content, err := ioutil.ReadFile(name)
   356  	if err != nil {
   357  		log.Fatalf("cover: %s: %s", name, err)
   358  	}
   359  	parsedFile, err := parser.ParseFile(fset, name, content, parser.ParseComments)
   360  	if err != nil {
   361  		log.Fatalf("cover: %s: %s", name, err)
   362  	}
   363  	// Remove comments. Or else they interfere with new AST.
   364  	parsedFile.Comments = nil
   365  
   366  	file := &File{
   367  		fset:    fset,
   368  		name:    name,
   369  		astFile: parsedFile,
   370  	}
   371  	if *mode == "atomic" {
   372  		file.atomicPkg = file.addImport(atomicPackagePath)
   373  	}
   374  	ast.Walk(file, file.astFile)
   375  	fd := os.Stdout
   376  	if *output != "" {
   377  		var err error
   378  		fd, err = os.Create(*output)
   379  		if err != nil {
   380  			log.Fatalf("cover: %s", err)
   381  		}
   382  	}
   383  	fd.Write(initialComments(content)) // Retain '// +build' directives.
   384  	file.print(fd)
   385  	// After printing the source tree, add some declarations for the counters etc.
   386  	// We could do this by adding to the tree, but it's easier just to print the text.
   387  	file.addVariables(fd)
   388  }
   389  
   390  func (f *File) print(w io.Writer) {
   391  	printer.Fprint(w, f.fset, f.astFile)
   392  }
   393  
   394  // intLiteral returns an ast.BasicLit representing the integer value.
   395  func (f *File) intLiteral(i int) *ast.BasicLit {
   396  	node := &ast.BasicLit{
   397  		Kind:  token.INT,
   398  		Value: fmt.Sprint(i),
   399  	}
   400  	return node
   401  }
   402  
   403  // index returns an ast.BasicLit representing the number of counters present.
   404  func (f *File) index() *ast.BasicLit {
   405  	return f.intLiteral(len(f.blocks))
   406  }
   407  
   408  // setCounterStmt returns the expression: __count[23] = 1.
   409  func setCounterStmt(f *File, counter ast.Expr) ast.Stmt {
   410  	return &ast.AssignStmt{
   411  		Lhs: []ast.Expr{counter},
   412  		Tok: token.ASSIGN,
   413  		Rhs: []ast.Expr{f.intLiteral(1)},
   414  	}
   415  }
   416  
   417  // incCounterStmt returns the expression: __count[23]++.
   418  func incCounterStmt(f *File, counter ast.Expr) ast.Stmt {
   419  	return &ast.IncDecStmt{
   420  		X:   counter,
   421  		Tok: token.INC,
   422  	}
   423  }
   424  
   425  // atomicCounterStmt returns the expression: atomic.AddUint32(&__count[23], 1)
   426  func atomicCounterStmt(f *File, counter ast.Expr) ast.Stmt {
   427  	return &ast.ExprStmt{
   428  		X: &ast.CallExpr{
   429  			Fun: &ast.SelectorExpr{
   430  				X:   ast.NewIdent(f.atomicPkg),
   431  				Sel: ast.NewIdent("AddUint32"),
   432  			},
   433  			Args: []ast.Expr{&ast.UnaryExpr{
   434  				Op: token.AND,
   435  				X:  counter,
   436  			},
   437  				f.intLiteral(1),
   438  			},
   439  		},
   440  	}
   441  }
   442  
   443  // newCounter creates a new counter expression of the appropriate form.
   444  func (f *File) newCounter(start, end token.Pos, numStmt int) ast.Stmt {
   445  	counter := &ast.IndexExpr{
   446  		X: &ast.SelectorExpr{
   447  			X:   ast.NewIdent(*varVar),
   448  			Sel: ast.NewIdent("Count"),
   449  		},
   450  		Index: f.index(),
   451  	}
   452  	stmt := counterStmt(f, counter)
   453  	f.blocks = append(f.blocks, Block{start, end, numStmt})
   454  	return stmt
   455  }
   456  
   457  // addCounters takes a list of statements and adds counters to the beginning of
   458  // each basic block at the top level of that list. For instance, given
   459  //
   460  //	S1
   461  //	if cond {
   462  //		S2
   463  // 	}
   464  //	S3
   465  //
   466  // counters will be added before S1 and before S3. The block containing S2
   467  // will be visited in a separate call.
   468  // TODO: Nested simple blocks get unnecessary (but correct) counters
   469  func (f *File) addCounters(pos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) []ast.Stmt {
   470  	// Special case: make sure we add a counter to an empty block. Can't do this below
   471  	// or we will add a counter to an empty statement list after, say, a return statement.
   472  	if len(list) == 0 {
   473  		return []ast.Stmt{f.newCounter(pos, blockEnd, 0)}
   474  	}
   475  	// We have a block (statement list), but it may have several basic blocks due to the
   476  	// appearance of statements that affect the flow of control.
   477  	var newList []ast.Stmt
   478  	for {
   479  		// Find first statement that affects flow of control (break, continue, if, etc.).
   480  		// It will be the last statement of this basic block.
   481  		var last int
   482  		end := blockEnd
   483  		for last = 0; last < len(list); last++ {
   484  			stmt := list[last]
   485  			end = f.statementBoundary(stmt)
   486  			if f.endsBasicSourceBlock(stmt) {
   487  				// If it is a labeled statement, we need to place a counter between
   488  				// the label and its statement because it may be the target of a goto
   489  				// and thus start a basic block. That is, given
   490  				//	foo: stmt
   491  				// we need to create
   492  				//	foo: ; stmt
   493  				// and mark the label as a block-terminating statement.
   494  				// The result will then be
   495  				//	foo: COUNTER[n]++; stmt
   496  				// However, we can't do this if the labeled statement is already
   497  				// a control statement, such as a labeled for.
   498  				if label, isLabel := stmt.(*ast.LabeledStmt); isLabel && !f.isControl(label.Stmt) {
   499  					newLabel := *label
   500  					newLabel.Stmt = &ast.EmptyStmt{
   501  						Semicolon: label.Stmt.Pos(),
   502  						Implicit:  true,
   503  					}
   504  					end = label.Pos() // Previous block ends before the label.
   505  					list[last] = &newLabel
   506  					// Open a gap and drop in the old statement, now without a label.
   507  					list = append(list, nil)
   508  					copy(list[last+1:], list[last:])
   509  					list[last+1] = label.Stmt
   510  				}
   511  				last++
   512  				extendToClosingBrace = false // Block is broken up now.
   513  				break
   514  			}
   515  		}
   516  		if extendToClosingBrace {
   517  			end = blockEnd
   518  		}
   519  		if pos != end { // Can have no source to cover if e.g. blocks abut.
   520  			newList = append(newList, f.newCounter(pos, end, last))
   521  		}
   522  		newList = append(newList, list[0:last]...)
   523  		list = list[last:]
   524  		if len(list) == 0 {
   525  			break
   526  		}
   527  		pos = list[0].Pos()
   528  	}
   529  	return newList
   530  }
   531  
   532  // hasFuncLiteral reports the existence and position of the first func literal
   533  // in the node, if any. If a func literal appears, it usually marks the termination
   534  // of a basic block because the function body is itself a block.
   535  // Therefore we draw a line at the start of the body of the first function literal we find.
   536  // TODO: what if there's more than one? Probably doesn't matter much.
   537  func hasFuncLiteral(n ast.Node) (bool, token.Pos) {
   538  	if n == nil {
   539  		return false, 0
   540  	}
   541  	var literal funcLitFinder
   542  	ast.Walk(&literal, n)
   543  	return literal.found(), token.Pos(literal)
   544  }
   545  
   546  // statementBoundary finds the location in s that terminates the current basic
   547  // block in the source.
   548  func (f *File) statementBoundary(s ast.Stmt) token.Pos {
   549  	// Control flow statements are easy.
   550  	switch s := s.(type) {
   551  	case *ast.BlockStmt:
   552  		// Treat blocks like basic blocks to avoid overlapping counters.
   553  		return s.Lbrace
   554  	case *ast.IfStmt:
   555  		found, pos := hasFuncLiteral(s.Init)
   556  		if found {
   557  			return pos
   558  		}
   559  		found, pos = hasFuncLiteral(s.Cond)
   560  		if found {
   561  			return pos
   562  		}
   563  		return s.Body.Lbrace
   564  	case *ast.ForStmt:
   565  		found, pos := hasFuncLiteral(s.Init)
   566  		if found {
   567  			return pos
   568  		}
   569  		found, pos = hasFuncLiteral(s.Cond)
   570  		if found {
   571  			return pos
   572  		}
   573  		found, pos = hasFuncLiteral(s.Post)
   574  		if found {
   575  			return pos
   576  		}
   577  		return s.Body.Lbrace
   578  	case *ast.LabeledStmt:
   579  		return f.statementBoundary(s.Stmt)
   580  	case *ast.RangeStmt:
   581  		found, pos := hasFuncLiteral(s.X)
   582  		if found {
   583  			return pos
   584  		}
   585  		return s.Body.Lbrace
   586  	case *ast.SwitchStmt:
   587  		found, pos := hasFuncLiteral(s.Init)
   588  		if found {
   589  			return pos
   590  		}
   591  		found, pos = hasFuncLiteral(s.Tag)
   592  		if found {
   593  			return pos
   594  		}
   595  		return s.Body.Lbrace
   596  	case *ast.SelectStmt:
   597  		return s.Body.Lbrace
   598  	case *ast.TypeSwitchStmt:
   599  		found, pos := hasFuncLiteral(s.Init)
   600  		if found {
   601  			return pos
   602  		}
   603  		return s.Body.Lbrace
   604  	}
   605  	// If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal.
   606  	// If it does, that's tricky because we want to exclude the body of the function from this block.
   607  	// Draw a line at the start of the body of the first function literal we find.
   608  	// TODO: what if there's more than one? Probably doesn't matter much.
   609  	found, pos := hasFuncLiteral(s)
   610  	if found {
   611  		return pos
   612  	}
   613  	return s.End()
   614  }
   615  
   616  // endsBasicSourceBlock reports whether s changes the flow of control: break, if, etc.,
   617  // or if it's just problematic, for instance contains a function literal, which will complicate
   618  // accounting due to the block-within-an expression.
   619  func (f *File) endsBasicSourceBlock(s ast.Stmt) bool {
   620  	switch s := s.(type) {
   621  	case *ast.BlockStmt:
   622  		// Treat blocks like basic blocks to avoid overlapping counters.
   623  		return true
   624  	case *ast.BranchStmt:
   625  		return true
   626  	case *ast.ForStmt:
   627  		return true
   628  	case *ast.IfStmt:
   629  		return true
   630  	case *ast.LabeledStmt:
   631  		return true // A goto may branch here, starting a new basic block.
   632  	case *ast.RangeStmt:
   633  		return true
   634  	case *ast.SwitchStmt:
   635  		return true
   636  	case *ast.SelectStmt:
   637  		return true
   638  	case *ast.TypeSwitchStmt:
   639  		return true
   640  	case *ast.ExprStmt:
   641  		// Calls to panic change the flow.
   642  		// We really should verify that "panic" is the predefined function,
   643  		// but without type checking we can't and the likelihood of it being
   644  		// an actual problem is vanishingly small.
   645  		if call, ok := s.X.(*ast.CallExpr); ok {
   646  			if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 {
   647  				return true
   648  			}
   649  		}
   650  	}
   651  	found, _ := hasFuncLiteral(s)
   652  	return found
   653  }
   654  
   655  // isControl reports whether s is a control statement that, if labeled, cannot be
   656  // separated from its label.
   657  func (f *File) isControl(s ast.Stmt) bool {
   658  	switch s.(type) {
   659  	case *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt, *ast.TypeSwitchStmt:
   660  		return true
   661  	}
   662  	return false
   663  }
   664  
   665  // funcLitFinder implements the ast.Visitor pattern to find the location of any
   666  // function literal in a subtree.
   667  type funcLitFinder token.Pos
   668  
   669  func (f *funcLitFinder) Visit(node ast.Node) (w ast.Visitor) {
   670  	if f.found() {
   671  		return nil // Prune search.
   672  	}
   673  	switch n := node.(type) {
   674  	case *ast.FuncLit:
   675  		*f = funcLitFinder(n.Body.Lbrace)
   676  		return nil // Prune search.
   677  	}
   678  	return f
   679  }
   680  
   681  func (f *funcLitFinder) found() bool {
   682  	return token.Pos(*f) != token.NoPos
   683  }
   684  
   685  // Sort interface for []block1; used for self-check in addVariables.
   686  
   687  type block1 struct {
   688  	Block
   689  	index int
   690  }
   691  
   692  type blockSlice []block1
   693  
   694  func (b blockSlice) Len() int           { return len(b) }
   695  func (b blockSlice) Less(i, j int) bool { return b[i].startByte < b[j].startByte }
   696  func (b blockSlice) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }
   697  
   698  // offset translates a token position into a 0-indexed byte offset.
   699  func (f *File) offset(pos token.Pos) int {
   700  	return f.fset.Position(pos).Offset
   701  }
   702  
   703  // addVariables adds to the end of the file the declarations to set up the counter and position variables.
   704  func (f *File) addVariables(w io.Writer) {
   705  	// Self-check: Verify that the instrumented basic blocks are disjoint.
   706  	t := make([]block1, len(f.blocks))
   707  	for i := range f.blocks {
   708  		t[i].Block = f.blocks[i]
   709  		t[i].index = i
   710  	}
   711  	sort.Sort(blockSlice(t))
   712  	for i := 1; i < len(t); i++ {
   713  		if t[i-1].endByte > t[i].startByte {
   714  			fmt.Fprintf(os.Stderr, "cover: internal error: block %d overlaps block %d\n", t[i-1].index, t[i].index)
   715  			// Note: error message is in byte positions, not token positions.
   716  			fmt.Fprintf(os.Stderr, "\t%s:#%d,#%d %s:#%d,#%d\n",
   717  				f.name, f.offset(t[i-1].startByte), f.offset(t[i-1].endByte),
   718  				f.name, f.offset(t[i].startByte), f.offset(t[i].endByte))
   719  		}
   720  	}
   721  
   722  	// Declare the coverage struct as a package-level variable.
   723  	fmt.Fprintf(w, "\nvar %s = struct {\n", *varVar)
   724  	fmt.Fprintf(w, "\tCount     [%d]uint32\n", len(f.blocks))
   725  	fmt.Fprintf(w, "\tPos       [3 * %d]uint32\n", len(f.blocks))
   726  	fmt.Fprintf(w, "\tNumStmt   [%d]uint16\n", len(f.blocks))
   727  	fmt.Fprintf(w, "} {\n")
   728  
   729  	// Initialize the position array field.
   730  	fmt.Fprintf(w, "\tPos: [3 * %d]uint32{\n", len(f.blocks))
   731  
   732  	// A nice long list of positions. Each position is encoded as follows to reduce size:
   733  	// - 32-bit starting line number
   734  	// - 32-bit ending line number
   735  	// - (16 bit ending column number << 16) | (16-bit starting column number).
   736  	for i, block := range f.blocks {
   737  		start := f.fset.Position(block.startByte)
   738  		end := f.fset.Position(block.endByte)
   739  		fmt.Fprintf(w, "\t\t%d, %d, %#x, // [%d]\n", start.Line, end.Line, (end.Column&0xFFFF)<<16|(start.Column&0xFFFF), i)
   740  	}
   741  
   742  	// Close the position array.
   743  	fmt.Fprintf(w, "\t},\n")
   744  
   745  	// Initialize the position array field.
   746  	fmt.Fprintf(w, "\tNumStmt: [%d]uint16{\n", len(f.blocks))
   747  
   748  	// A nice long list of statements-per-block, so we can give a conventional
   749  	// valuation of "percent covered". To save space, it's a 16-bit number, so we
   750  	// clamp it if it overflows - won't matter in practice.
   751  	for i, block := range f.blocks {
   752  		n := block.numStmt
   753  		if n > 1<<16-1 {
   754  			n = 1<<16 - 1
   755  		}
   756  		fmt.Fprintf(w, "\t\t%d, // %d\n", n, i)
   757  	}
   758  
   759  	// Close the statements-per-block array.
   760  	fmt.Fprintf(w, "\t},\n")
   761  
   762  	// Close the struct initialization.
   763  	fmt.Fprintf(w, "}\n")
   764  }