Skip to content

Package rewrite can rewrite a Go AST node given a rewriter function

Notifications You must be signed in to change notification settings

rajbarik/ast-rewrite

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Package rewrite

GoDoc

Package rewrite can recursively rewrite a Go AST given a rewriter function.

The following example splits an asignment x, y := 0, 1 to two assignments x := 0 and y := 1

src := "func() { x, y := 0, 1 }"
node, err := parser.ParseExpr(src)
if err != nil {
	panic(err)
}

node = rewrite.Rewrite(node, func(node ast.Node) (ast.Node, bool) {
	if assign, ok := node.(*AssignStmt); ok {
		if len(assign.Lhs) > 1 && assign.Tok == token.DEFINE {
			var block rewrite.ExpandedBlockStmt
			for i := range assign.Lhs {
				block.List = append(block.List, &AssignStmt{
					Lhs: []Expr{assign.Lhs[i]},
					Tok: token.DEFINE,
					Rhs: []Expr{assign.Rhs[i]},
				})
			}
			node = &block
		}
	}
	return node, true
}).(Expr)

format.Node(os.Stdout, token.NewFileSet(), node)

Output:

func() {
 	x := 0
 	y := 1
}

About

Package rewrite can rewrite a Go AST node given a rewriter function

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 100.0%