-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
140 lines (119 loc) · 2.31 KB
/
node.go
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package typegen
import (
"fmt"
"reflect"
"github.com/mikeschinkel/go-diffator"
. "github.com/mikeschinkel/go-lib"
)
type Nodes []*Node
func (ns Nodes) AppendNode(n *Node) Nodes {
resetDebugString(n)
return append(ns, n)
}
type NodeArgs struct {
Value any
ReflectValue *reflect.Value
Name string
Type NodeType
marshaler *NodeMarshaler
Index int
Parent *Node
Typename string
}
type Node struct {
Id int
Value any
Typename string
Type NodeType
Name string
Parent *Node
nodes Nodes
Marshaler *NodeMarshaler
Index int
varname string
debugString string
}
func NewNode(id int, args *NodeArgs) (n *Node) {
if args.Type == InvalidNode {
args.Type = NodeType(args.ReflectValue.Kind())
}
n = &Node{
Id: id,
Name: args.Name,
Type: args.Type,
Typename: args.Typename,
Value: args.Value,
Marshaler: args.marshaler,
Index: args.Index,
Parent: args.Parent,
}
if args.ReflectValue != nil {
r := diffator.NewReflector(args.ReflectValue)
n.Value = r.Any()
n.Typename = r.Typename()
}
if n.Typename == "" {
Panicf("Missing argument for NewNode() for '%s'; either ReflectValue or Typename must be passed.", n)
}
n.Reset()
return n
}
func (n *Node) String() (s string) {
if n != nil {
s = fmt.Sprintf("%s %sNode [Id: %d, Index: %d]", n.Name, n.Type, n.Id, n.Index)
}
return s
}
func (n *Node) Reset() *Node {
if n == nil {
return n
}
n.nodes = make(Nodes, 0)
resetDebugString(n)
return n
}
func (n *Node) Varname() string {
return n.varname
}
func (n *Node) SetVarname(name string) *Node {
if n.varname != "" {
Panicf("Unexpected: overwriting varname '%s'", name)
}
n.varname = name
return n
}
func (n *Node) SetNodeCount(cnt int) *Node {
nodes := make(Nodes, 0, cnt)
for i, node := range n.nodes {
if i >= len(nodes) {
goto end
}
nodes[i] = node
}
end:
n.nodes = nodes
return n
}
func (n *Node) AddNode(node *Node) *Node {
node.Parent = n
resetDebugString(node)
node.Index = len(n.nodes)
n.nodes = n.nodes.AppendNode(node)
return n
}
func (n *Node) ChildNode(i int) *Node {
if i < 0 {
n = nil
goto end
}
if i >= len(n.nodes) {
n = nil
goto end
}
n = n.nodes[i]
end:
return n
}
func (n *Node) Nodes() Nodes {
return n.nodes
}