php-parser/pkg/visitor/traverser/traverser_test.go
Laytan Laats 25877adda4 feat: add enter and leave checks for traversers
- Improved performance (can short circuit/not continue when done)
- Backwards compatible because added interfaces
- Now generating the implementation for easier updates
2023-03-25 22:03:02 +01:00

68 lines
1.3 KiB
Go

package traverser_test
import (
"testing"
"github.com/VKCOM/php-parser/pkg/ast"
"github.com/VKCOM/php-parser/pkg/visitor"
"github.com/VKCOM/php-parser/pkg/visitor/traverser"
)
// testCase is a traverser that does not go into any class statement or its children.
// If it does, the test fails.
type testCase struct {
t *testing.T
visitor.Null
traversedFunction bool
}
var _ ast.Visitor = &testCase{}
func (t *testCase) EnterNode(n ast.Vertex) bool {
t.t.Logf("EnterNode: %T", n)
if _, ok := n.(*ast.StmtClass); ok {
return false
}
return true
}
func (t *testCase) LeaveNode(n ast.Vertex) {
t.t.Logf("LeaveNode: %T", n)
if _, ok := n.(*ast.Root); ok {
if !t.traversedFunction {
t.t.Error("traverser did not traverse function")
}
}
}
func (t *testCase) StmtClass(n *ast.StmtClass) {
t.t.Errorf("traverser got to class")
}
func (t *testCase) StmtClassMethod(n *ast.StmtClassMethod) {
t.t.Errorf("traverser got to method")
}
func (t *testCase) StmtFunction(n *ast.StmtFunction) {
t.traversedFunction = true
}
func TestEnterNodeIsRespected(t *testing.T) {
tc := &testCase{t: t}
tv := traverser.NewTraverser(tc)
root := &ast.Root{
Stmts: []ast.Vertex{
&ast.StmtFunction{},
&ast.StmtClass{
Stmts: []ast.Vertex{
&ast.StmtClassMethod{},
},
},
},
}
root.Accept(tv)
}