controlflow

package module
v0.0.0-...-b4e3b08 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2017 License: MIT Imports: 5 Imported by: 0

README

A package to remove goto statements from a Go syntax tree by rewriting them as conditionals and loops.

Build Status

This is an ongoing project and is incomplete. Please experiment with it but don't rely on it.

Documentation and examples

controlflow documentation

References

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ElimGotos

func ElimGotos(stmts []ast.Stmt) []ast.Stmt

ElimGotos removes any goto statements from stmts by rewriting them as conditionals and loops. A transformed syntax tree is returned; stmts is not modified.

Example
code := `
package branchy
func isGoodNumber(x int) bool {

	if x%3 == 0 {
		goto fail
	} else if x%5 == 0 {
		goto fail
	}
    return true
fail:
	return false	
}
`

// Parse the code
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "code.go", code, 0)
if err != nil {
	panic(err)
}

// List of statements in the function's body
body := file.Decls[0].(*ast.FuncDecl).Body.List

// Rewrite the function body without goto statements
newBody := ElimGotos(body)

// Print the result
config := printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}
config.Fprint(os.Stdout, token.NewFileSet(), newBody)
Output:

gotofail := false
if x%3 == 0 {
    gotofail = true
} else {
    gotofail = x%5 == 0
}
if !gotofail {
    return true
}
return false

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL