yq/pkg/yqlib/treeops/path_tree.go

57 lines
1.4 KiB
Go
Raw Normal View History

2020-10-08 23:59:03 +00:00
package treeops
2020-09-18 07:08:33 +00:00
2020-09-25 06:23:33 +00:00
import "fmt"
2020-09-18 07:08:33 +00:00
2020-10-08 23:59:03 +00:00
var myPathTokeniser = NewPathTokeniser()
var myPathPostfixer = NewPathPostFixer()
2020-09-25 06:23:33 +00:00
type PathTreeNode struct {
PathElement *PathElement
Lhs *PathTreeNode
Rhs *PathTreeNode
}
2020-09-18 07:08:33 +00:00
2020-09-25 06:23:33 +00:00
type PathTreeCreator interface {
2020-10-08 23:59:03 +00:00
ParsePath(path string) (*PathTreeNode, error)
CreatePathTree(postFixPath []*PathElement) (*PathTreeNode, error)
2020-09-25 06:23:33 +00:00
}
2020-09-18 07:08:33 +00:00
2020-09-25 06:23:33 +00:00
type pathTreeCreator struct {
}
2020-09-18 07:08:33 +00:00
2020-09-25 06:23:33 +00:00
func NewPathTreeCreator() PathTreeCreator {
return &pathTreeCreator{}
2020-09-18 07:08:33 +00:00
}
2020-10-08 23:59:03 +00:00
func (p *pathTreeCreator) ParsePath(path string) (*PathTreeNode, error) {
tokens, err := myPathTokeniser.Tokenise(path)
if err != nil {
return nil, err
}
var pathElements []*PathElement
pathElements, err = myPathPostfixer.ConvertToPostfix(tokens)
if err != nil {
return nil, err
}
return p.CreatePathTree(pathElements)
}
2020-09-25 06:23:33 +00:00
func (p *pathTreeCreator) CreatePathTree(postFixPath []*PathElement) (*PathTreeNode, error) {
var stack = make([]*PathTreeNode, 0)
for _, pathElement := range postFixPath {
var newNode = PathTreeNode{PathElement: pathElement}
if pathElement.PathElementType == Operation {
remaining, lhs, rhs := stack[:len(stack)-2], stack[len(stack)-2], stack[len(stack)-1]
newNode.Lhs = lhs
newNode.Rhs = rhs
stack = remaining
}
stack = append(stack, &newNode)
}
if len(stack) != 1 {
return nil, fmt.Errorf("expected stack to have 1 thing but its %v", stack)
2020-09-18 07:08:33 +00:00
}
2020-09-25 06:23:33 +00:00
return stack[0], nil
2020-09-18 07:08:33 +00:00
}