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.
25 const usageMessage = "" +
26 `Usage of 'go tool cover':
27 Given a coverage profile produced by 'go test':
28 go test -coverprofile=c.out
30 Open a web browser displaying annotated source code:
31 go tool cover -html=c.out
33 Write out an HTML file instead of launching a web browser:
34 go tool cover -html=c.out -o coverage.html
36 Display coverage percentages to stdout for each function:
37 go tool cover -func=c.out
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
45 fmt.Fprintln(os.Stderr, usageMessage)
46 fmt.Fprintln(os.Stderr, "Flags:")
48 fmt.Fprintln(os.Stderr, "\n Only one of -html, -func, or -mode may be set.")
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")
60 var profile string // The profile to read; the value of -html or -func
62 var counterStmt func(*File, ast.Expr) ast.Stmt
65 atomicPackagePath = "sync/atomic"
66 atomicPackageName = "_cover_atomic_"
73 // Usage information when no arguments.
74 if flag.NFlag() == 0 && flag.NArg() == 0 {
80 fmt.Fprintln(os.Stderr, err)
81 fmt.Fprintln(os.Stderr, `For usage information, run "go tool cover -help"`)
85 // Generate coverage-annotated source.
91 // Output HTML or function coverage information.
93 err = htmlOutput(profile, *output)
95 err = funcOutput(profile, *output)
99 fmt.Fprintf(os.Stderr, "cover: %v\n", err)
104 // parseFlags sets the profile and counterStmt globals and performs validations.
105 func parseFlags() error {
109 return fmt.Errorf("too many options")
114 // Must either display a profile or rewrite Go source.
115 if (profile == "") == (*mode == "") {
116 return fmt.Errorf("too many options")
122 counterStmt = setCounterStmt
124 counterStmt = incCounterStmt
126 counterStmt = atomicCounterStmt
128 return fmt.Errorf("unknown -mode %v", *mode)
131 if flag.NArg() == 0 {
132 return fmt.Errorf("missing source file")
133 } else if flag.NArg() == 1 {
136 } else if flag.NArg() == 0 {
139 return fmt.Errorf("too many arguments")
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.
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.
155 name string // Name of file.
158 atomicPkg string // Package name for "sync/atomic" in this file.
161 // Visit implements the ast.Visitor interface.
162 func (f *File) Visit(node ast.Node) ast.Visitor {
163 switch n := node.(type) {
165 // If it's a switch or select, the body is a list of case clauses; don't tag the block itself.
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)
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)
182 n.List = f.addCounters(n.Lbrace, n.Rbrace+1, n.List, true) // +1 to step past closing brace.
188 // The elses are special, because if we have
192 // we want to cover the "if y". To do this, we need a place to drop the counter,
193 // so we add a hidden block:
199 switch stmt := n.Else.(type) {
201 block := &ast.BlockStmt{
202 Lbrace: n.Body.End(), // Start at end of the "if" block so the covered part looks like it starts at the "else".
203 List: []ast.Stmt{stmt},
208 stmt.Lbrace = n.Body.End() // Start at end of the "if" block so the covered part looks like it starts at the "else".
210 panic("unexpected node type in if")
214 case *ast.SelectStmt:
215 // Don't annotate an empty select - creates a syntax error.
216 if n.Body == nil || len(n.Body.List) == 0 {
219 case *ast.SwitchStmt:
220 // Don't annotate an empty switch - creates a syntax error.
221 if n.Body == nil || len(n.Body.List) == 0 {
224 case *ast.TypeSwitchStmt:
225 // Don't annotate an empty type switch - creates a syntax error.
226 if n.Body == nil || len(n.Body.List) == 0 {
233 // unquote returns the unquoted string.
234 func unquote(s string) string {
235 t, err := strconv.Unquote(s)
237 log.Fatalf("cover: improperly quoted string %q\n", s)
242 // addImport adds an import for the specified path, if one does not already exist, and returns
243 // the local package name.
244 func (f *File) addImport(path string) string {
245 // Does the package already import it?
246 for _, s := range f.astFile.Imports {
247 if unquote(s.Path.Value) == path {
251 return filepath.Base(path)
254 newImport := &ast.ImportSpec{
255 Name: ast.NewIdent(atomicPackageName),
258 Value: fmt.Sprintf("%q", path),
261 impDecl := &ast.GenDecl{
267 // Make the new import the first Decl in the file.
269 astFile.Decls = append(astFile.Decls, nil)
270 copy(astFile.Decls[1:], astFile.Decls[0:])
271 astFile.Decls[0] = impDecl
272 astFile.Imports = append(astFile.Imports, newImport)
274 // Now refer to the package, just in case it ends up unused.
275 // That is, append to the end of the file the declaration
276 // var _ = _cover_atomic_.AddUint32
277 reference := &ast.GenDecl{
286 X: ast.NewIdent(atomicPackageName),
287 Sel: ast.NewIdent("AddUint32"),
293 astFile.Decls = append(astFile.Decls, reference)
294 return atomicPackageName
297 var slashslash = []byte("//")
299 // initialComments returns the prefix of content containing only
300 // whitespace and line comments. Any +build directives must appear
301 // within this region. This approach is more reliable than using
302 // go/printer to print a modified AST containing comments.
304 func initialComments(content []byte) []byte {
305 // Derived from go/build.Context.shouldBuild.
310 if i := bytes.IndexByte(line, '\n'); i >= 0 {
311 line, p = line[:i], p[i+1:]
315 line = bytes.TrimSpace(line)
316 if len(line) == 0 { // Blank line.
317 end = len(content) - len(p)
320 if !bytes.HasPrefix(line, slashslash) { // Not comment line.
327 func annotate(name string) {
328 fset := token.NewFileSet()
329 content, err := ioutil.ReadFile(name)
331 log.Fatalf("cover: %s: %s", name, err)
333 parsedFile, err := parser.ParseFile(fset, name, content, parser.ParseComments)
335 log.Fatalf("cover: %s: %s", name, err)
337 parsedFile.Comments = trimComments(parsedFile, fset)
344 if *mode == "atomic" {
345 file.atomicPkg = file.addImport(atomicPackagePath)
347 ast.Walk(file, file.astFile)
351 fd, err = os.Create(*output)
353 log.Fatalf("cover: %s", err)
356 fd.Write(initialComments(content)) // Retain '// +build' directives.
358 // After printing the source tree, add some declarations for the counters etc.
359 // We could do this by adding to the tree, but it's easier just to print the text.
360 file.addVariables(fd)
363 // trimComments drops all but the //go: comments, some of which are semantically important.
364 // We drop all others because they can appear in places that cause our counters
365 // to appear in syntactically incorrect places. //go: appears at the beginning of
366 // the line and is syntactically safe.
367 func trimComments(file *ast.File, fset *token.FileSet) []*ast.CommentGroup {
368 var comments []*ast.CommentGroup
369 for _, group := range file.Comments {
370 var list []*ast.Comment
371 for _, comment := range group.List {
372 if strings.HasPrefix(comment.Text, "//go:") && fset.Position(comment.Slash).Column == 1 {
373 list = append(list, comment)
377 comments = append(comments, &ast.CommentGroup{List: list})
383 func (f *File) print(w io.Writer) {
384 printer.Fprint(w, f.fset, f.astFile)
387 // intLiteral returns an ast.BasicLit representing the integer value.
388 func (f *File) intLiteral(i int) *ast.BasicLit {
389 node := &ast.BasicLit{
391 Value: fmt.Sprint(i),
396 // index returns an ast.BasicLit representing the number of counters present.
397 func (f *File) index() *ast.BasicLit {
398 return f.intLiteral(len(f.blocks))
401 // setCounterStmt returns the expression: __count[23] = 1.
402 func setCounterStmt(f *File, counter ast.Expr) ast.Stmt {
403 return &ast.AssignStmt{
404 Lhs: []ast.Expr{counter},
406 Rhs: []ast.Expr{f.intLiteral(1)},
410 // incCounterStmt returns the expression: __count[23]++.
411 func incCounterStmt(f *File, counter ast.Expr) ast.Stmt {
412 return &ast.IncDecStmt{
418 // atomicCounterStmt returns the expression: atomic.AddUint32(&__count[23], 1)
419 func atomicCounterStmt(f *File, counter ast.Expr) ast.Stmt {
420 return &ast.ExprStmt{
422 Fun: &ast.SelectorExpr{
423 X: ast.NewIdent(f.atomicPkg),
424 Sel: ast.NewIdent("AddUint32"),
426 Args: []ast.Expr{&ast.UnaryExpr{
436 // newCounter creates a new counter expression of the appropriate form.
437 func (f *File) newCounter(start, end token.Pos, numStmt int) ast.Stmt {
438 counter := &ast.IndexExpr{
439 X: &ast.SelectorExpr{
440 X: ast.NewIdent(*varVar),
441 Sel: ast.NewIdent("Count"),
445 stmt := counterStmt(f, counter)
446 f.blocks = append(f.blocks, Block{start, end, numStmt})
450 // addCounters takes a list of statements and adds counters to the beginning of
451 // each basic block at the top level of that list. For instance, given
459 // counters will be added before S1 and before S3. The block containing S2
460 // will be visited in a separate call.
461 // TODO: Nested simple blocks get unnecessary (but correct) counters
462 func (f *File) addCounters(pos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) []ast.Stmt {
463 // Special case: make sure we add a counter to an empty block. Can't do this below
464 // or we will add a counter to an empty statement list after, say, a return statement.
466 return []ast.Stmt{f.newCounter(pos, blockEnd, 0)}
468 // We have a block (statement list), but it may have several basic blocks due to the
469 // appearance of statements that affect the flow of control.
470 var newList []ast.Stmt
472 // Find first statement that affects flow of control (break, continue, if, etc.).
473 // It will be the last statement of this basic block.
476 for last = 0; last < len(list); last++ {
477 end = f.statementBoundary(list[last])
478 if f.endsBasicSourceBlock(list[last]) {
479 extendToClosingBrace = false // Block is broken up now.
484 if extendToClosingBrace {
487 if pos != end { // Can have no source to cover if e.g. blocks abut.
488 newList = append(newList, f.newCounter(pos, end, last))
490 newList = append(newList, list[0:last]...)
500 // hasFuncLiteral reports the existence and position of the first func literal
501 // in the node, if any. If a func literal appears, it usually marks the termination
502 // of a basic block because the function body is itself a block.
503 // Therefore we draw a line at the start of the body of the first function literal we find.
504 // TODO: what if there's more than one? Probably doesn't matter much.
505 func hasFuncLiteral(n ast.Node) (bool, token.Pos) {
509 var literal funcLitFinder
510 ast.Walk(&literal, n)
511 return literal.found(), token.Pos(literal)
514 // statementBoundary finds the location in s that terminates the current basic
515 // block in the source.
516 func (f *File) statementBoundary(s ast.Stmt) token.Pos {
517 // Control flow statements are easy.
518 switch s := s.(type) {
520 // Treat blocks like basic blocks to avoid overlapping counters.
523 found, pos := hasFuncLiteral(s.Init)
527 found, pos = hasFuncLiteral(s.Cond)
533 found, pos := hasFuncLiteral(s.Init)
537 found, pos = hasFuncLiteral(s.Cond)
541 found, pos = hasFuncLiteral(s.Post)
546 case *ast.LabeledStmt:
547 return f.statementBoundary(s.Stmt)
549 found, pos := hasFuncLiteral(s.X)
554 case *ast.SwitchStmt:
555 found, pos := hasFuncLiteral(s.Init)
559 found, pos = hasFuncLiteral(s.Tag)
564 case *ast.SelectStmt:
566 case *ast.TypeSwitchStmt:
567 found, pos := hasFuncLiteral(s.Init)
573 // If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal.
574 // If it does, that's tricky because we want to exclude the body of the function from this block.
575 // Draw a line at the start of the body of the first function literal we find.
576 // TODO: what if there's more than one? Probably doesn't matter much.
577 found, pos := hasFuncLiteral(s)
584 // endsBasicSourceBlock reports whether s changes the flow of control: break, if, etc.,
585 // or if it's just problematic, for instance contains a function literal, which will complicate
586 // accounting due to the block-within-an expression.
587 func (f *File) endsBasicSourceBlock(s ast.Stmt) bool {
588 switch s := s.(type) {
590 // Treat blocks like basic blocks to avoid overlapping counters.
592 case *ast.BranchStmt:
598 case *ast.LabeledStmt:
599 return f.endsBasicSourceBlock(s.Stmt)
602 case *ast.SwitchStmt:
604 case *ast.SelectStmt:
606 case *ast.TypeSwitchStmt:
609 // Calls to panic change the flow.
610 // We really should verify that "panic" is the predefined function,
611 // but without type checking we can't and the likelihood of it being
612 // an actual problem is vanishingly small.
613 if call, ok := s.X.(*ast.CallExpr); ok {
614 if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 {
619 found, _ := hasFuncLiteral(s)
623 // funcLitFinder implements the ast.Visitor pattern to find the location of any
624 // function literal in a subtree.
625 type funcLitFinder token.Pos
627 func (f *funcLitFinder) Visit(node ast.Node) (w ast.Visitor) {
629 return nil // Prune search.
631 switch n := node.(type) {
633 *f = funcLitFinder(n.Body.Lbrace)
634 return nil // Prune search.
639 func (f *funcLitFinder) found() bool {
640 return token.Pos(*f) != token.NoPos
643 // Sort interface for []block1; used for self-check in addVariables.
650 type blockSlice []block1
652 func (b blockSlice) Len() int { return len(b) }
653 func (b blockSlice) Less(i, j int) bool { return b[i].startByte < b[j].startByte }
654 func (b blockSlice) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
656 // offset translates a token position into a 0-indexed byte offset.
657 func (f *File) offset(pos token.Pos) int {
658 return f.fset.Position(pos).Offset
661 // addVariables adds to the end of the file the declarations to set up the counter and position variables.
662 func (f *File) addVariables(w io.Writer) {
663 // Self-check: Verify that the instrumented basic blocks are disjoint.
664 t := make([]block1, len(f.blocks))
665 for i := range f.blocks {
666 t[i].Block = f.blocks[i]
669 sort.Sort(blockSlice(t))
670 for i := 1; i < len(t); i++ {
671 if t[i-1].endByte > t[i].startByte {
672 fmt.Fprintf(os.Stderr, "cover: internal error: block %d overlaps block %d\n", t[i-1].index, t[i].index)
673 // Note: error message is in byte positions, not token positions.
674 fmt.Fprintf(os.Stderr, "\t%s:#%d,#%d %s:#%d,#%d\n",
675 f.name, f.offset(t[i-1].startByte), f.offset(t[i-1].endByte),
676 f.name, f.offset(t[i].startByte), f.offset(t[i].endByte))
680 // Declare the coverage struct as a package-level variable.
681 fmt.Fprintf(w, "\nvar %s = struct {\n", *varVar)
682 fmt.Fprintf(w, "\tCount [%d]uint32\n", len(f.blocks))
683 fmt.Fprintf(w, "\tPos [3 * %d]uint32\n", len(f.blocks))
684 fmt.Fprintf(w, "\tNumStmt [%d]uint16\n", len(f.blocks))
685 fmt.Fprintf(w, "} {\n")
687 // Initialize the position array field.
688 fmt.Fprintf(w, "\tPos: [3 * %d]uint32{\n", len(f.blocks))
690 // A nice long list of positions. Each position is encoded as follows to reduce size:
691 // - 32-bit starting line number
692 // - 32-bit ending line number
693 // - (16 bit ending column number << 16) | (16-bit starting column number).
694 for i, block := range f.blocks {
695 start := f.fset.Position(block.startByte)
696 end := f.fset.Position(block.endByte)
697 fmt.Fprintf(w, "\t\t%d, %d, %#x, // [%d]\n", start.Line, end.Line, (end.Column&0xFFFF)<<16|(start.Column&0xFFFF), i)
700 // Close the position array.
701 fmt.Fprintf(w, "\t},\n")
703 // Initialize the position array field.
704 fmt.Fprintf(w, "\tNumStmt: [%d]uint16{\n", len(f.blocks))
706 // A nice long list of statements-per-block, so we can give a conventional
707 // valuation of "percent covered". To save space, it's a 16-bit number, so we
708 // clamp it if it overflows - won't matter in practice.
709 for i, block := range f.blocks {
714 fmt.Fprintf(w, "\t\t%d, // %d\n", n, i)
717 // Close the statements-per-block array.
718 fmt.Fprintf(w, "\t},\n")
720 // Close the struct initialization.
721 fmt.Fprintf(w, "}\n")