diff --git a/README.md b/README.md index 0babeff..a8f98e5 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,27 @@ A Parser for PHP written in Go inspired by [Nikic PHP Parser](https://github.com - Abstract syntax tree representation - Traversing AST +## Example +```Golang +package main + +import ( + "bytes" + + "github.com/z7zmey/php-parser/parser" + "github.com/z7zmey/php-parser/visitor" +) + +func main() { + src := ` 0 { - fmt.Printf(" %v", a) - } - fmt.Println() - - if c := d.comments[n]; len(c) > 0 { - fmt.Printf("%vcomments:\n", d.indent+" ") - for _, cc := range c { - fmt.Printf("%v%q\n", d.indent+" ", cc) - } - } - - return true -} - -func (d dumper) GetChildrenVisitor(key string) node.Visitor { - fmt.Printf("%v%q:\n", d.indent+" ", key) - return dumper{d.indent + " ", d.comments, d.positions} -} - -func (d dumper) LeaveNode(n node.Node) { - // do nothing -} diff --git a/main.go b/main.go index 55105a0..6e8e63a 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "github.com/yookoala/realpath" "github.com/z7zmey/php-parser/parser" + "github.com/z7zmey/php-parser/visitor" ) func main() { @@ -25,7 +26,11 @@ func main() { src, _ := os.Open(string(path)) nodes, comments, positions := parser.Parse(src, path) - visitor := dumper{" | ", comments, positions} + visitor := visitor.Dumper{ + Indent: " | ", + Comments: comments, + Positions: positions, + } nodes.Walk(visitor) } return nil diff --git a/visitor/dumper.go b/visitor/dumper.go new file mode 100644 index 0000000..1c81122 --- /dev/null +++ b/visitor/dumper.go @@ -0,0 +1,47 @@ +package visitor + +import ( + "fmt" + "reflect" + + "github.com/z7zmey/php-parser/position" + + "github.com/z7zmey/php-parser/comment" + "github.com/z7zmey/php-parser/node" +) + +type Dumper struct { + Indent string + Comments comment.Comments + Positions position.Positions +} + +func (d Dumper) EnterNode(n node.Node) bool { + + fmt.Printf("%v%v", d.Indent, reflect.TypeOf(n)) + if p := d.Positions[n]; p != nil { + fmt.Printf(" %v", *p) + } + if a := n.Attributes(); len(a) > 0 { + fmt.Printf(" %v", a) + } + fmt.Println() + + if c := d.Comments[n]; len(c) > 0 { + fmt.Printf("%vComments:\n", d.Indent+" ") + for _, cc := range c { + fmt.Printf("%v%q\n", d.Indent+" ", cc) + } + } + + return true +} + +func (d Dumper) GetChildrenVisitor(key string) node.Visitor { + fmt.Printf("%v%q:\n", d.Indent+" ", key) + return Dumper{d.Indent + " ", d.Comments, d.Positions} +} + +func (d Dumper) LeaveNode(n node.Node) { + // do nothing +}