neugram / ng

scripting language integrated with Go
https://neugram.io
BSD 2-Clause "Simplified" License
916 stars 43 forks source link

ng/stmt,ng/expr: introduce a Walk function #93

Open sbinet opened 6 years ago

sbinet commented 6 years ago

to fix neugram/ng#92 I think we'd need some kind of a visitor for stmt.Stmt, expr.Expr, etc...

the go/ast has ast.Walk:

$> go doc go/ast.Walk
func Walk(v Visitor, node Node)
    Walk traverses an AST in depth-first order: It starts by calling
    v.Visit(node); node must not be nil. If the visitor w returned by
    v.Visit(node) is not nil, Walk is invoked recursively with visitor w for
    each of the non-nil children of node, followed by a call of w.Visit(nil).

$> go doc go/ast.Visitor
type Visitor interface {
    Visit(node Node) (w Visitor)
}
    A Visitor's Visit method is invoked for each node encountered by Walk. If
    the result visitor w is not nil, Walk visits each of the children of node
    with the visitor w, followed by a call of w.Visit(nil).

$> go doc go/ast.Node
type Node interface {
    Pos() token.Pos // position of first character belonging to the node
    End() token.Pos // position of first character immediately after the node
}
    All node types implement the Node interface.

what do you think?

crawshaw commented 6 years ago

I wonder if we could jump straight to an Apply interface. Something like the fallthrough detection doesn't actually need to modify the AST, but Apply can be used without making any changes. (And it would be super-simple to build a Walk on top of it.)

https://go-review.googlesource.com/c/tools/+/77811/4/go/ast/astutil/rewrite.go

We will need a generic Node interface. Right now there's no position information to expose by it (this is a long-standing TODO I keep not getting to). I'll file a separate issue about that.

sbinet commented 6 years ago

Apply sounds good to me.

crawshaw commented 6 years ago

I need this for #5, so I'm going to take a look at it. (Though I'm back at work for a week, so it may have to wait until next weekend.)