-
Notifications
You must be signed in to change notification settings - Fork 0
/
PLLParser.py
475 lines (375 loc) · 10.8 KB
/
PLLParser.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# PLLParser.py
"""
parse a 'Python-like language'
"""
import sys, io, re, pytest
from more_itertools import ilen
from pprint import pprint
from myutils import (rmPrefix, reLeadWS, isAllWhiteSpace,
traceStr, cleanup_testcode, firstWordOf)
from TreeNode import TreeNode
# --- Some pre-compiled regular expressions
hDefOptions = {
'hereDocStr': '<<<',
'markStr': '*',
'reAttr': re.compile(r'^(\S+)\s*\=\s*(.*)$'),
}
# ---------------------------------------------------------------------------
def parsePLL(fh, constructor=TreeNode,
hOptions={},
*,
debug=False):
return PLLParser(constructor, hOptions, debug).parse(fh)
# ---------------------------------------------------------------------------
class PLLParser():
# --- We want to compile these just once, so make them class fields
reLine = re.compile(r'^(\s*)')
hDefOptions = {
# --- These become attributes of the PLLParser object
'hereDocStr': '<<<',
'markStr': '*',
'reComment': re.compile(r'(?<!\\)#.*$'), # ignore escaped '#' char
'reAttr': re.compile(r'^(\S+)\s*\=\s*(.*)$'),
}
# ------------------------------------------------------------------------
def __init__(self, constructor=TreeNode,
hOptions={},
debug=False):
self.setOptions(hOptions)
self.constructor = constructor
self.debug = debug
# ------------------------------------------------------------------------
def setOptions(self, hOptions):
for name in self.hDefOptions.keys():
if name in hOptions:
value = hOptions[name]
else:
value = self.hDefOptions[name]
setattr(self, name, value)
# ------------------------------------------------------------------------
def parse(self, fh):
# --- Returns (rootNode, hSubTrees)
self.numLines = 0
rootNode = None
hSubTrees = {}
curLevel = None
debug = self.debug
# --- Putting this in a separate variable
# allows us to get HEREDOC lines
gen = self._generator(fh)
for line in gen:
if debug:
print(f"LINE {self.numLines}: '{traceStr(line)}'", end='')
(newLevel, label, marked, numHereDoc) = self.splitLine(line)
if debug:
print(f" [{newLevel},{numHereDoc}] '{label}'")
# --- Extract HEREDOC strings, if any
lHereDoc = None
if numHereDoc > 0:
lHereDoc = []
try:
text = ''
for i in range(numHereDoc):
hereLine = gen.send('any')
while not isAllWhiteSpace(hereLine):
text += hereLine
hereLine = gen.send('any')
lHereDoc.append(rmPrefix(text))
numHereDoc -= 1
except:
raise SyntaxError("Unexpected EOF in HEREDOC string")
# --- process first non-empty line
if rootNode == None:
rootNode = curNode = self.constructor(label)
if lHereDoc:
rootNode['lHereDoc'] = lHereDoc
# --- This wouldn't make any sense, but in case someone does it
if marked:
hSubTrees[firstWordOf(label)] = curNode
curLevel = newLevel
if debug:
print(f" - root node set to '{label}'")
continue
diff = newLevel - curLevel
if diff > 1:
# --- continuation line - append to current node's label
if debug:
print(' - continuation')
curNode['label'] += ' ' + label
# --- Don't change curLevel
elif diff == 1:
# --- create new child node
if debug:
assert isinstance(curNode, TreeNode)
print(f" - new child of {curNode.asDebugString()}")
assert not curNode.firstChild
curNode = self.constructor(label).makeChildOf(curNode)
if lHereDoc:
curNode['lHereDoc'] = lHereDoc
if marked:
hSubTrees[firstWordOf(label)] = curNode
curLevel += 1
elif diff < 0: # i.e. newLevel < curLevel
# --- Move up -diff levels, then create sibling node
if debug:
n = -diff
desc = 'level' if n==1 else 'levels'
print(f' - go up {n} {desc}')
while (curLevel > newLevel):
curLevel -= 1
curNode = curNode.parent
assert curNode
curNode = self.constructor(label).makeSiblingOf(curNode)
if lHereDoc:
curNode['lHereDoc'] = lHereDoc
if marked:
hSubTrees[firstWordOf(label)] = curNode
elif diff == 0:
# --- create new sibling node
if debug:
print(f" - new sibling of {curNode.asDebugString()}")
assert not curNode.nextSibling
curNode = self.constructor(label).makeSiblingOf(curNode)
if lHereDoc:
curNode['lHereDoc'] = lHereDoc
if marked:
hSubTrees[firstWordOf(label)] = curNode
else:
raise Exception("What! This cannot happen")
if self.numLines == 0:
raise Exception("parsePLL(): No text to parse")
if not rootNode:
raise Exception("parsePLL(): rootNode is empty")
assert isinstance(rootNode, self.constructor)
return (rootNode, hSubTrees)
# ------------------------------------------------------------------------
def _generator(self, fh):
# --- Allow passing in a string
if isinstance(fh, str):
fh = io.StringIO(fh)
# --- We'll need the first line to determine
# if there's any leading whitespace, which will
# be stripped from ALL lines (and therefore must
# be there for every subsequent line)
line = self.nextNonBlankLine(fh)
if not line:
return
# --- Check if there's any leading whitespace
leadWS = ''
leadLen = 0
result = reLeadWS.search(line)
if result:
leadWS = result.group(1)
leadLen = len(leadWS)
flag = None # might become 'any'
if leadWS:
while line:
# --- Check if the required leadWS is present
if not flag and (line[:leadLen] != leadWS):
raise SyntaxError("Missing leading whitespace")
flag = yield line[leadLen:]
if flag:
line = self.nextAnyLine(fh)
else:
line = self.nextNonBlankLine(fh)
else:
while line:
flag = yield line
if flag:
line = self.nextAnyLine(fh)
else:
line = self.nextNonBlankLine(fh)
# ------------------------------------------------------------------------
def splitLine(self, line):
# --- All whitespace lines should never be passed to this function
assert type(line) == str
assert not isAllWhiteSpace(line)
# --- returns (level, label, marked, numHereDoc)
# label will have markStr removed, but hereDocStr's will remain
marked = False
result = self.reLine.search(line)
if result:
# --- Get indentation, if any, to determine level
indent = result.group(1)
if ' ' in indent:
raise SyntaxError(f"Indentation '{traceStr(indent)}'"
" cannot contain space chars")
level = len(indent)
# --- Check if the mark string is present
# If so, strip it to get label, then set key = label
if self.markStr:
if line.find(self.markStr, level) == level:
label = line[level + len(self.markStr):].lstrip()
if len(label) == 0:
raise SyntaxError("Marked lines cannot be empty")
marked = True
else:
label = line[level:]
else:
label = line[level:]
# --- Check if there are any HereDoc strings
numHereDoc = 0
if self.hereDocStr:
pos = label.find(self.hereDocStr, 0)
while pos != -1:
numHereDoc += 1
pos += len(self.hereDocStr)
pos = label.find(self.hereDocStr, pos)
label = label.replace('\\#', '#')
return (level, label, marked, numHereDoc)
else:
raise Exception("What! This cannot happen (reLine fails to match)")
# ---------------------------------------------------------------------------
def nextAnyLine(self, fh):
line = fh.readline()
self.numLines += 1
if line:
return line
else:
return None
# ---------------------------------------------------------------------------
def nextNonBlankLine(self, fh):
line = fh.readline()
self.numLines += 1
if not line:
return None
line = re.sub(self.reComment, '', line)
line = line.rstrip()
while line == '':
line = fh.readline()
self.numLines += 1
if not line: return None
line = re.sub(self.reComment, '', line)
line = line.rstrip()
return line
# ---------------------------------------------------------------------------
# UNIT TESTS
# ---------------------------------------------------------------------------
def test_1():
s = '''
top
peach
fuzzy
navel
pink
apple
red
'''
(tree, hSubTrees) = parsePLL(s)
n = ilen(tree.children())
assert n == 2
n = ilen(tree.descendents())
assert n == 6
assert ilen(tree.firstChild.children()) == 2
assert tree['label'] == 'top'
assert tree.firstChild['label'] == 'peach'
node = tree.firstChild.firstChild
node['label'] == 'fuzzy navel'
# ---------------------------------------------------------------------------
# Test some invalid input
def test_7():
s = '''
main
peach
apple
'''
with pytest.raises(SyntaxError):
parsePLL(s)
def test_8():
s = '''
main
peach
apple
'''
with pytest.raises(SyntaxError):
parsePLL(s)
# ---------------------------------------------------------------------------
# --- Test HEREDOC syntax
def test_3():
s = '''
menubar
file
new
*handler <<<
my $evt = $_[0];
$evt.createNewFile();
return undef;
open
edit
undo
'''
(tree, hSubTrees) = parsePLL(s, debug=False)
handler = hSubTrees['handler']
label = tree['label']
assert label == 'menubar'
n = ilen(tree.children())
assert n == 2
n = ilen(tree.descendents())
assert n == 7
assert 'lHereDoc' in handler
assert (handler['lHereDoc'][0]
== 'my $evt = $_[0];\n$evt.createNewFile();\nreturn undef;\n')
# ---------------------------------------------------------------------------
# Test if it will parse fragments
def test_4():
s = '''
menubar
file
new
open
edit
undo
layout
row
EditField
SelectField
'''
(tree, hSubTrees) = parsePLL(s, debug=False)
n = ilen(tree.descendents())
assert n == 6
n = ilen(tree.followingNodes())
assert n == 10
# ---------------------------------------------------------------------------
# Test marked subtrees
def test_5():
s = '''
App
* menubar
file
new
open
edit
undo
* layout
row
EditField
SelectField
'''
(tree, hSubTrees) = parsePLL(s, debug=False)
subtree1 = hSubTrees['menubar']
subtree2 = hSubTrees['layout']
n = ilen(tree.descendents())
assert n == 11
assert (subtree1['label'] == 'menubar')
n = ilen(subtree1.descendents())
assert n == 6
assert (subtree2['label'] == 'layout')
n = ilen(subtree2.descendents())
assert n == 4
n = ilen(tree.followingNodes())
assert n == 11
def test_6():
s = '''
bg # a comment
color = \\#abcdef # not a comment
'''
(tree, hSubTrees) = parsePLL(s)
n = ilen(tree.descendents())
assert n == 2
assert tree['label'] == 'bg'
assert tree.firstChild['label'] == 'color = #abcdef'
# ---------------------------------------------------------------------------
cleanup_testcode(globals()) # remove unit tests when not testing
# ---------------------------------------------------------------------------
# To Do:
# 1. Allow spaces for indentation