summaryrefslogtreecommitdiff
path: root/vendor/github.com/mitchellh/packer/vendor/github.com/ChrisTrenkamp/goxpath/internal/parser/ast.go
blob: ec62206eaa0a642bf7ff74d1164b185be0dc37b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package parser

import "github.com/ChrisTrenkamp/goxpath/internal/lexer"

//NodeType enumerations
const (
	Empty lexer.XItemType = ""
)

//Node builds an AST tree for operating on XPath expressions
type Node struct {
	Val    lexer.XItem
	Left   *Node
	Right  *Node
	Parent *Node
	next   *Node
}

var beginPathType = map[lexer.XItemType]bool{
	lexer.XItemAbsLocPath:     true,
	lexer.XItemAbbrAbsLocPath: true,
	lexer.XItemAbbrRelLocPath: true,
	lexer.XItemRelLocPath:     true,
	lexer.XItemFunction:       true,
}

func (n *Node) add(i lexer.XItem) {
	if n.Val.Typ == Empty {
		n.Val = i
	} else if n.Left == nil {
		n.Left = &Node{Val: n.Val, Parent: n}
		n.Val = i
	} else if beginPathType[n.Val.Typ] {
		next := &Node{Val: n.Val, Left: n.Left, Parent: n}
		n.Left = next
		n.Val = i
	} else if n.Right == nil {
		n.Right = &Node{Val: i, Parent: n}
	} else {
		next := &Node{Val: n.Val, Left: n.Left, Right: n.Right, Parent: n}
		n.Left, n.Right = next, nil
		n.Val = i
	}
	n.next = n
}

func (n *Node) push(i lexer.XItem) {
	if n.Left == nil {
		n.Left = &Node{Val: i, Parent: n}
		n.next = n.Left
	} else if n.Right == nil {
		n.Right = &Node{Val: i, Parent: n}
		n.next = n.Right
	} else {
		next := &Node{Val: i, Left: n.Right, Parent: n}
		n.Right = next
		n.next = n.Right
	}
}

func (n *Node) pushNotEmpty(i lexer.XItem) {
	if n.Val.Typ == Empty {
		n.add(i)
	} else {
		n.push(i)
	}
}

/*
func (n *Node) prettyPrint(depth, width int) {
	nodes := []*Node{}
	n.getLine(depth, &nodes)
	fmt.Printf("%*s", (width-depth)*2, "")
	toggle := true
	if len(nodes) > 1 {
		for _, i := range nodes {
			if i != nil {
				if toggle {
					fmt.Print("/   ")
				} else {
					fmt.Print("\\   ")
				}
			}
			toggle = !toggle
		}
		fmt.Println()
		fmt.Printf("%*s", (width-depth)*2, "")
	}
	for _, i := range nodes {
		if i != nil {
			fmt.Print(i.Val.Val, "   ")
		}
	}
	fmt.Println()
}

func (n *Node) getLine(depth int, ret *[]*Node) {
	if depth <= 0 && n != nil {
		*ret = append(*ret, n)
		return
	}
	if n.Left != nil {
		n.Left.getLine(depth-1, ret)
	} else if depth-1 <= 0 {
		*ret = append(*ret, nil)
	}
	if n.Right != nil {
		n.Right.getLine(depth-1, ret)
	} else if depth-1 <= 0 {
		*ret = append(*ret, nil)
	}
}
*/