cfg

package
Version: v0.0.0-...-8433dcb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2020 License: BSD-3-Clause Imports: 7 Imported by: 3

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

func FromFunc(f *ast.FuncDecl) *CFG

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

func FromStmts

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

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

func (*CFG) Blocks

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

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

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

func (*CFG) Sort

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

func (*CFG) Succs

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.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL