move dumper to visitor package

This commit is contained in:
z7zmey 2018-01-12 10:04:31 +02:00
parent c5e1b29f0f
commit 538cf34777
4 changed files with 74 additions and 48 deletions

View File

@ -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 := `<? echo "Hello world";`
nodes, comments, positions := parser.Parse(bytes.NewBufferString(src), "example.php")
visitor := visitor.Dumper{" | ", comments, positions}
nodes.Walk(visitor)
}
```
## Roadmap
- [X] Lexer
- [x] PHP 7 syntax analyzer (completely)

View File

@ -1,47 +0,0 @@
package main
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
}

View File

@ -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

47
visitor/dumper.go Normal file
View File

@ -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
}