github.com/euank/go@v0.0.0-20160829210321-495514729181/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.Pos(), 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.Pos(), 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  	}
   244  	return f
   245  }
   246  
   247  // unquote returns the unquoted string.
   248  func unquote(s string) string {
   249  	t, err := strconv.Unquote(s)
   250  	if err != nil {
   251  		log.Fatalf("cover: improperly quoted string %q\n", s)
   252  	}
   253  	return t
   254  }
   255  
   256  // addImport adds an import for the specified path, if one does not already exist, and returns
   257  // the local package name.
   258  func (f *File) addImport(path string) string {
   259  	// Does the package already import it?
   260  	for _, s := range f.astFile.Imports {
   261  		if unquote(s.Path.Value) == path {
   262  			if s.Name != nil {
   263  				return s.Name.Name
   264  			}
   265  			return filepath.Base(path)
   266  		}
   267  	}
   268  	newImport := &ast.ImportSpec{
   269  		Name: ast.NewIdent(atomicPackageName),
   270  		Path: &ast.BasicLit{
   271  			Kind:  token.STRING,
   272  			Value: fmt.Sprintf("%q", path),
   273  		},
   274  	}
   275  	impDecl := &ast.GenDecl{
   276  		Tok: token.IMPORT,
   277  		Specs: []ast.Spec{
   278  			newImport,
   279  		},
   280  	}
   281  	// Make the new import the first Decl in the file.
   282  	astFile := f.astFile
   283  	astFile.Decls = append(astFile.Decls, nil)
   284  	copy(astFile.Decls[1:], astFile.Decls[0:])
   285  	astFile.Decls[0] = impDecl
   286  	astFile.Imports = append(astFile.Imports, newImport)
   287  
   288  	// Now refer to the package, just in case it ends up unused.
   289  	// That is, append to the end of the file the declaration
   290  	//	var _ = _cover_atomic_.AddUint32
   291  	reference := &ast.GenDecl{
   292  		Tok: token.VAR,
   293  		Specs: []ast.Spec{
   294  			&ast.ValueSpec{
   295  				Names: []*ast.Ident{
   296  					ast.NewIdent("_"),
   297  				},
   298  				Values: []ast.Expr{
   299  					&ast.SelectorExpr{
   300  						X:   ast.NewIdent(atomicPackageName),
   301  						Sel: ast.NewIdent("AddUint32"),
   302  					},
   303  				},
   304  			},
   305  		},
   306  	}
   307  	astFile.Decls = append(astFile.Decls, reference)
   308  	return atomicPackageName
   309  }
   310  
   311  var slashslash = []byte("//")
   312  
   313  // initialComments returns the prefix of content containing only
   314  // whitespace and line comments. Any +build directives must appear
   315  // within this region. This approach is more reliable than using
   316  // go/printer to print a modified AST containing comments.
   317  //
   318  func initialComments(content []byte) []byte {
   319  	// Derived from go/build.Context.shouldBuild.
   320  	end := 0
   321  	p := content
   322  	for len(p) > 0 {
   323  		line := p
   324  		if i := bytes.IndexByte(line, '\n'); i >= 0 {
   325  			line, p = line[:i], p[i+1:]
   326  		} else {
   327  			p = p[len(p):]
   328  		}
   329  		line = bytes.TrimSpace(line)
   330  		if len(line) == 0 { // Blank line.
   331  			end = len(content) - len(p)
   332  			continue
   333  		}
   334  		if !bytes.HasPrefix(line, slashslash) { // Not comment line.
   335  			break
   336  		}
   337  	}
   338  	return content[:end]
   339  }
   340  
   341  func annotate(name string) {
   342  	fset := token.NewFileSet()
   343  	content, err := ioutil.ReadFile(name)
   344  	if err != nil {
   345  		log.Fatalf("cover: %s: %s", name, err)
   346  	}
   347  	parsedFile, err := parser.ParseFile(fset, name, content, parser.ParseComments)
   348  	if err != nil {
   349  		log.Fatalf("cover: %s: %s", name, err)
   350  	}
   351  	parsedFile.Comments = trimComments(parsedFile, fset)
   352  
   353  	file := &File{
   354  		fset:    fset,
   355  		name:    name,
   356  		astFile: parsedFile,
   357  	}
   358  	if *mode == "atomic" {
   359  		file.atomicPkg = file.addImport(atomicPackagePath)
   360  	}
   361  	ast.Walk(file, file.astFile)
   362  	fd := os.Stdout
   363  	if *output != "" {
   364  		var err error
   365  		fd, err = os.Create(*output)
   366  		if err != nil {
   367  			log.Fatalf("cover: %s", err)
   368  		}
   369  	}
   370  	fd.Write(initialComments(content)) // Retain '// +build' directives.
   371  	file.print(fd)
   372  	// After printing the source tree, add some declarations for the counters etc.
   373  	// We could do this by adding to the tree, but it's easier just to print the text.
   374  	file.addVariables(fd)
   375  }
   376  
   377  // trimComments drops all but the //go: comments, some of which are semantically important.
   378  // We drop all others because they can appear in places that cause our counters
   379  // to appear in syntactically incorrect places. //go: appears at the beginning of
   380  // the line and is syntactically safe.
   381  func trimComments(file *ast.File, fset *token.FileSet) []*ast.CommentGroup {
   382  	var comments []*ast.CommentGroup
   383  	for _, group := range file.Comments {
   384  		var list []*ast.Comment
   385  		for _, comment := range group.List {
   386  			if strings.HasPrefix(comment.Text, "//go:") && fset.Position(comment.Slash).Column == 1 {
   387  				list = append(list, comment)
   388  			}
   389  		}
   390  		if list != nil {
   391  			comments = append(comments, &ast.CommentGroup{List: list})
   392  		}
   393  	}
   394  	return comments
   395  }
   396  
   397  func (f *File) print(w io.Writer) {
   398  	printer.Fprint(w, f.fset, f.astFile)
   399  }
   400  
   401  // intLiteral returns an ast.BasicLit representing the integer value.
   402  func (f *File) intLiteral(i int) *ast.BasicLit {
   403  	node := &ast.BasicLit{
   404  		Kind:  token.INT,
   405  		Value: fmt.Sprint(i),
   406  	}
   407  	return node
   408  }
   409  
   410  // index returns an ast.BasicLit representing the number of counters present.
   411  func (f *File) index() *ast.BasicLit {
   412  	return f.intLiteral(len(f.blocks))
   413  }
   414  
   415  // setCounterStmt returns the expression: __count[23] = 1.
   416  func setCounterStmt(f *File, counter ast.Expr) ast.Stmt {
   417  	return &ast.AssignStmt{
   418  		Lhs: []ast.Expr{counter},
   419  		Tok: token.ASSIGN,
   420  		Rhs: []ast.Expr{f.intLiteral(1)},
   421  	}
   422  }
   423  
   424  // incCounterStmt returns the expression: __count[23]++.
   425  func incCounterStmt(f *File, counter ast.Expr) ast.Stmt {
   426  	return &ast.IncDecStmt{
   427  		X:   counter,
   428  		Tok: token.INC,
   429  	}
   430  }
   431  
   432  // atomicCounterStmt returns the expression: atomic.AddUint32(&__count[23], 1)
   433  func atomicCounterStmt(f *File, counter ast.Expr) ast.Stmt {
   434  	return &ast.ExprStmt{
   435  		X: &ast.CallExpr{
   436  			Fun: &ast.SelectorExpr{
   437  				X:   ast.NewIdent(f.atomicPkg),
   438  				Sel: ast.NewIdent("AddUint32"),
   439  			},
   440  			Args: []ast.Expr{&ast.UnaryExpr{
   441  				Op: token.AND,
   442  				X:  counter,
   443  			},
   444  				f.intLiteral(1),
   445  			},
   446  		},
   447  	}
   448  }
   449  
   450  // newCounter creates a new counter expression of the appropriate form.
   451  func (f *File) newCounter(start, end token.Pos, numStmt int) ast.Stmt {
   452  	counter := &ast.IndexExpr{
   453  		X: &ast.SelectorExpr{
   454  			X:   ast.NewIdent(*varVar),
   455  			Sel: ast.NewIdent("Count"),
   456  		},
   457  		Index: f.index(),
   458  	}
   459  	stmt := counterStmt(f, counter)
   460  	f.blocks = append(f.blocks, Block{start, end, numStmt})
   461  	return stmt
   462  }
   463  
   464  // addCounters takes a list of statements and adds counters to the beginning of
   465  // each basic block at the top level of that list. For instance, given
   466  //
   467  //	S1
   468  //	if cond {
   469  //		S2
   470  // 	}
   471  //	S3
   472  //
   473  // counters will be added before S1 and before S3. The block containing S2
   474  // will be visited in a separate call.
   475  // TODO: Nested simple blocks get unnecessary (but correct) counters
   476  func (f *File) addCounters(pos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) []ast.Stmt {
   477  	// Special case: make sure we add a counter to an empty block. Can't do this below
   478  	// or we will add a counter to an empty statement list after, say, a return statement.
   479  	if len(list) == 0 {
   480  		return []ast.Stmt{f.newCounter(pos, blockEnd, 0)}
   481  	}
   482  	// We have a block (statement list), but it may have several basic blocks due to the
   483  	// appearance of statements that affect the flow of control.
   484  	var newList []ast.Stmt
   485  	for {
   486  		// Find first statement that affects flow of control (break, continue, if, etc.).
   487  		// It will be the last statement of this basic block.
   488  		var last int
   489  		end := blockEnd
   490  		for last = 0; last < len(list); last++ {
   491  			end = f.statementBoundary(list[last])
   492  			if f.endsBasicSourceBlock(list[last]) {
   493  				extendToClosingBrace = false // Block is broken up now.
   494  				last++
   495  				break
   496  			}
   497  		}
   498  		if extendToClosingBrace {
   499  			end = blockEnd
   500  		}
   501  		if pos != end { // Can have no source to cover if e.g. blocks abut.
   502  			newList = append(newList, f.newCounter(pos, end, last))
   503  		}
   504  		newList = append(newList, list[0:last]...)
   505  		list = list[last:]
   506  		if len(list) == 0 {
   507  			break
   508  		}
   509  		pos = list[0].Pos()
   510  	}
   511  	return newList
   512  }
   513  
   514  // hasFuncLiteral reports the existence and position of the first func literal
   515  // in the node, if any. If a func literal appears, it usually marks the termination
   516  // of a basic block because the function body is itself a block.
   517  // Therefore we draw a line at the start of the body of the first function literal we find.
   518  // TODO: what if there's more than one? Probably doesn't matter much.
   519  func hasFuncLiteral(n ast.Node) (bool, token.Pos) {
   520  	if n == nil {
   521  		return false, 0
   522  	}
   523  	var literal funcLitFinder
   524  	ast.Walk(&literal, n)
   525  	return literal.found(), token.Pos(literal)
   526  }
   527  
   528  // statementBoundary finds the location in s that terminates the current basic
   529  // block in the source.
   530  func (f *File) statementBoundary(s ast.Stmt) token.Pos {
   531  	// Control flow statements are easy.
   532  	switch s := s.(type) {
   533  	case *ast.BlockStmt:
   534  		// Treat blocks like basic blocks to avoid overlapping counters.
   535  		return s.Lbrace
   536  	case *ast.IfStmt:
   537  		found, pos := hasFuncLiteral(s.Init)
   538  		if found {
   539  			return pos
   540  		}
   541  		found, pos = hasFuncLiteral(s.Cond)
   542  		if found {
   543  			return pos
   544  		}
   545  		return s.Body.Lbrace
   546  	case *ast.ForStmt:
   547  		found, pos := hasFuncLiteral(s.Init)
   548  		if found {
   549  			return pos
   550  		}
   551  		found, pos = hasFuncLiteral(s.Cond)
   552  		if found {
   553  			return pos
   554  		}
   555  		found, pos = hasFuncLiteral(s.Post)
   556  		if found {
   557  			return pos
   558  		}
   559  		return s.Body.Lbrace
   560  	case *ast.LabeledStmt:
   561  		return f.statementBoundary(s.Stmt)
   562  	case *ast.RangeStmt:
   563  		found, pos := hasFuncLiteral(s.X)
   564  		if found {
   565  			return pos
   566  		}
   567  		return s.Body.Lbrace
   568  	case *ast.SwitchStmt:
   569  		found, pos := hasFuncLiteral(s.Init)
   570  		if found {
   571  			return pos
   572  		}
   573  		found, pos = hasFuncLiteral(s.Tag)
   574  		if found {
   575  			return pos
   576  		}
   577  		return s.Body.Lbrace
   578  	case *ast.SelectStmt:
   579  		return s.Body.Lbrace
   580  	case *ast.TypeSwitchStmt:
   581  		found, pos := hasFuncLiteral(s.Init)
   582  		if found {
   583  			return pos
   584  		}
   585  		return s.Body.Lbrace
   586  	}
   587  	// If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal.
   588  	// If it does, that's tricky because we want to exclude the body of the function from this block.
   589  	// Draw a line at the start of the body of the first function literal we find.
   590  	// TODO: what if there's more than one? Probably doesn't matter much.
   591  	found, pos := hasFuncLiteral(s)
   592  	if found {
   593  		return pos
   594  	}
   595  	return s.End()
   596  }
   597  
   598  // endsBasicSourceBlock reports whether s changes the flow of control: break, if, etc.,
   599  // or if it's just problematic, for instance contains a function literal, which will complicate
   600  // accounting due to the block-within-an expression.
   601  func (f *File) endsBasicSourceBlock(s ast.Stmt) bool {
   602  	switch s := s.(type) {
   603  	case *ast.BlockStmt:
   604  		// Treat blocks like basic blocks to avoid overlapping counters.
   605  		return true
   606  	case *ast.BranchStmt:
   607  		return true
   608  	case *ast.ForStmt:
   609  		return true
   610  	case *ast.IfStmt:
   611  		return true
   612  	case *ast.LabeledStmt:
   613  		return f.endsBasicSourceBlock(s.Stmt)
   614  	case *ast.RangeStmt:
   615  		return true
   616  	case *ast.SwitchStmt:
   617  		return true
   618  	case *ast.SelectStmt:
   619  		return true
   620  	case *ast.TypeSwitchStmt:
   621  		return true
   622  	case *ast.ExprStmt:
   623  		// Calls to panic change the flow.
   624  		// We really should verify that "panic" is the predefined function,
   625  		// but without type checking we can't and the likelihood of it being
   626  		// an actual problem is vanishingly small.
   627  		if call, ok := s.X.(*ast.CallExpr); ok {
   628  			if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 {
   629  				return true
   630  			}
   631  		}
   632  	}
   633  	found, _ := hasFuncLiteral(s)
   634  	return found
   635  }
   636  
   637  // funcLitFinder implements the ast.Visitor pattern to find the location of any
   638  // function literal in a subtree.
   639  type funcLitFinder token.Pos
   640  
   641  func (f *funcLitFinder) Visit(node ast.Node) (w ast.Visitor) {
   642  	if f.found() {
   643  		return nil // Prune search.
   644  	}
   645  	switch n := node.(type) {
   646  	case *ast.FuncLit:
   647  		*f = funcLitFinder(n.Body.Lbrace)
   648  		return nil // Prune search.
   649  	}
   650  	return f
   651  }
   652  
   653  func (f *funcLitFinder) found() bool {
   654  	return token.Pos(*f) != token.NoPos
   655  }
   656  
   657  // Sort interface for []block1; used for self-check in addVariables.
   658  
   659  type block1 struct {
   660  	Block
   661  	index int
   662  }
   663  
   664  type blockSlice []block1
   665  
   666  func (b blockSlice) Len() int           { return len(b) }
   667  func (b blockSlice) Less(i, j int) bool { return b[i].startByte < b[j].startByte }
   668  func (b blockSlice) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }
   669  
   670  // offset translates a token position into a 0-indexed byte offset.
   671  func (f *File) offset(pos token.Pos) int {
   672  	return f.fset.Position(pos).Offset
   673  }
   674  
   675  // addVariables adds to the end of the file the declarations to set up the counter and position variables.
   676  func (f *File) addVariables(w io.Writer) {
   677  	// Self-check: Verify that the instrumented basic blocks are disjoint.
   678  	t := make([]block1, len(f.blocks))
   679  	for i := range f.blocks {
   680  		t[i].Block = f.blocks[i]
   681  		t[i].index = i
   682  	}
   683  	sort.Sort(blockSlice(t))
   684  	for i := 1; i < len(t); i++ {
   685  		if t[i-1].endByte > t[i].startByte {
   686  			fmt.Fprintf(os.Stderr, "cover: internal error: block %d overlaps block %d\n", t[i-1].index, t[i].index)
   687  			// Note: error message is in byte positions, not token positions.
   688  			fmt.Fprintf(os.Stderr, "\t%s:#%d,#%d %s:#%d,#%d\n",
   689  				f.name, f.offset(t[i-1].startByte), f.offset(t[i-1].endByte),
   690  				f.name, f.offset(t[i].startByte), f.offset(t[i].endByte))
   691  		}
   692  	}
   693  
   694  	// Declare the coverage struct as a package-level variable.
   695  	fmt.Fprintf(w, "\nvar %s = struct {\n", *varVar)
   696  	fmt.Fprintf(w, "\tCount     [%d]uint32\n", len(f.blocks))
   697  	fmt.Fprintf(w, "\tPos       [3 * %d]uint32\n", len(f.blocks))
   698  	fmt.Fprintf(w, "\tNumStmt   [%d]uint16\n", len(f.blocks))
   699  	fmt.Fprintf(w, "} {\n")
   700  
   701  	// Initialize the position array field.
   702  	fmt.Fprintf(w, "\tPos: [3 * %d]uint32{\n", len(f.blocks))
   703  
   704  	// A nice long list of positions. Each position is encoded as follows to reduce size:
   705  	// - 32-bit starting line number
   706  	// - 32-bit ending line number
   707  	// - (16 bit ending column number << 16) | (16-bit starting column number).
   708  	for i, block := range f.blocks {
   709  		start := f.fset.Position(block.startByte)
   710  		end := f.fset.Position(block.endByte)
   711  		fmt.Fprintf(w, "\t\t%d, %d, %#x, // [%d]\n", start.Line, end.Line, (end.Column&0xFFFF)<<16|(start.Column&0xFFFF), i)
   712  	}
   713  
   714  	// Close the position array.
   715  	fmt.Fprintf(w, "\t},\n")
   716  
   717  	// Initialize the position array field.
   718  	fmt.Fprintf(w, "\tNumStmt: [%d]uint16{\n", len(f.blocks))
   719  
   720  	// A nice long list of statements-per-block, so we can give a conventional
   721  	// valuation of "percent covered". To save space, it's a 16-bit number, so we
   722  	// clamp it if it overflows - won't matter in practice.
   723  	for i, block := range f.blocks {
   724  		n := block.numStmt
   725  		if n > 1<<16-1 {
   726  			n = 1<<16 - 1
   727  		}
   728  		fmt.Fprintf(w, "\t\t%d, // %d\n", n, i)
   729  	}
   730  
   731  	// Close the statements-per-block array.
   732  	fmt.Fprintf(w, "\t},\n")
   733  
   734  	// Close the struct initialization.
   735  	fmt.Fprintf(w, "}\n")
   736  }