godoctor: github.com/godoctor/godoctor/analysis/cfg Index | Examples | Files

package cfg

import "github.com/godoctor/godoctor/analysis/cfg"

Package cfg provides intraprocedural control flow graphs (CFGs) with statement-level granularity, i.e., CFGs whose nodes correspond 1-1 to the Stmt nodes from an abstract syntax tree.

Index

Examples

Package Files

cfg.go

type CFG Uses

type CFG struct {
    // Sentinel nodes for single-entry, single-exit CFG. Not in original AST.
    Entry, Exit *ast.BadStmt
    // All defers found in CFG, disjoint from blocks. May be flowed to after Exit.
    Defers []*ast.DeferStmt
    // contains filtered or unexported fields
}

CFG defines a control flow graph with statement-level granularity, in which there is a 1-1 correspondence between a block in the CFG and an ast.Stmt.

Code:

src := `
package main

import "fmt"

func main() {
  for {
    if 1 > 0 {
      fmt.Println("my computer works")
    } else {
      fmt.Println("something has gone terribly wrong")
    }
  }
}
  `

fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", src, 0)
if err != nil {
    fmt.Println(err)
    return
}

funcOne := f.Decls[1].(*ast.FuncDecl)
c := cfg.FromFunc(funcOne)
_ = c.Blocks() // for 100% coverage ;)

ast.Inspect(f, func(n ast.Node) bool {
    switch stmt := n.(type) {
    case *ast.IfStmt:
        s := c.Succs(stmt)
        p := c.Preds(stmt)

        fmt.Println(len(s))
        fmt.Println(len(p))
    }
    return true
})

Output:

2
1

func FromFunc Uses

func FromFunc(f *ast.FuncDecl) *CFG

FromFunc is a convenience function for creating a CFG from a given function declaration.

func FromStmts Uses

func FromStmts(s []ast.Stmt) *CFG

FromStmts returns the control-flow graph for the given sequence of statements.

func (*CFG) Blocks Uses

func (c *CFG) Blocks() []ast.Stmt

Blocks returns a slice of all blocks in a CFG, including the Entry and Exit nodes. The blocks are roughly in the order they appear in the source code.

func (*CFG) Preds Uses

func (c *CFG) Preds(s ast.Stmt) []ast.Stmt

Preds returns a slice of all immediate predecessors for the given statement. May include Entry node.

func (*CFG) PrintDot Uses

func (c *CFG) PrintDot(f io.Writer, fset *token.FileSet, addl func(n ast.Stmt) string)

func (*CFG) Sort Uses

func (c *CFG) Sort(stmts []ast.Stmt)

func (*CFG) Succs Uses

func (c *CFG) Succs(s ast.Stmt) []ast.Stmt

Succs returns a slice of all immediate successors to the given statement. May include Exit node.

Package cfg imports 7 packages (graph) and is imported by 4 packages. Updated 2018-05-06. Refresh now. Tools for package owners.