-
Notifications
You must be signed in to change notification settings - Fork 0
/
TreeNode.py
413 lines (327 loc) · 9.39 KB
/
TreeNode.py
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# TreeNode.py
import sys, re, pytest, collections
from more_itertools import ilen
from myutils import rmPrefix, isAllWhiteSpace
reAssign = re.compile(r'^(\S+)\s*\=\s*(.*)$')
class TreeNode(collections.abc.MutableMapping):
# --- These are a Class variables -------------------
# Modify this to affect how indentation is printed
# NOTE: Does NOT affect parsing
indent = "\t"
# labels matching this are NOT quoted
reSimpleLabel = re.compile(r'^[A-Za-z0-9_]+$')
# ------------------------------------------------------------------------
def __init__(self, label):
super().__init__()
# --- label cannot be all whitespace nor start with whitespace
if isAllWhiteSpace(label):
raise Exception(f"Label '{traceStr(label)}' is all whitespace")
if (label.lstrip() != label):
raise Exception(f"Label '{traceStr(label)}' has leading whitespace")
self.hData = {
'label': label,
}
self.parent = None
self.nextSibling = None
self.firstChild = None
# ------------------------------------------------------------------------
# Multiple ways to build up a tree structure
# ------------------------------------------------------------------------
def makeChildOf(self, node):
assert isinstance(node, TreeNode)
self.parent = node
lastChild = node.firstChild
if lastChild != None:
while lastChild.nextSibling:
lastChild = lastChild.nextSibling
# --- Now, lastChild has no nextSibling
lastChild.nextSibling = self
else:
node.firstChild = self
return self # allow chaining
def makeSiblingOf(self, node):
assert isinstance(node, TreeNode)
assert not self.parent
# assert node.parent
parent = node.parent
cur = node
while cur.nextSibling:
cur = cur.nextSibling
assert cur.parent == parent
cur.nextSibling = self
self.parent = parent
return self # allow chaining
def appendNode(self, newNode):
node = self
while node.nextSibling:
node = node.nextSibling
node.nextSibling = newNode
return self # allow chaining
def appendChildNode(self, newNode):
if self.firstChild:
self.firstChild.appendNode(newNode)
else:
self.firstChild = newNode
return self # allow chaining
def append(self, label):
self.appendNode(TreeNode(label))
return self # allow chaining
def appendChild(self, label):
self.appendChildNode(TreeNode(label))
return self # allow chaining
# ------------------------------------------------------------------------
# --- These methods allow us to treat a TreeNode object as a dict
def __getitem__(self, key):
return self.hData[key]
def __setitem__(self, key, value):
self.hData[key] = value
def __delitem__(self, key):
del self.hData[key]
def __len__(self):
return len(self.hData)
def __iter__(self):
return iter(self.hData)
# ------------------------------------------------------------------------
# --- These methods allow us to iterate over all of a
# TreeNode's children or descendents
def hasChildren(self):
return self.firstChild != None
def numChildren(self):
n = 0
node = self.firstChild
while node:
n += 1
node = node.nextSibling
return n
def children(self):
child = self.firstChild
while (child):
yield child
child = child.nextSibling
def descendents(self, level=0):
# --- First, visit the node itself
yield (level, self)
# --- Next, visit all of the node's descendents
child = self.firstChild
while (child):
yield from child.descendents(level+1)
child = child.nextSibling
def followingNodes(self, level=0):
# --- First, visit the node itself
yield (level, self)
# --- Next, visit all of the node's descendents
child = self.firstChild
while (child):
yield from child.descendents(level+1)
child = child.nextSibling
# --- Next, visit siblings and their descendents
node = self.nextSibling
while node:
yield (level, node)
child = node.firstChild
while (child):
yield from child.descendents(level+1)
child = child.nextSibling
node = node.nextSibling
def numNodes(self):
return ilen(self.descendents())
def asString(self, level=0, indent='\t'):
s = ''
cur = self
while cur:
for (level,node) in cur.descendents():
s += (indent * level) + node.hData['label'] + '\n'
cur = cur.nextSibling
return s
# ------------------------------------------------------------------------
# Utility Methods
# ------------------------------------------------------------------------
def getOptions(self, *, re=reAssign):
# --- re must include 2 groups - name of option and value of option
# only direct children are checked
hOptions = {}
for child in self.children():
try:
label = child['label']
r = re.search(label)
if r:
hOptions[r.group(1)] = r.group(2)
except Exception as ex:
pass
return hOptions
# ------------------------------------------------------------------------
def hasTrueChildren(self, re=reAssign):
child = self.firstChild
while (child):
label = child['label']
if not re.search(label):
return True
child = child.nextSibling
return False
# ------------------------------------------------------------------------
def trueChildren(self, re=reAssign):
child = self.firstChild
while (child):
label = child['label']
if not re.search(label):
yield child
child = child.nextSibling
# ------------------------------------------------------------------------
def printTree(self, desc=None, *,
level=0, debug=False, indent=None):
print()
print('='*50)
if desc:
print('-'*6 + ' Tree \'' + desc + '\'')
print('-'*50)
for (level,node) in self.descendents():
node.printNode(level, debug, indent)
print('='*50)
def printFragment(self, desc=None, *,
level=0, debug=False, indent=None):
print()
print('='*50)
if desc:
print('-'*6 + ' Tree \'' + desc + '\'')
print('-'*50)
cur = self
while cur:
for (level,node) in cur.descendents():
node.printNode(level, debug, indent)
cur = cur.nextSibling
print('='*50)
def printNode(self, level=0, debug=True, indent=None):
indentStr = (indent or self.indent) * level
if debug:
print('-' * 50)
print(f"{indentStr}{self.asDebugString()}")
if debug:
print(f"{indentStr} -parent = {nodeStr(self.parent)}")
print(f"{indentStr} -nextSibling = {nodeStr(self.nextSibling)}")
print(f"{indentStr} -firstChild = {nodeStr(self.firstChild)}")
print('-' * 50)
return
def asDebugString(self):
# --- This should also "escape" any control characters
label = self['label']
if self.reSimpleLabel.match(label):
return label
else:
return "'" + label + "'"
# ---------------------------------------------------------------------------
def nodeStr(node):
# --- Cannot be a method because node can be None
# e.g. nodeStr(somenode.nextSibling)
if node:
assert isinstance(node, TreeNode)
return node.asDebugString()
else:
return '(None)'
# ---------------------------------------------------------------------------
# UNIT TESTS
# ---------------------------------------------------------------------------
# --- test tree ---
# top
# peach
# fuzzy navel
# pink
# apple
# red
test_tree = TreeNode('top')
peach = TreeNode('peach').makeChildOf(test_tree)
TreeNode('fuzzy navel').makeChildOf(peach)
TreeNode('pink').makeChildOf(peach)
apple = TreeNode('apple').makeChildOf(test_tree)
TreeNode('red').makeChildOf(apple)
def test_0():
# --- Test asString()
mystr = test_tree.asString()
assert mystr == rmPrefix('''
top
peach
fuzzy navel
pink
apple
red
''')
def test_1():
n = ilen(test_tree.children())
assert n == 2
def test_2():
n = ilen(test_tree.descendents())
assert n == 6
def test_3():
assert ilen(test_tree.firstChild.children()) == 2
def test_4():
assert test_tree['label'] == 'top'
def test_5():
assert test_tree.firstChild['label'] == 'peach'
def test_6():
node = test_tree.firstChild.firstChild
node['label'] == 'fuzzy navel'
# --- test using getOptions()
# only direct children are checked
# if the regexp isn't matched, the child is ignored
def test_7():
from PLLParser import parsePLL
(node,h) = parsePLL('''
mainWindow
*menubar
align=left
flow = 99
--------------
not an option
*layout
life= 42
meaning =42
''')
menubar = h['menubar']
assert menubar
assert isinstance(menubar, TreeNode)
hOptions1 = menubar.getOptions()
assert hOptions1 == {
'align': 'left',
'flow': '99',
}
layout = h['layout']
assert layout
assert isinstance(layout, TreeNode)
hOptions2 = layout.getOptions()
assert hOptions2 == {
'life': '42',
'meaning': '42',
}
def test_8():
from PLLParser import parsePLL
# --- Note that this regexp allows no space before the colon
# and requires at least one space after the colon
reWithColon = re.compile(r'^(\S+):\s+(.*)$')
(node,h) = parsePLL('''
mainWindow
*menubar
align: left
flow: 99
notAnOption : text
notAnOption:moretext
--------------
not an option
*layout
life: 42
meaning: 42
''')
menubar = h['menubar']
assert menubar
assert isinstance(menubar, TreeNode)
hOptions1 = menubar.getOptions(re=reWithColon)
assert hOptions1 == {
'align': 'left',
'flow': '99',
}
layout = h['layout']
assert layout
assert isinstance(layout, TreeNode)
hOptions2 = layout.getOptions(re=reWithColon)
assert hOptions2 == {
'life': '42',
'meaning': '42',
}