Documentation ¶
Overview ¶
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 ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CFG ¶
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.
Example ¶
package main import ( "fmt" "go/ast" "go/parser" "go/token" "github.com/godoctor/godoctor/analysis/cfg" ) func main() { 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 ¶
FromFunc is a convenience function for creating a CFG from a given function declaration.
func (*CFG) Blocks ¶
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 ¶
Preds returns a slice of all immediate predecessors for the given statement. May include Entry node.