| |
| |
| |
|
|
| package main |
|
|
| import ( |
| "bytes" |
| "cmd/internal/cov/covcmd" |
| "cmp" |
| "encoding/json" |
| "flag" |
| "fmt" |
| "go/ast" |
| "go/parser" |
| "go/token" |
| "internal/coverage" |
| "internal/coverage/encodemeta" |
| "internal/coverage/slicewriter" |
| "io" |
| "log" |
| "os" |
| "path/filepath" |
| "slices" |
| "strconv" |
| "strings" |
|
|
| "cmd/internal/edit" |
| "cmd/internal/objabi" |
| "cmd/internal/telemetry/counter" |
| ) |
|
|
| const usageMessage = "" + |
| `Usage of 'go tool cover': |
| Given a coverage profile produced by 'go test': |
| go test -coverprofile=c.out |
| |
| Open a web browser displaying annotated source code: |
| go tool cover -html=c.out |
| |
| Write out an HTML file instead of launching a web browser: |
| go tool cover -html=c.out -o coverage.html |
| |
| Display coverage percentages to stdout for each function: |
| go tool cover -func=c.out |
| |
| Finally, to generate modified source code with coverage annotations |
| for a package (what go test -cover does): |
| go tool cover -mode=set -var=CoverageVariableName \ |
| -pkgcfg=<config> -outfilelist=<file> file1.go ... fileN.go |
| |
| where -pkgcfg points to a file containing the package path, |
| package name, module path, and related info from "go build", |
| and -outfilelist points to a file containing the filenames |
| of the instrumented output files (one per input file). |
| See https://pkg.go.dev/cmd/internal/cov/covcmd#CoverPkgConfig for |
| more on the package config. |
| ` |
|
|
| func usage() { |
| fmt.Fprint(os.Stderr, usageMessage) |
| fmt.Fprintln(os.Stderr, "\nFlags:") |
| flag.PrintDefaults() |
| fmt.Fprintln(os.Stderr, "\n Only one of -html, -func, or -mode may be set.") |
| os.Exit(2) |
| } |
|
|
| var ( |
| mode = flag.String("mode", "", "coverage mode: set, count, atomic") |
| varVar = flag.String("var", "GoCover", "name of coverage variable to generate") |
| output = flag.String("o", "", "file for output") |
| outfilelist = flag.String("outfilelist", "", "file containing list of output files (one per line) if -pkgcfg is in use") |
| htmlOut = flag.String("html", "", "generate HTML representation of coverage profile") |
| funcOut = flag.String("func", "", "output coverage profile information for each function") |
| pkgcfg = flag.String("pkgcfg", "", "enable full-package instrumentation mode using params from specified config file") |
| pkgconfig covcmd.CoverPkgConfig |
| outputfiles []string |
| profile string |
| counterStmt func(*File, string) string |
| covervarsoutfile string |
| cmode coverage.CounterMode |
| cgran coverage.CounterGranularity |
| ) |
|
|
| const ( |
| atomicPackagePath = "sync/atomic" |
| atomicPackageName = "_cover_atomic_" |
| ) |
|
|
| func main() { |
| counter.Open() |
|
|
| objabi.AddVersionFlag() |
| flag.Usage = usage |
| objabi.Flagparse(usage) |
| counter.Inc("cover/invocations") |
| counter.CountFlags("cover/flag:", *flag.CommandLine) |
|
|
| |
| if flag.NFlag() == 0 && flag.NArg() == 0 { |
| flag.Usage() |
| } |
|
|
| err := parseFlags() |
| if err != nil { |
| fmt.Fprintln(os.Stderr, err) |
| fmt.Fprintln(os.Stderr, `For usage information, run "go tool cover -help"`) |
| os.Exit(2) |
| } |
|
|
| |
| if *mode != "" { |
| annotate(flag.Args()) |
| return |
| } |
|
|
| |
| if *htmlOut != "" { |
| err = htmlOutput(profile, *output) |
| } else { |
| err = funcOutput(profile, *output) |
| } |
|
|
| if err != nil { |
| fmt.Fprintf(os.Stderr, "cover: %v\n", err) |
| os.Exit(2) |
| } |
| } |
|
|
| |
| func parseFlags() error { |
| profile = *htmlOut |
| if *funcOut != "" { |
| if profile != "" { |
| return fmt.Errorf("too many options") |
| } |
| profile = *funcOut |
| } |
|
|
| |
| if (profile == "") == (*mode == "") { |
| return fmt.Errorf("too many options") |
| } |
|
|
| if *varVar != "" && !token.IsIdentifier(*varVar) { |
| return fmt.Errorf("-var: %q is not a valid identifier", *varVar) |
| } |
|
|
| if *mode != "" { |
| switch *mode { |
| case "set": |
| counterStmt = setCounterStmt |
| cmode = coverage.CtrModeSet |
| case "count": |
| counterStmt = incCounterStmt |
| cmode = coverage.CtrModeCount |
| case "atomic": |
| counterStmt = atomicCounterStmt |
| cmode = coverage.CtrModeAtomic |
| case "regonly": |
| counterStmt = nil |
| cmode = coverage.CtrModeRegOnly |
| case "testmain": |
| counterStmt = nil |
| cmode = coverage.CtrModeTestMain |
| default: |
| return fmt.Errorf("unknown -mode %v", *mode) |
| } |
|
|
| if flag.NArg() == 0 { |
| return fmt.Errorf("missing source file(s)") |
| } else { |
| if *pkgcfg != "" { |
| if *output != "" { |
| return fmt.Errorf("please use '-outfilelist' flag instead of '-o'") |
| } |
| var err error |
| if outputfiles, err = readOutFileList(*outfilelist); err != nil { |
| return err |
| } |
| covervarsoutfile = outputfiles[0] |
| outputfiles = outputfiles[1:] |
| numInputs := len(flag.Args()) |
| numOutputs := len(outputfiles) |
| if numOutputs != numInputs { |
| return fmt.Errorf("number of output files (%d) not equal to number of input files (%d)", numOutputs, numInputs) |
| } |
| if err := readPackageConfig(*pkgcfg); err != nil { |
| return err |
| } |
| return nil |
| } else { |
| if *outfilelist != "" { |
| return fmt.Errorf("'-outfilelist' flag applicable only when -pkgcfg used") |
| } |
| } |
| if flag.NArg() == 1 { |
| return nil |
| } |
| } |
| } else if flag.NArg() == 0 { |
| return nil |
| } |
| return fmt.Errorf("too many arguments") |
| } |
|
|
| func readOutFileList(path string) ([]string, error) { |
| data, err := os.ReadFile(path) |
| if err != nil { |
| return nil, fmt.Errorf("error reading -outfilelist file %q: %v", path, err) |
| } |
| return strings.Split(strings.TrimSpace(string(data)), "\n"), nil |
| } |
|
|
| func readPackageConfig(path string) error { |
| data, err := os.ReadFile(path) |
| if err != nil { |
| return fmt.Errorf("error reading pkgconfig file %q: %v", path, err) |
| } |
| if err := json.Unmarshal(data, &pkgconfig); err != nil { |
| return fmt.Errorf("error reading pkgconfig file %q: %v", path, err) |
| } |
| switch pkgconfig.Granularity { |
| case "perblock": |
| cgran = coverage.CtrGranularityPerBlock |
| case "perfunc": |
| cgran = coverage.CtrGranularityPerFunc |
| default: |
| return fmt.Errorf(`%s: pkgconfig requires perblock/perfunc value`, path) |
| } |
| return nil |
| } |
|
|
| |
| |
| |
| type Block struct { |
| startByte token.Pos |
| endByte token.Pos |
| numStmt int |
| } |
|
|
| |
| type Package struct { |
| mdb *encodemeta.CoverageMetaDataBuilder |
| counterLengths []int |
| } |
|
|
| |
| type Func struct { |
| units []coverage.CoverableUnit |
| counterVar string |
| } |
|
|
| |
| |
| type File struct { |
| fset *token.FileSet |
| name string |
| astFile *ast.File |
| blocks []Block |
| content []byte |
| edit *edit.Buffer |
| mdb *encodemeta.CoverageMetaDataBuilder |
| fn Func |
| pkg *Package |
| } |
|
|
| |
| |
| |
| |
| func (f *File) findText(pos token.Pos, text string) int { |
| b := []byte(text) |
| start := f.offset(pos) |
| i := start |
| s := f.content |
| for i < len(s) { |
| if bytes.HasPrefix(s[i:], b) { |
| return i |
| } |
| if i+2 <= len(s) && s[i] == '/' && s[i+1] == '/' { |
| for i < len(s) && s[i] != '\n' { |
| i++ |
| } |
| continue |
| } |
| if i+2 <= len(s) && s[i] == '/' && s[i+1] == '*' { |
| for i += 2; ; i++ { |
| if i+2 > len(s) { |
| return 0 |
| } |
| if s[i] == '*' && s[i+1] == '/' { |
| i += 2 |
| break |
| } |
| } |
| continue |
| } |
| i++ |
| } |
| return -1 |
| } |
|
|
| |
| func (f *File) Visit(node ast.Node) ast.Visitor { |
| switch n := node.(type) { |
| case *ast.BlockStmt: |
| |
| if len(n.List) > 0 { |
| switch n.List[0].(type) { |
| case *ast.CaseClause: |
| for _, n := range n.List { |
| clause := n.(*ast.CaseClause) |
| f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false) |
| } |
| return f |
| case *ast.CommClause: |
| for _, n := range n.List { |
| clause := n.(*ast.CommClause) |
| f.addCounters(clause.Colon+1, clause.Colon+1, clause.End(), clause.Body, false) |
| } |
| return f |
| } |
| } |
| f.addCounters(n.Lbrace, n.Lbrace+1, n.Rbrace+1, n.List, true) |
| case *ast.IfStmt: |
| if n.Init != nil { |
| ast.Walk(f, n.Init) |
| } |
| ast.Walk(f, n.Cond) |
| ast.Walk(f, n.Body) |
| if n.Else == nil { |
| return nil |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| elseOffset := f.findText(n.Body.End(), "else") |
| if elseOffset < 0 { |
| panic("lost else") |
| } |
| f.edit.Insert(elseOffset+4, "{") |
| f.edit.Insert(f.offset(n.Else.End()), "}") |
|
|
| |
| |
| |
| |
| pos := f.fset.File(n.Body.End()).Pos(elseOffset + 4) |
| switch stmt := n.Else.(type) { |
| case *ast.IfStmt: |
| block := &ast.BlockStmt{ |
| Lbrace: pos, |
| List: []ast.Stmt{stmt}, |
| Rbrace: stmt.End(), |
| } |
| n.Else = block |
| case *ast.BlockStmt: |
| stmt.Lbrace = pos |
| default: |
| panic("unexpected node type in if") |
| } |
| ast.Walk(f, n.Else) |
| return nil |
| case *ast.SelectStmt: |
| |
| if n.Body == nil || len(n.Body.List) == 0 { |
| return nil |
| } |
| case *ast.SwitchStmt: |
| |
| if n.Body == nil || len(n.Body.List) == 0 { |
| if n.Init != nil { |
| ast.Walk(f, n.Init) |
| } |
| if n.Tag != nil { |
| ast.Walk(f, n.Tag) |
| } |
| return nil |
| } |
| case *ast.TypeSwitchStmt: |
| |
| if n.Body == nil || len(n.Body.List) == 0 { |
| if n.Init != nil { |
| ast.Walk(f, n.Init) |
| } |
| ast.Walk(f, n.Assign) |
| return nil |
| } |
| case *ast.FuncDecl: |
| |
| |
| if n.Name.Name == "_" || n.Body == nil { |
| return nil |
| } |
| fname := n.Name.Name |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| if atomicOnAtomic() && (fname == "AddUint32" || fname == "StoreUint32") { |
| return nil |
| } |
| |
| if r := n.Recv; r != nil && len(r.List) == 1 { |
| t := r.List[0].Type |
| star := "" |
| if p, _ := t.(*ast.StarExpr); p != nil { |
| t = p.X |
| star = "*" |
| } |
| if p, _ := t.(*ast.Ident); p != nil { |
| fname = star + p.Name + "." + fname |
| } |
| } |
| walkBody := true |
| if *pkgcfg != "" { |
| f.preFunc(n, fname) |
| if pkgconfig.Granularity == "perfunc" { |
| walkBody = false |
| } |
| } |
| if walkBody { |
| ast.Walk(f, n.Body) |
| } |
| if *pkgcfg != "" { |
| flit := false |
| f.postFunc(n, fname, flit, n.Body) |
| } |
| return nil |
| case *ast.FuncLit: |
| |
| |
| if f.fn.counterVar != "" { |
| return f |
| } |
|
|
| |
| |
| |
| pos := n.Pos() |
| p := f.fset.File(pos).Position(pos) |
| fname := fmt.Sprintf("func.L%d.C%d", p.Line, p.Column) |
| if *pkgcfg != "" { |
| f.preFunc(n, fname) |
| } |
| if pkgconfig.Granularity != "perfunc" { |
| ast.Walk(f, n.Body) |
| } |
| if *pkgcfg != "" { |
| flit := true |
| f.postFunc(n, fname, flit, n.Body) |
| } |
| return nil |
| } |
| return f |
| } |
|
|
| func mkCounterVarName(idx int) string { |
| return fmt.Sprintf("%s_%d", *varVar, idx) |
| } |
|
|
| func mkPackageIdVar() string { |
| return *varVar + "P" |
| } |
|
|
| func mkMetaVar() string { |
| return *varVar + "M" |
| } |
|
|
| func mkPackageIdExpression() string { |
| ppath := pkgconfig.PkgPath |
| if hcid := coverage.HardCodedPkgID(ppath); hcid != -1 { |
| return fmt.Sprintf("uint32(%d)", uint32(hcid)) |
| } |
| return mkPackageIdVar() |
| } |
|
|
| func (f *File) preFunc(fn ast.Node, fname string) { |
| f.fn.units = f.fn.units[:0] |
|
|
| |
| cv := mkCounterVarName(len(f.pkg.counterLengths)) |
| f.fn.counterVar = cv |
| } |
|
|
| func (f *File) postFunc(fn ast.Node, funcname string, flit bool, body *ast.BlockStmt) { |
|
|
| |
| singleCtr := "" |
| if pkgconfig.Granularity == "perfunc" { |
| singleCtr = "; " + f.newCounter(fn.Pos(), fn.Pos(), 1) |
| } |
|
|
| |
| nc := len(f.fn.units) + coverage.FirstCtrOffset |
| f.pkg.counterLengths = append(f.pkg.counterLengths, nc) |
|
|
| |
| |
| fnpos := f.fset.Position(fn.Pos()) |
| ppath := pkgconfig.PkgPath |
| filename := ppath + "/" + filepath.Base(fnpos.Filename) |
|
|
| |
| |
| |
| |
| |
| |
| if pkgconfig.Local { |
| filename = f.name |
| } |
|
|
| |
| fd := coverage.FuncDesc{ |
| Funcname: funcname, |
| Srcfile: filename, |
| Units: f.fn.units, |
| Lit: flit, |
| } |
| funcId := f.mdb.AddFunc(fd) |
|
|
| hookWrite := func(cv string, which int, val string) string { |
| return fmt.Sprintf("%s[%d] = %s", cv, which, val) |
| } |
| if *mode == "atomic" { |
| hookWrite = func(cv string, which int, val string) string { |
| return fmt.Sprintf("%sStoreUint32(&%s[%d], %s)", |
| atomicPackagePrefix(), cv, which, val) |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| cv := f.fn.counterVar |
| regHook := hookWrite(cv, 0, strconv.Itoa(len(f.fn.units))) + " ; " + |
| hookWrite(cv, 1, mkPackageIdExpression()) + " ; " + |
| hookWrite(cv, 2, strconv.Itoa(int(funcId))) + singleCtr |
|
|
| |
| |
| |
|
|
| boff := f.offset(body.Pos()) |
| ipos := f.fset.File(body.Pos()).Pos(boff) |
| ip := f.offset(ipos) |
| f.edit.Replace(ip, ip+1, string(f.content[ipos-1])+regHook+" ; ") |
|
|
| f.fn.counterVar = "" |
| } |
|
|
| func annotate(names []string) { |
| var p *Package |
| if *pkgcfg != "" { |
| pp := pkgconfig.PkgPath |
| pn := pkgconfig.PkgName |
| mp := pkgconfig.ModulePath |
| mdb, err := encodemeta.NewCoverageMetaDataBuilder(pp, pn, mp) |
| if err != nil { |
| log.Fatalf("creating coverage meta-data builder: %v\n", err) |
| } |
| p = &Package{ |
| mdb: mdb, |
| } |
| } |
| |
| for k, name := range names { |
| if strings.ContainsAny(name, "\r\n") { |
| |
| log.Fatalf("cover: input path contains newline character: %q", name) |
| } |
|
|
| fd := os.Stdout |
| isStdout := true |
| if *pkgcfg != "" { |
| var err error |
| fd, err = os.Create(outputfiles[k]) |
| if err != nil { |
| log.Fatalf("cover: %s", err) |
| } |
| isStdout = false |
| } else if *output != "" { |
| var err error |
| fd, err = os.Create(*output) |
| if err != nil { |
| log.Fatalf("cover: %s", err) |
| } |
| isStdout = false |
| } |
| p.annotateFile(name, fd) |
| if !isStdout { |
| if err := fd.Close(); err != nil { |
| log.Fatalf("cover: %s", err) |
| } |
| } |
| } |
|
|
| if *pkgcfg != "" { |
| fd, err := os.Create(covervarsoutfile) |
| if err != nil { |
| log.Fatalf("cover: %s", err) |
| } |
| p.emitMetaData(fd) |
| if err := fd.Close(); err != nil { |
| log.Fatalf("cover: %s", err) |
| } |
| } |
| } |
|
|
| func (p *Package) annotateFile(name string, fd io.Writer) { |
| fset := token.NewFileSet() |
| content, err := os.ReadFile(name) |
| if err != nil { |
| log.Fatalf("cover: %s: %s", name, err) |
| } |
| parsedFile, err := parser.ParseFile(fset, name, content, parser.ParseComments) |
| if err != nil { |
| log.Fatalf("cover: %s: %s", name, err) |
| } |
|
|
| file := &File{ |
| fset: fset, |
| name: name, |
| content: content, |
| edit: edit.NewBuffer(content), |
| astFile: parsedFile, |
| } |
| if p != nil { |
| file.mdb = p.mdb |
| file.pkg = p |
| } |
|
|
| if *mode == "atomic" { |
| |
| |
| |
| |
| |
| |
| |
| if pkgconfig.PkgPath != "sync/atomic" { |
| file.edit.Insert(file.offset(file.astFile.Name.End()), |
| fmt.Sprintf("; import %s %q", atomicPackageName, atomicPackagePath)) |
| } |
| } |
| if pkgconfig.PkgName == "main" { |
| file.edit.Insert(file.offset(file.astFile.Name.End()), |
| "; import _ \"runtime/coverage\"") |
| } |
|
|
| if counterStmt != nil { |
| ast.Walk(file, file.astFile) |
| } |
| newContent := file.edit.Bytes() |
|
|
| if strings.ContainsAny(name, "\r\n") { |
| |
| |
| panic(fmt.Sprintf("annotateFile: name contains unexpected newline character: %q", name)) |
| } |
| fmt.Fprintf(fd, "//line %s:1:1\n", name) |
| fd.Write(newContent) |
|
|
| |
| |
| |
| file.addVariables(fd) |
|
|
| |
| |
| if *mode == "atomic" { |
| fmt.Fprintf(fd, "\nvar _ = %sLoadUint32\n", atomicPackagePrefix()) |
| } |
| } |
|
|
| |
| func setCounterStmt(f *File, counter string) string { |
| return fmt.Sprintf("%s = 1", counter) |
| } |
|
|
| |
| func incCounterStmt(f *File, counter string) string { |
| return fmt.Sprintf("%s++", counter) |
| } |
|
|
| |
| func atomicCounterStmt(f *File, counter string) string { |
| return fmt.Sprintf("%sAddUint32(&%s, 1)", atomicPackagePrefix(), counter) |
| } |
|
|
| |
| func (f *File) newCounter(start, end token.Pos, numStmt int) string { |
| var stmt string |
| if *pkgcfg != "" { |
| slot := len(f.fn.units) + coverage.FirstCtrOffset |
| if f.fn.counterVar == "" { |
| panic("internal error: counter var unset") |
| } |
| stmt = counterStmt(f, fmt.Sprintf("%s[%d]", f.fn.counterVar, slot)) |
| stpos := f.fset.Position(start) |
| enpos := f.fset.Position(end) |
| stpos, enpos = dedup(stpos, enpos) |
| unit := coverage.CoverableUnit{ |
| StLine: uint32(stpos.Line), |
| StCol: uint32(stpos.Column), |
| EnLine: uint32(enpos.Line), |
| EnCol: uint32(enpos.Column), |
| NxStmts: uint32(numStmt), |
| } |
| f.fn.units = append(f.fn.units, unit) |
| } else { |
| stmt = counterStmt(f, fmt.Sprintf("%s.Count[%d]", *varVar, |
| len(f.blocks))) |
| f.blocks = append(f.blocks, Block{start, end, numStmt}) |
| } |
| return stmt |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| func (f *File) addCounters(pos, insertPos, blockEnd token.Pos, list []ast.Stmt, extendToClosingBrace bool) { |
| |
| |
| if len(list) == 0 { |
| f.edit.Insert(f.offset(insertPos), f.newCounter(insertPos, blockEnd, 0)+";") |
| return |
| } |
| |
| |
| list = append([]ast.Stmt(nil), list...) |
| |
| |
| for { |
| |
| |
| var last int |
| end := blockEnd |
| for last = 0; last < len(list); last++ { |
| stmt := list[last] |
| end = f.statementBoundary(stmt) |
| if f.endsBasicSourceBlock(stmt) { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| if label, isLabel := stmt.(*ast.LabeledStmt); isLabel && !f.isControl(label.Stmt) { |
| newLabel := *label |
| newLabel.Stmt = &ast.EmptyStmt{ |
| Semicolon: label.Stmt.Pos(), |
| Implicit: true, |
| } |
| end = label.Pos() |
| list[last] = &newLabel |
| |
| list = append(list, nil) |
| copy(list[last+1:], list[last:]) |
| list[last+1] = label.Stmt |
| } |
| last++ |
| extendToClosingBrace = false |
| break |
| } |
| } |
| if extendToClosingBrace { |
| end = blockEnd |
| } |
| if pos != end { |
| f.edit.Insert(f.offset(insertPos), f.newCounter(pos, end, last)+";") |
| } |
| list = list[last:] |
| if len(list) == 0 { |
| break |
| } |
| pos = list[0].Pos() |
| insertPos = pos |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| func hasFuncLiteral(n ast.Node) (bool, token.Pos) { |
| if n == nil { |
| return false, 0 |
| } |
| var literal funcLitFinder |
| ast.Walk(&literal, n) |
| return literal.found(), token.Pos(literal) |
| } |
|
|
| |
| |
| func (f *File) statementBoundary(s ast.Stmt) token.Pos { |
| |
| switch s := s.(type) { |
| case *ast.BlockStmt: |
| |
| return s.Lbrace |
| case *ast.IfStmt: |
| found, pos := hasFuncLiteral(s.Init) |
| if found { |
| return pos |
| } |
| found, pos = hasFuncLiteral(s.Cond) |
| if found { |
| return pos |
| } |
| return s.Body.Lbrace |
| case *ast.ForStmt: |
| found, pos := hasFuncLiteral(s.Init) |
| if found { |
| return pos |
| } |
| found, pos = hasFuncLiteral(s.Cond) |
| if found { |
| return pos |
| } |
| found, pos = hasFuncLiteral(s.Post) |
| if found { |
| return pos |
| } |
| return s.Body.Lbrace |
| case *ast.LabeledStmt: |
| return f.statementBoundary(s.Stmt) |
| case *ast.RangeStmt: |
| found, pos := hasFuncLiteral(s.X) |
| if found { |
| return pos |
| } |
| return s.Body.Lbrace |
| case *ast.SwitchStmt: |
| found, pos := hasFuncLiteral(s.Init) |
| if found { |
| return pos |
| } |
| found, pos = hasFuncLiteral(s.Tag) |
| if found { |
| return pos |
| } |
| return s.Body.Lbrace |
| case *ast.SelectStmt: |
| return s.Body.Lbrace |
| case *ast.TypeSwitchStmt: |
| found, pos := hasFuncLiteral(s.Init) |
| if found { |
| return pos |
| } |
| return s.Body.Lbrace |
| } |
| |
| |
| |
| |
| found, pos := hasFuncLiteral(s) |
| if found { |
| return pos |
| } |
| return s.End() |
| } |
|
|
| |
| |
| |
| func (f *File) endsBasicSourceBlock(s ast.Stmt) bool { |
| switch s := s.(type) { |
| case *ast.BlockStmt: |
| |
| return true |
| case *ast.BranchStmt: |
| return true |
| case *ast.ForStmt: |
| return true |
| case *ast.IfStmt: |
| return true |
| case *ast.LabeledStmt: |
| return true |
| case *ast.RangeStmt: |
| return true |
| case *ast.SwitchStmt: |
| return true |
| case *ast.SelectStmt: |
| return true |
| case *ast.TypeSwitchStmt: |
| return true |
| case *ast.ExprStmt: |
| |
| |
| |
| |
| if call, ok := s.X.(*ast.CallExpr); ok { |
| if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "panic" && len(call.Args) == 1 { |
| return true |
| } |
| } |
| } |
| found, _ := hasFuncLiteral(s) |
| return found |
| } |
|
|
| |
| |
| func (f *File) isControl(s ast.Stmt) bool { |
| switch s.(type) { |
| case *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt, *ast.TypeSwitchStmt: |
| return true |
| } |
| return false |
| } |
|
|
| |
| |
| type funcLitFinder token.Pos |
|
|
| func (f *funcLitFinder) Visit(node ast.Node) (w ast.Visitor) { |
| if f.found() { |
| return nil |
| } |
| switch n := node.(type) { |
| case *ast.FuncLit: |
| *f = funcLitFinder(n.Body.Lbrace) |
| return nil |
| } |
| return f |
| } |
|
|
| func (f *funcLitFinder) found() bool { |
| return token.Pos(*f) != token.NoPos |
| } |
|
|
| |
|
|
| type block1 struct { |
| Block |
| index int |
| } |
|
|
| |
| func (f *File) offset(pos token.Pos) int { |
| return f.fset.Position(pos).Offset |
| } |
|
|
| |
| func (f *File) addVariables(w io.Writer) { |
| if *pkgcfg != "" { |
| return |
| } |
| |
| t := make([]block1, len(f.blocks)) |
| for i := range f.blocks { |
| t[i].Block = f.blocks[i] |
| t[i].index = i |
| } |
| slices.SortFunc(t, func(a, b block1) int { |
| return cmp.Compare(a.startByte, b.startByte) |
| }) |
| for i := 1; i < len(t); i++ { |
| if t[i-1].endByte > t[i].startByte { |
| fmt.Fprintf(os.Stderr, "cover: internal error: block %d overlaps block %d\n", t[i-1].index, t[i].index) |
| |
| fmt.Fprintf(os.Stderr, "\t%s:#%d,#%d %s:#%d,#%d\n", |
| f.name, f.offset(t[i-1].startByte), f.offset(t[i-1].endByte), |
| f.name, f.offset(t[i].startByte), f.offset(t[i].endByte)) |
| } |
| } |
|
|
| |
| fmt.Fprintf(w, "\nvar %s = struct {\n", *varVar) |
| fmt.Fprintf(w, "\tCount [%d]uint32\n", len(f.blocks)) |
| fmt.Fprintf(w, "\tPos [3 * %d]uint32\n", len(f.blocks)) |
| fmt.Fprintf(w, "\tNumStmt [%d]uint16\n", len(f.blocks)) |
| fmt.Fprintf(w, "} {\n") |
|
|
| |
| fmt.Fprintf(w, "\tPos: [3 * %d]uint32{\n", len(f.blocks)) |
|
|
| |
| |
| |
| |
| for i, block := range f.blocks { |
| start := f.fset.Position(block.startByte) |
| end := f.fset.Position(block.endByte) |
|
|
| start, end = dedup(start, end) |
|
|
| fmt.Fprintf(w, "\t\t%d, %d, %#x, // [%d]\n", start.Line, end.Line, (end.Column&0xFFFF)<<16|(start.Column&0xFFFF), i) |
| } |
|
|
| |
| fmt.Fprintf(w, "\t},\n") |
|
|
| |
| fmt.Fprintf(w, "\tNumStmt: [%d]uint16{\n", len(f.blocks)) |
|
|
| |
| |
| |
| for i, block := range f.blocks { |
| n := block.numStmt |
| if n > 1<<16-1 { |
| n = 1<<16 - 1 |
| } |
| fmt.Fprintf(w, "\t\t%d, // %d\n", n, i) |
| } |
|
|
| |
| fmt.Fprintf(w, "\t},\n") |
|
|
| |
| fmt.Fprintf(w, "}\n") |
| } |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| type pos2 struct { |
| p1, p2 token.Position |
| } |
|
|
| |
| var seenPos2 = make(map[pos2]bool) |
|
|
| |
| |
| |
| func dedup(p1, p2 token.Position) (r1, r2 token.Position) { |
| key := pos2{ |
| p1: p1, |
| p2: p2, |
| } |
|
|
| |
| |
| key.p1.Offset = 0 |
| key.p2.Offset = 0 |
|
|
| for seenPos2[key] { |
| key.p2.Column++ |
| } |
| seenPos2[key] = true |
|
|
| return key.p1, key.p2 |
| } |
|
|
| func (p *Package) emitMetaData(w io.Writer) { |
| if *pkgcfg == "" { |
| return |
| } |
|
|
| |
| |
| |
| |
| if pkgconfig.EmitMetaFile != "" { |
| p.emitMetaFile(pkgconfig.EmitMetaFile) |
| } |
|
|
| |
| |
| if counterStmt == nil && len(p.counterLengths) != 0 { |
| panic("internal error: seen functions with regonly/testmain") |
| } |
|
|
| |
| fmt.Fprintf(w, "\npackage %s\n\n", pkgconfig.PkgName) |
|
|
| |
| fmt.Fprintf(w, "\nvar %sP uint32\n", *varVar) |
|
|
| |
| for k := range p.counterLengths { |
| cvn := mkCounterVarName(k) |
| fmt.Fprintf(w, "var %s [%d]uint32\n", cvn, p.counterLengths[k]) |
| } |
|
|
| |
| var sws slicewriter.WriteSeeker |
| digest, err := p.mdb.Emit(&sws) |
| if err != nil { |
| log.Fatalf("encoding meta-data: %v", err) |
| } |
| p.mdb = nil |
| fmt.Fprintf(w, "var %s = [...]byte{\n", mkMetaVar()) |
| payload := sws.BytesWritten() |
| for k, b := range payload { |
| fmt.Fprintf(w, " 0x%x,", b) |
| if k != 0 && k%8 == 0 { |
| fmt.Fprintf(w, "\n") |
| } |
| } |
| fmt.Fprintf(w, "}\n") |
|
|
| fixcfg := covcmd.CoverFixupConfig{ |
| Strategy: "normal", |
| MetaVar: mkMetaVar(), |
| MetaLen: len(payload), |
| MetaHash: fmt.Sprintf("%x", digest), |
| PkgIdVar: mkPackageIdVar(), |
| CounterPrefix: *varVar, |
| CounterGranularity: pkgconfig.Granularity, |
| CounterMode: *mode, |
| } |
| fixdata, err := json.Marshal(fixcfg) |
| if err != nil { |
| log.Fatalf("marshal fixupcfg: %v", err) |
| } |
| if err := os.WriteFile(pkgconfig.OutConfig, fixdata, 0666); err != nil { |
| log.Fatalf("error writing %s: %v", pkgconfig.OutConfig, err) |
| } |
| } |
|
|
| |
| |
| func atomicOnAtomic() bool { |
| return *mode == "atomic" && pkgconfig.PkgPath == "sync/atomic" |
| } |
|
|
| |
| |
| |
| |
| func atomicPackagePrefix() string { |
| if atomicOnAtomic() { |
| return "" |
| } |
| return atomicPackageName + "." |
| } |
|
|
| func (p *Package) emitMetaFile(outpath string) { |
| |
| of, err := os.OpenFile(outpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) |
| if err != nil { |
| log.Fatalf("opening covmeta %s: %v", outpath, err) |
| } |
|
|
| if len(p.counterLengths) == 0 { |
| |
| |
| |
| if err = of.Close(); err != nil { |
| log.Fatalf("closing meta-data file: %v", err) |
| } |
| return |
| } |
|
|
| |
| var sws slicewriter.WriteSeeker |
| digest, err := p.mdb.Emit(&sws) |
| if err != nil { |
| log.Fatalf("encoding meta-data: %v", err) |
| } |
| payload := sws.BytesWritten() |
| blobs := [][]byte{payload} |
|
|
| |
| mfw := encodemeta.NewCoverageMetaFileWriter(outpath, of) |
| err = mfw.Write(digest, blobs, cmode, cgran) |
| if err != nil { |
| log.Fatalf("writing meta-data file: %v", err) |
| } |
| if err = of.Close(); err != nil { |
| log.Fatalf("closing meta-data file: %v", err) |
| } |
| } |
|
|