github.com/epfl-dcsl/gotee@v0.0.0-20200909122901-014b35f5e5e9/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/token" 14 "io" 15 "io/ioutil" 16 "log" 17 "os" 18 "sort" 19 "strconv" 20 21 "cmd/internal/edit" 22 "cmd/internal/objabi" 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, string) string 63 64 const ( 65 atomicPackagePath = "sync/atomic" 66 atomicPackageName = "_cover_atomic_" 67 ) 68 69 func main() { 70 objabi.AddVersionFlag() 71 flag.Usage = usage 72 flag.Parse() 73 74 // Usage information when no arguments. 75 if flag.NFlag() == 0 && flag.NArg() == 0 { 76 flag.Usage() 77 } 78 79 err := parseFlags() 80 if err != nil { 81 fmt.Fprintln(os.Stderr, err) 82 fmt.Fprintln(os.Stderr, `For usage information, run "go tool cover -help"`) 83 os.Exit(2) 84 } 85 86 // Generate coverage-annotated source. 87 if *mode != "" { 88 annotate(flag.Arg(0)) 89 return 90 } 91 92 // Output HTML or function coverage information. 93 if *htmlOut != "" { 94 err = htmlOutput(profile, *output) 95 } else { 96 err = funcOutput(profile, *output) 97 } 98 99 if err != nil { 100 fmt.Fprintf(os.Stderr, "cover: %v\n", err) 101 os.Exit(2) 102 } 103 } 104 105 // parseFlags sets the profile and counterStmt globals and performs validations. 106 func parseFlags() error { 107 profile = *htmlOut 108 if *funcOut != "" { 109 if profile != "" { 110 return fmt.Errorf("too many options") 111 } 112 profile = *funcOut 113 } 114 115 // Must either display a profile or rewrite Go source. 116 if (profile == "") == (*mode == "") { 117 return fmt.Errorf("too many options") 118 } 119 120 if *mode != "" { 121 switch *mode { 122 case "set": 123 counterStmt = setCounterStmt 124 case "count": 125 counterStmt = incCounterStmt 126 case "atomic": 127 counterStmt = atomicCounterStmt 128 default: 129 return fmt.Errorf("unknown -mode %v", *mode) 130 } 131 132 if flag.NArg() == 0 { 133 return fmt.Errorf("missing source file") 134 } else if flag.NArg() == 1 { 135 return nil 136 } 137 } else if flag.NArg() == 0 { 138 return nil 139 } 140 return fmt.Errorf("too many arguments") 141 } 142 143 // Block represents the information about a basic block to be recorded in the analysis. 144 // Note: Our definition of basic block is based on control structures; we don't break 145 // apart && and ||. We could but it doesn't seem important enough to bother. 146 type Block struct { 147 startByte token.Pos 148 endByte token.Pos 149 numStmt int 150 } 151 152 // File is a wrapper for the state of a file used in the parser. 153 // The basic parse tree walker is a method of this type. 154 type File struct { 155 fset *token.FileSet 156 name string // Name of file. 157 astFile *ast.File 158 blocks []Block 159 content []byte 160 edit *edit.Buffer 161 } 162 163 // findText finds text in the original source, starting at pos. 164 // It correctly skips over comments and assumes it need not 165 // handle quoted strings. 166 // It returns a byte offset within f.src. 167 func (f *File) findText(pos token.Pos, text string) int { 168 b := []byte(text) 169 start := f.offset(pos) 170 i := start 171 s := f.content 172 for i < len(s) { 173 if bytes.HasPrefix(s[i:], b) { 174 return i 175 } 176 if i+2 <= len(s) && s[i] == '/' && s[i+1] == '/' { 177 for i < len(s) && s[i] != '\n' { 178 i++ 179 } 180 continue 181 } 182 if i+2 <= len(s) && s[i] == '/' && s[i+1] == '*' { 183 for i += 2; ; i++ { 184 if i+2 > len(s) { 185 return 0 186 } 187 if s[i] == '*' && s[i+1] == '/' { 188 i += 2 189 break 190 } 191 } 192 continue 193 } 194 i++ 195 } 196 return -1 197 } 198 199 // Visit implements the ast.Visitor interface. 200 func (f *File) Visit(node ast.Node) ast.Visitor { 201 switch n := node.(type) { 202 case *ast.BlockStmt: 203 // If it's a switch or select, the body is a list of case clauses; don't tag the block itself. 204 if len(n.List) > 0 { 205 switch n.List[0].(type) { 206 case *ast.CaseClause: // switch 207 for _, n := range n.List { 208 clause := n.(*ast.CaseClause) 209 f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false) 210 } 211 return f 212 case *ast.CommClause: // select 213 for _, n := range n.List { 214 clause := n.(*ast.CommClause) 215 f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false) 216 } 217 return f 218 } 219 } 220 f.addCounters(n.Lbrace, n.Lbrace+1, n.Rbrace+1, n.List, true) // +1 to step past closing brace. 221 case *ast.IfStmt: 222 if n.Init != nil { 223 ast.Walk(f, n.Init) 224 } 225 ast.Walk(f, n.Cond) 226 ast.Walk(f, n.Body) 227 if n.Else == nil { 228 return nil 229 } 230 // The elses are special, because if we have 231 // if x { 232 // } else if y { 233 // } 234 // we want to cover the "if y". To do this, we need a place to drop the counter, 235 // so we add a hidden block: 236 // if x { 237 // } else { 238 // if y { 239 // } 240 // } 241 elseOffset := f.findText(n.Body.End(), "else") 242 if elseOffset < 0 { 243 panic("lost else") 244 } 245 f.edit.Insert(elseOffset+4, "{") 246 f.edit.Insert(f.offset(n.Else.End()), "}") 247 248 // We just created a block, now walk it. 249 // Adjust the position of the new block to start after 250 // the "else". That will cause it to follow the "{" 251 // we inserted above. 252 pos := f.fset.File(n.Body.End()).Pos(elseOffset + 4) 253 switch stmt := n.Else.(type) { 254 case *ast.IfStmt: 255 block := &ast.BlockStmt{ 256 Lbrace: pos, 257 List: []ast.Stmt{stmt}, 258 Rbrace: stmt.End(), 259 } 260 n.Else = block 261 case *ast.BlockStmt: 262 stmt.Lbrace = pos 263 default: 264 panic("unexpected node type in if") 265 } 266 ast.Walk(f, n.Else) 267 return nil 268 case *ast.SelectStmt: 269 // Don't annotate an empty select - creates a syntax error. 270 if n.Body == nil || len(n.Body.List) == 0 { 271 return nil 272 } 273 case *ast.SwitchStmt: 274 // Don't annotate an empty switch - creates a syntax error. 275 if n.Body == nil || len(n.Body.List) == 0 { 276 if n.Init != nil { 277 ast.Walk(f, n.Init) 278 } 279 if n.Tag != nil { 280 ast.Walk(f, n.Tag) 281 } 282 return nil 283 } 284 case *ast.TypeSwitchStmt: 285 // Don't annotate an empty type switch - creates a syntax error. 286 if n.Body == nil || len(n.Body.List) == 0 { 287 if n.Init != nil { 288 ast.Walk(f, n.Init) 289 } 290 ast.Walk(f, n.Assign) 291 return nil 292 } 293 } 294 return f 295 } 296 297 // unquote returns the unquoted string. 298 func unquote(s string) string { 299 t, err := strconv.Unquote(s) 300 if err != nil { 301 log.Fatalf("cover: improperly quoted string %q\n", s) 302 } 303 return t 304 } 305 306 var slashslash = []byte("//") 307 308 func annotate(name string) { 309 fset := token.NewFileSet() 310 content, err := ioutil.ReadFile(name) 311 if err != nil { 312 log.Fatalf("cover: %s: %s", name, err) 313 } 314 parsedFile, err := parser.ParseFile(fset, name, content, parser.ParseComments) 315 if err != nil { 316 log.Fatalf("cover: %s: %s", name, err) 317 } 318 319 file := &File{ 320 fset: fset, 321 name: name, 322 content: content, 323 edit: edit.NewBuffer(content), 324 astFile: parsedFile, 325 } 326 if *mode == "atomic" { 327 // Add import of sync/atomic immediately after package clause. 328 // We do this even if there is an existing import, because the 329 // existing import may be shadowed at any given place we want 330 // to refer to it, and our name (_cover_atomic_) is less likely to 331 // be shadowed. 332 file.edit.Insert(file.offset(file.astFile.Name.End()), 333 fmt.Sprintf("; import %s %q", atomicPackageName, atomicPackagePath)) 334 } 335 336 ast.Walk(file, file.astFile) 337 newContent := file.edit.Bytes() 338 339 fd := os.Stdout 340 if *output != "" { 341 var err error 342 fd, err = os.Create(*output) 343 if err != nil { 344 log.Fatalf("cover: %s", err) 345 } 346 } 347 348 fmt.Fprintf(fd, "//line %s:1\n", name) 349 fd.Write(newContent) 350 351 // After printing the source tree, add some declarations for the counters etc. 352 // We could do this by adding to the tree, but it's easier just to print the text. 353 file.addVariables(fd) 354 } 355 356 // setCounterStmt returns the expression: __count[23] = 1. 357 func setCounterStmt(f *File, counter string) string { 358 return fmt.Sprintf("%s = 1", counter) 359 } 360 361 // incCounterStmt returns the expression: __count[23]++. 362 func incCounterStmt(f *File, counter string) string { 363 return fmt.Sprintf("%s++", counter) 364 } 365 366 // atomicCounterStmt returns the expression: atomic.AddUint32(&__count[23], 1) 367 func atomicCounterStmt(f *File, counter string) string { 368 return fmt.Sprintf("%s.AddUint32(&%s, 1)", atomicPackageName, counter) 369 } 370 371 // newCounter creates a new counter expression of the appropriate form. 372 func (f *File) newCounter(start, end token.Pos, numStmt int) string { 373 stmt := counterStmt(f, fmt.Sprintf("%s.Count[%d]", *varVar, len(f.blocks))) 374 f.blocks = append(f.blocks, Block{start, end, numStmt}) 375 return stmt 376 } 377 378 // addCounters takes a list of statements and adds counters to the beginning of 379 // each basic block at the top level of that list. For instance, given 380 // 381 // S1 382 // if cond { 383 // S2 384 // } 385 // S3 386 // 387 // counters will be added before S1 and before S3. The block containing S2 388 // will be visited in a separate call. 389 // TODO: Nested simple blocks get unnecessary (but correct) counters 390 func (f *File) addCounters(pos, insertPos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) { 391 // Special case: make sure we add a counter to an empty block. Can't do this below 392 // or we will add a counter to an empty statement list after, say, a return statement. 393 if len(list) == 0 { 394 f.edit.Insert(f.offset(insertPos), f.newCounter(insertPos, blockEnd, 0)+";") 395 return 396 } 397 // We have a block (statement list), but it may have several basic blocks due to the 398 // appearance of statements that affect the flow of control. 399 for { 400 // Find first statement that affects flow of control (break, continue, if, etc.). 401 // It will be the last statement of this basic block. 402 var last int 403 end := blockEnd 404 for last = 0; last < len(list); last++ { 405 stmt := list[last] 406 end = f.statementBoundary(stmt) 407 if f.endsBasicSourceBlock(stmt) { 408 // If it is a labeled statement, we need to place a counter between 409 // the label and its statement because it may be the target of a goto 410 // and thus start a basic block. That is, given 411 // foo: stmt 412 // we need to create 413 // foo: ; stmt 414 // and mark the label as a block-terminating statement. 415 // The result will then be 416 // foo: COUNTER[n]++; stmt 417 // However, we can't do this if the labeled statement is already 418 // a control statement, such as a labeled for. 419 if label, isLabel := stmt.(*ast.LabeledStmt); isLabel && !f.isControl(label.Stmt) { 420 newLabel := *label 421 newLabel.Stmt = &ast.EmptyStmt{ 422 Semicolon: label.Stmt.Pos(), 423 Implicit: true, 424 } 425 end = label.Pos() // Previous block ends before the label. 426 list[last] = &newLabel 427 // Open a gap and drop in the old statement, now without a label. 428 list = append(list, nil) 429 copy(list[last+1:], list[last:]) 430 list[last+1] = label.Stmt 431 } 432 last++ 433 extendToClosingBrace = false // Block is broken up now. 434 break 435 } 436 } 437 if extendToClosingBrace { 438 end = blockEnd 439 } 440 if pos != end { // Can have no source to cover if e.g. blocks abut. 441 f.edit.Insert(f.offset(insertPos), f.newCounter(pos, end, last)+";") 442 } 443 list = list[last:] 444 if len(list) == 0 { 445 break 446 } 447 pos = list[0].Pos() 448 insertPos = pos 449 } 450 } 451 452 // hasFuncLiteral reports the existence and position of the first func literal 453 // in the node, if any. If a func literal appears, it usually marks the termination 454 // of a basic block because the function body is itself a block. 455 // Therefore we draw a line at the start of the body of the first function literal we find. 456 // TODO: what if there's more than one? Probably doesn't matter much. 457 func hasFuncLiteral(n ast.Node) (bool, token.Pos) { 458 if n == nil { 459 return false, 0 460 } 461 var literal funcLitFinder 462 ast.Walk(&literal, n) 463 return literal.found(), token.Pos(literal) 464 } 465 466 // statementBoundary finds the location in s that terminates the current basic 467 // block in the source. 468 func (f *File) statementBoundary(s ast.Stmt) token.Pos { 469 // Control flow statements are easy. 470 switch s := s.(type) { 471 case *ast.BlockStmt: 472 // Treat blocks like basic blocks to avoid overlapping counters. 473 return s.Lbrace 474 case *ast.IfStmt: 475 found, pos := hasFuncLiteral(s.Init) 476 if found { 477 return pos 478 } 479 found, pos = hasFuncLiteral(s.Cond) 480 if found { 481 return pos 482 } 483 return s.Body.Lbrace 484 case *ast.ForStmt: 485 found, pos := hasFuncLiteral(s.Init) 486 if found { 487 return pos 488 } 489 found, pos = hasFuncLiteral(s.Cond) 490 if found { 491 return pos 492 } 493 found, pos = hasFuncLiteral(s.Post) 494 if found { 495 return pos 496 } 497 return s.Body.Lbrace 498 case *ast.LabeledStmt: 499 return f.statementBoundary(s.Stmt) 500 case *ast.RangeStmt: 501 found, pos := hasFuncLiteral(s.X) 502 if found { 503 return pos 504 } 505 return s.Body.Lbrace 506 case *ast.SwitchStmt: 507 found, pos := hasFuncLiteral(s.Init) 508 if found { 509 return pos 510 } 511 found, pos = hasFuncLiteral(s.Tag) 512 if found { 513 return pos 514 } 515 return s.Body.Lbrace 516 case *ast.SelectStmt: 517 return s.Body.Lbrace 518 case *ast.TypeSwitchStmt: 519 found, pos := hasFuncLiteral(s.Init) 520 if found { 521 return pos 522 } 523 return s.Body.Lbrace 524 } 525 // If not a control flow statement, it is a declaration, expression, call, etc. and it may have a function literal. 526 // If it does, that's tricky because we want to exclude the body of the function from this block. 527 // Draw a line at the start of the body of the first function literal we find. 528 // TODO: what if there's more than one? Probably doesn't matter much. 529 found, pos := hasFuncLiteral(s) 530 if found { 531 return pos 532 } 533 return s.End() 534 } 535 536 // endsBasicSourceBlock reports whether s changes the flow of control: break, if, etc., 537 // or if it's just problematic, for instance contains a function literal, which will complicate 538 // accounting due to the block-within-an expression. 539 func (f *File) endsBasicSourceBlock(s ast.Stmt) bool { 540 switch s := s.(type) { 541 case *ast.BlockStmt: 542 // Treat blocks like basic blocks to avoid overlapping counters. 543 return true 544 case *ast.BranchStmt: 545 return true 546 case *ast.ForStmt: 547 return true 548 case *ast.IfStmt: 549 return true 550 case *ast.LabeledStmt: 551 return true // A goto may branch here, starting a new basic block. 552 case *ast.RangeStmt: 553 return true 554 case *ast.SwitchStmt: 555 return true 556 case *ast.SelectStmt: 557 return true 558 case *ast.TypeSwitchStmt: 559 return true 560 case *ast.ExprStmt: 561 // Calls to panic change the flow. 562 // We really should verify that "panic" is the predefined function, 563 // but without type checking we can't and the likelihood of it being 564 // an actual problem is vanishingly small. 565 if call, ok := s.X.(*ast.CallExpr); ok { 566 if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 { 567 return true 568 } 569 } 570 } 571 found, _ := hasFuncLiteral(s) 572 return found 573 } 574 575 // isControl reports whether s is a control statement that, if labeled, cannot be 576 // separated from its label. 577 func (f *File) isControl(s ast.Stmt) bool { 578 switch s.(type) { 579 case *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt, *ast.TypeSwitchStmt: 580 return true 581 } 582 return false 583 } 584 585 // funcLitFinder implements the ast.Visitor pattern to find the location of any 586 // function literal in a subtree. 587 type funcLitFinder token.Pos 588 589 func (f *funcLitFinder) Visit(node ast.Node) (w ast.Visitor) { 590 if f.found() { 591 return nil // Prune search. 592 } 593 switch n := node.(type) { 594 case *ast.FuncLit: 595 *f = funcLitFinder(n.Body.Lbrace) 596 return nil // Prune search. 597 } 598 return f 599 } 600 601 func (f *funcLitFinder) found() bool { 602 return token.Pos(*f) != token.NoPos 603 } 604 605 // Sort interface for []block1; used for self-check in addVariables. 606 607 type block1 struct { 608 Block 609 index int 610 } 611 612 type blockSlice []block1 613 614 func (b blockSlice) Len() int { return len(b) } 615 func (b blockSlice) Less(i, j int) bool { return b[i].startByte < b[j].startByte } 616 func (b blockSlice) Swap(i, j int) { b[i], b[j] = b[j], b[i] } 617 618 // offset translates a token position into a 0-indexed byte offset. 619 func (f *File) offset(pos token.Pos) int { 620 return f.fset.Position(pos).Offset 621 } 622 623 // addVariables adds to the end of the file the declarations to set up the counter and position variables. 624 func (f *File) addVariables(w io.Writer) { 625 // Self-check: Verify that the instrumented basic blocks are disjoint. 626 t := make([]block1, len(f.blocks)) 627 for i := range f.blocks { 628 t[i].Block = f.blocks[i] 629 t[i].index = i 630 } 631 sort.Sort(blockSlice(t)) 632 for i := 1; i < len(t); i++ { 633 if t[i-1].endByte > t[i].startByte { 634 fmt.Fprintf(os.Stderr, "cover: internal error: block %d overlaps block %d\n", t[i-1].index, t[i].index) 635 // Note: error message is in byte positions, not token positions. 636 fmt.Fprintf(os.Stderr, "\t%s:#%d,#%d %s:#%d,#%d\n", 637 f.name, f.offset(t[i-1].startByte), f.offset(t[i-1].endByte), 638 f.name, f.offset(t[i].startByte), f.offset(t[i].endByte)) 639 } 640 } 641 642 // Declare the coverage struct as a package-level variable. 643 fmt.Fprintf(w, "\nvar %s = struct {\n", *varVar) 644 fmt.Fprintf(w, "\tCount [%d]uint32\n", len(f.blocks)) 645 fmt.Fprintf(w, "\tPos [3 * %d]uint32\n", len(f.blocks)) 646 fmt.Fprintf(w, "\tNumStmt [%d]uint16\n", len(f.blocks)) 647 fmt.Fprintf(w, "} {\n") 648 649 // Initialize the position array field. 650 fmt.Fprintf(w, "\tPos: [3 * %d]uint32{\n", len(f.blocks)) 651 652 // A nice long list of positions. Each position is encoded as follows to reduce size: 653 // - 32-bit starting line number 654 // - 32-bit ending line number 655 // - (16 bit ending column number << 16) | (16-bit starting column number). 656 for i, block := range f.blocks { 657 start := f.fset.Position(block.startByte) 658 end := f.fset.Position(block.endByte) 659 fmt.Fprintf(w, "\t\t%d, %d, %#x, // [%d]\n", start.Line, end.Line, (end.Column&0xFFFF)<<16|(start.Column&0xFFFF), i) 660 } 661 662 // Close the position array. 663 fmt.Fprintf(w, "\t},\n") 664 665 // Initialize the position array field. 666 fmt.Fprintf(w, "\tNumStmt: [%d]uint16{\n", len(f.blocks)) 667 668 // A nice long list of statements-per-block, so we can give a conventional 669 // valuation of "percent covered". To save space, it's a 16-bit number, so we 670 // clamp it if it overflows - won't matter in practice. 671 for i, block := range f.blocks { 672 n := block.numStmt 673 if n > 1<<16-1 { 674 n = 1<<16 - 1 675 } 676 fmt.Fprintf(w, "\t\t%d, // %d\n", n, i) 677 } 678 679 // Close the statements-per-block array. 680 fmt.Fprintf(w, "\t},\n") 681 682 // Close the struct initialization. 683 fmt.Fprintf(w, "}\n") 684 685 // Emit a reference to the atomic package to avoid 686 // import and not used error when there's no code in a file. 687 if *mode == "atomic" { 688 fmt.Fprintf(w, "var _ = %s.LoadUint32\n", atomicPackageName) 689 } 690 }