php-parser/visitor/dumper.go

70 lines
1.7 KiB
Go
Raw Normal View History

2018-02-20 18:22:15 +00:00
// Package visitor contains walker.visitor implementations
package visitor
2018-01-12 08:04:31 +00:00
import (
"fmt"
"reflect"
2018-01-17 16:58:45 +00:00
"github.com/z7zmey/php-parser/node"
2018-01-12 08:04:31 +00:00
"github.com/z7zmey/php-parser/position"
"github.com/z7zmey/php-parser/comment"
2018-01-17 16:58:45 +00:00
"github.com/z7zmey/php-parser/walker"
2018-01-12 08:04:31 +00:00
)
2018-01-12 08:16:09 +00:00
// Dumper prints ast hierarchy to stdout
// Also prints comments and positions attached to nodes
2018-01-12 08:04:31 +00:00
type Dumper struct {
2018-03-01 20:31:36 +00:00
Indent string
Comments comment.Comments
Positions position.Positions
NsResolver *NamespaceResolver
2018-01-12 08:04:31 +00:00
}
2018-01-12 08:16:09 +00:00
// EnterNode is invoked at every node in heirerchy
2018-02-20 17:52:07 +00:00
func (d Dumper) EnterNode(w walker.Walkable) bool {
2018-01-17 16:58:45 +00:00
n := w.(node.Node)
2018-01-12 08:04:31 +00:00
2018-03-01 20:31:36 +00:00
fmt.Printf("%v[%v]\n", d.Indent, reflect.TypeOf(n))
if d.Positions != nil {
if p := d.Positions[n]; p != nil {
fmt.Printf("%v\"Position\": %s;\n", d.Indent+" ", *p)
}
2018-01-12 08:04:31 +00:00
}
2018-03-01 20:31:36 +00:00
if d.NsResolver != nil {
if namespacedName, ok := d.NsResolver.ResolvedNames[n]; ok {
fmt.Printf("%v\"NamespacedName\": %s;\n", d.Indent+" ", namespacedName)
}
2018-01-12 08:04:31 +00:00
}
2018-03-01 20:31:36 +00:00
if d.Comments != nil {
if c := d.Comments[n]; len(c) > 0 {
fmt.Printf("%v\"Comments\":\n", d.Indent+" ")
for _, cc := range c {
fmt.Printf("%v%q\n", d.Indent+" ", cc)
}
}
}
if a := n.Attributes(); len(a) > 0 {
for key, attr := range a {
fmt.Printf("%v\"%v\": %v;\n", d.Indent+" ", key, attr)
2018-01-12 08:04:31 +00:00
}
}
return true
}
2018-01-12 08:16:09 +00:00
// GetChildrenVisitor is invoked at every node parameter that contains children nodes
2018-01-17 16:58:45 +00:00
func (d Dumper) GetChildrenVisitor(key string) walker.Visitor {
2018-01-12 08:04:31 +00:00
fmt.Printf("%v%q:\n", d.Indent+" ", key)
2018-03-01 20:31:36 +00:00
return Dumper{d.Indent + " ", d.Comments, d.Positions, d.NsResolver}
2018-01-12 08:04:31 +00:00
}
2018-01-12 08:16:09 +00:00
// LeaveNode is invoked after node process
2018-02-20 17:52:07 +00:00
func (d Dumper) LeaveNode(n walker.Walkable) {
2018-01-12 08:04:31 +00:00
// do nothing
}