astrewrite

package module
v0.0.0-...-9094e54 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2019 License: MIT Imports: 2 Imported by: 14

README

This project is archived and not maintained. There is a better implementation and solution in the golang.org/x/tools/go/ast/astutil package that you can use.

astrewrite GoDoc Build Status

astrewrite provides a Walk() function, similar to ast.Inspect() from the ast package. The only difference is that the passed walk function can also return a node, which is used to rewrite the parent node. This provides an easy way to rewrite a given ast.Node while walking the AST.

Example

package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"

	"github.com/fatih/astrewrite"
)

func main() {
	src := `package main

type Foo struct{}`

	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "foo.go", src, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	rewriteFunc := func(n ast.Node) (ast.Node, bool) {
		x, ok := n.(*ast.TypeSpec)
		if !ok {
			return n, true
		}

		// change struct type name to "Bar"
		x.Name.Name = "Bar"
		return x, true
	}

	rewritten := astrewrite.Walk(file, rewriteFunc)

	var buf bytes.Buffer
	printer.Fprint(&buf, fset, rewritten)
	fmt.Println(buf.String())
	// Output:
	// package main
	//
	// type Bar struct{}
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Walk

func Walk(node ast.Node, fn WalkFunc) ast.Node

Walk traverses an AST in depth-first order: It starts by calling fn(node); node must not be nil. It returns the rewritten node. If fn returns true, Walk invokes fn recursively for each of the non-nil children of node, followed by a call of fn(nil). The returned node of fn can be used to rewrite the passed node to fn. Panics if the returned type is not the same type as the original one.

Example
src := `package main

type Foo struct{}`

fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "foo.go", src, parser.ParseComments)
if err != nil {
	panic(err)
}

rewriteFunc := func(n ast.Node) (ast.Node, bool) {
	x, ok := n.(*ast.TypeSpec)
	if !ok {
		return n, true
	}

	// change struct type name to "Bar"
	x.Name.Name = "Bar"
	return x, true
}

rewritten := Walk(file, rewriteFunc)

var buf bytes.Buffer
printer.Fprint(&buf, fset, rewritten)
fmt.Println(buf.String())
Output:

package main

type Bar struct{}

Types

type WalkFunc

type WalkFunc func(ast.Node) (ast.Node, bool)

WalkFunc describes a function to be called for each node during a Walk. The returned node can be used to rewrite the AST. Walking stops if the returned bool is false.

Jump to

Keyboard shortcuts

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