move MutatingWalker to new subpackage, exhaustively implement all cases

This commit is contained in:
mappu 2020-04-12 14:42:01 +12:00
parent 78bd54ad13
commit 739db2c444
5 changed files with 1105 additions and 58 deletions

11
main.go
View File

@ -10,6 +10,8 @@ import (
"github.com/z7zmey/php-parser/parser"
"github.com/z7zmey/php-parser/visitor"
"php2go/parseutil"
)
func ConvertFile(filename string) (string, error) {
@ -48,7 +50,14 @@ func ConvertFile(filename string) (string, error) {
}
// Pass 1: Normalise Alt** Stmt types
walkMutate(&n, normaliseAltCb)
normaliser := parseutil.MutatingWalker{
EnterNode: normaliseAltCb,
LeaveNode: parseutil.MutatingWalkerNoop,
}
err = normaliser.Walk(&n)
if err != nil {
return "", err
}
// Debug pass: Walk and print JSON...
if fh, err := os.OpenFile(filename+`.parse2.json`, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644); err == nil {

View File

@ -1,54 +0,0 @@
package main
import (
// "fmt"
//"io/ioutil"
"github.com/z7zmey/php-parser/node"
"github.com/z7zmey/php-parser/node/stmt"
//"github.com/z7zmey/php-parser/walker"
)
func walkMutate(n_ *node.Node, cb func(*node.Node)) {
// Mutate in-place, non recursive...
cb(n_)
// Walk on the mutated version
// We must reimplement .Walk() in order to get pointer behaviour
switch n := (*n_).(type) {
case *stmt.StmtList:
for i, _ := range n.Stmts {
walkMutate(&n.Stmts[i], cb)
}
case *node.Root:
for i, _ := range n.Stmts {
walkMutate(&n.Stmts[i], cb)
}
case *stmt.If:
walkMutate(&n.Cond, cb)
walkMutate(&n.Else, cb)
for i, _ := range n.ElseIf {
walkMutate(&n.ElseIf[i], cb)
}
walkMutate(&n.Stmt, cb)
case *stmt.Else:
walkMutate(&n.Stmt, cb)
case *stmt.ElseIf:
walkMutate(&n.Cond, cb)
walkMutate(&n.Stmt, cb)
default:
// FIXME need to implement Walk() for all node types, to ensure that
// we can perform mutation transforms in nested contexts
// bail
//panic(fmt.Sprintf("walkMutate: unimplemented type '%t'", n))
}
}

View File

@ -9,7 +9,7 @@ import (
//"github.com/z7zmey/php-parser/walker"
)
func normaliseAltCb(n_ *node.Node) {
func normaliseAltCb(n_ *node.Node) error {
switch n := (*n_).(type) {
case *stmt.AltIf:
@ -36,6 +36,8 @@ func normaliseAltCb(n_ *node.Node) {
*n_ = elifStmt
default:
return // no change
// no change
}
return nil // always
}

View File

@ -1,4 +1,4 @@
package main
package parseutil
import (
"fmt"
@ -215,6 +215,10 @@ type Exhaustive interface {
func switchExhaustive(e Exhaustive, n_ *node.Node) error {
n := *n_ // no copy
if n == nil {
return nil // inner handlers expect a non-nil pointer
}
switch n := n.(type) {
// node

1086
parseutil/MutatingWalker.go Normal file

File diff suppressed because it is too large Load Diff