-
Notifications
You must be signed in to change notification settings - Fork 8
/
LIBLR.py
4135 lines (3725 loc) · 136 KB
/
LIBLR.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 tw=0 et :
#======================================================================
#
# LIBLR.py - Parser Generator with LR(1) and LALR
#
# History of this file:
#
# 2023.01.20 skywind grammar definition
# 2023.01.21 skywind grammar analayzer
# 2023.01.22 skywind basic tokenizer
# 2023.01.23 skywind grammar loader
# 2023.01.24 skywind LR(1) generator
# 2023.01.25 skywind LALR generator
# 2023.01.25 skywind Lexer & PDAInput
# 2023.01.26 skywind PDA
# 2023.01.26 skywind conflict solver
# 2023.01.27 skywind better error checking
# 2023.02.22 skywind new print() method for Node class
#
#======================================================================
from __future__ import unicode_literals, print_function
import sys
import os
import time
import json
import copy
import re
import collections
import pprint
from enum import Enum, IntEnum
#----------------------------------------------------------------------
# exports
#----------------------------------------------------------------------
__all__ = ['GrammarError', 'Symbol', 'Vector', 'Production', 'Grammar',
'Token', 'Parser', 'LRTable', 'Action', 'ActionName', 'Node',
'create_parser', 'create_parser_from_file']
#----------------------------------------------------------------------
# logs
#----------------------------------------------------------------------
LOG_ERROR = lambda *args: print('error:', *args)
LOG_WARNING = lambda *args: print('warning:', *args)
LOG_INFO = lambda *args: print('info:', *args)
LOG_DEBUG = lambda *args: print('debug:', *args)
LOG_VERBOSE = lambda *args: print('debug:', *args)
# ignore log levels
LOG_VERBOSE = lambda *args: 0
LOG_DEBUG = lambda *args: 0
#----------------------------------------------------------------------
# GrammarError
#----------------------------------------------------------------------
class GrammarError (Exception):
pass
#----------------------------------------------------------------------
# 符号类:包括终结符和非终结符,term 代表是否为终结符,
# 空的话用空字符串表示
#----------------------------------------------------------------------
class Symbol (object):
def __init__ (self, name, terminal = False):
self.name = name
self.term = terminal
# 转为可打印字符串
def __str__ (self):
if not self.name:
return "''"
return self.name
# 判断是否相等
def __eq__ (self, symbol):
if isinstance(symbol, str):
return (self.name == symbol)
elif symbol is None:
return (self is None)
elif not isinstance(symbol, Symbol):
raise TypeError('Symbol cannot be compared to a %s'%type(symbol))
return (self.name == symbol.name)
def __ne__ (self, symbol):
return (not (self == symbol))
# >=
def __ge__ (self, symbol):
return (self.name >= symbol.name)
# >
def __gt__ (self, symbol):
return (self.name > symbol.name)
# <=
def __le__ (self, symbol):
return (self.name <= symbol.name)
# <
def __lt__ (self, symbol):
return (self.name < symbol.name)
def __repr__ (self):
if not self.term:
return '%s(%r)'%(type(self).__name__, self.name)
return '%s(%r, %r)'%(type(self).__name__, self.name, self.term)
# 求哈希,有这个函数可以将 Symbol 放到容器里当 key
def __hash__ (self):
return hash(self.name)
# 拷贝
def __copy__ (self):
obj = Symbol(self.name, self.term)
if hasattr(self, 'value'):
obj.value = self.value
if hasattr(self, 'token'):
obj.token = self.token
return obj
# 深度拷贝
def __deepcopy__ (self):
obj = Symbol(self.name, self.term)
if hasattr(self, 'value'):
obj.value = copy.deepcopy(self.value)
if hasattr(self, 'token'):
obj.token = copy.deepcopy(self.token)
return obj
# 判断是否是字符串字面量
def _is_literal (self):
if len(self.name) < 2:
return False
mark = self.name[0]
if mark not in ('"', "'"):
return False
if self.name[-1] == mark:
return True
return False
# 判断是否是空/epsilon
@property
def is_epsilon (self):
if self.term:
return False
elif self.name == '':
return True
if self.name in ('%empty', '%e', '%epsilon', '\u03b5', '<empty>'):
return True
return False
# 判断是否是字符串字面量
@property
def is_literal (self):
return self._is_literal()
#----------------------------------------------------------------------
# 从字符串或者 tuple 创建一个 Symbol
#----------------------------------------------------------------------
def load_symbol (source):
if isinstance(source, Symbol):
return source
elif isinstance(source, str):
sym = Symbol(source)
if sym.is_literal:
sym.term = True
if len(sym.name) == 2 and sym.name[0] == sym.name[1]:
sym.term = False
sym.name = ''
try: sym.value = eval(sym.name)
except: pass
elif source == '$':
sym.term = True
elif source == '#':
sym.term = True
return sym
elif isinstance(source, list) or isinstance(source, tuple):
assert len(source) > 0
if len(source) == 0:
raise ValueError('bad symbol: %r'%source)
elif len(source) == 1:
return Symbol(source[0])
elif len(source) == 2:
return Symbol(source[0], source[1])
s = Symbol(source[0], source[1])
s.value = source[2]
return s
raise ValueError('bad symbol: %r'%source)
#----------------------------------------------------------------------
# 符号矢量:符号列表
#----------------------------------------------------------------------
class Vector (object):
def __init__ (self, vector):
self.m = tuple(self.__load_vector(vector))
self.__hash = None
def __load_vector (self, vector):
epsilon = True
output = []
p = [ load_symbol(n) for n in vector ]
for symbol in p:
if not symbol.is_epsilon:
epsilon = False
break
if not epsilon:
for n in p:
if not n.is_epsilon:
output.append(n)
return output
def __len__ (self):
return len(self.m)
def __getitem__ (self, index):
return self.m[index]
def __contains__ (self, key):
if isinstance(key, int):
return (key >= 0 and key < len(self.m))
for n in self.m:
if n == key:
return True
return False
def __hash__ (self):
if self.__hash is None:
h = tuple([n.name for n in self.m])
self.__hash = hash(h)
return self.__hash
def __iter__ (self):
return self.m.__iter__()
def __repr__ (self):
return '%s(%r)'%(type(self).__name__, self.m)
def __str__ (self):
body = [ str(n) for n in self.m ]
return ' '.join(body)
def __eq__ (self, p):
assert isinstance(p, Vector)
if hash(self) != hash(p):
return False
return (self.m == p.m)
def __ne__ (self, p):
return (not (self == p))
def __ge__ (self, p):
return (self.m >= p.m)
def __gt__ (self, p):
return (self.m > p.m)
def __le__ (self, p):
return (self.m <= p.m)
def __lt__ (self, p):
return (self.m < p.m)
def __copy__ (self):
obj = Vector(self.m)
obj.__hash = self.__hash
return obj
def __deepcopy__ (self):
p = [ n.__deepcopy__() for n in self.m ]
obj = Vector(p)
obj.__hash = self.__hash
return obj
def search (self, symbol, stop = -1):
if stop < 0:
return self.m.index(symbol)
return self.m.index(symbol, stop)
@property
def is_empty (self):
return (len(self.m) == 0)
# 计算最左边的终结符
def leftmost_terminal (self):
for n in self.m:
if n.term:
return n
return None
# 计算最右边的终结符
def rightmost_terminal (self):
index = len(self.m) - 1
while index >= 0:
symbol = self.m[index]
if symbol.term:
return symbol
index -= 1
return None
#----------------------------------------------------------------------
# 产生式/生成式:由 head -> body 组成,head 是 symbol,
# budy 是一个 Vector,即 symbol 组成的序列
#----------------------------------------------------------------------
class Production (object):
def __init__ (self, head, body, index = -1):
self.head = load_symbol(head)
self.body = Vector(body)
self.__hash = None
self.index = index
self.is_epsilon = None
self.has_epsilon = None
self.precedence = None
self.action = None
def __len__ (self):
return len(self.body)
def __getitem__ (self, index):
return self.body[index]
def __contains__ (self, key):
return (key in self.body)
def __hash__ (self):
if self.__hash is None:
h1 = hash(self.head)
h2 = hash(self.body)
self.__hash = hash((h1, h2))
return self.__hash
def __iter__ (self):
return self.body.__iter__()
def __repr__ (self):
return '%s(%r, %r)'%(type(self).__name__, self.head, self.body)
def __str__ (self):
body = [ str(n) for n in self.body ]
return '%s: %s ;'%(self.head, ' '.join(body))
def __eq__ (self, p):
assert isinstance(p, Production)
if hash(self) != hash(p):
return False
if self.head != p.head:
return False
return (self.body == p.body)
def __ne__ (self, p):
return not (self == p)
def __ge__ (self, p):
if self.head > p.head:
return True
elif self.head < p.head:
return False
return (self.body >= p.body)
def __gt__ (self, p):
if self.head > p.head:
return True
elif self.head < p.head:
return False
return (self.body > p.body)
def __lt__ (self, p):
return (not (self >= p))
def __le__ (self, p):
return (not (self > p))
def __copy__ (self):
obj = Production(self.head, self.body)
obj.index = self.index
obj.precedence = self.precedence
obj.is_epsilon = self.is_epsilon
obj.has_epsilon = self.has_epsilon
obj.__hash = self.__hash
obj.action = self.action
return obj
def __deepcopy__ (self):
p = self.body.__deepcopy__()
obj = Production(self.head.__deepcopy__(), p)
obj.index = self.index
obj.precedence = self.precedence
obj.is_epsilon = self.is_epsilon
obj.has_epsilon = self.has_epsilon
obj.__hash = self.__hash
if self.action:
obj.action = copy.deepcopy(self.action)
return obj
def search (self, symbol, stop = -1):
return self.body.search(symbol, stop)
@property
def is_empty (self):
return (len(self.body) == 0)
# 计算最右边的终结符
def rightmost_terminal (self):
return self.body.rightmost_terminal()
# 最左侧的终结符
def leftmost_terminal (self):
return self.body.leftmost_terminal()
# 计算是否直接左递归
@property
def is_left_recursion (self):
if len(self.body) == 0:
return False
return (self.head == self.body[0])
# 计算是否直接右递归
@property
def is_right_recursion (self):
if len(self.body) == 0:
return False
return (self.head == self.body[-1])
def __action_to_string (self, m):
if isinstance(m, str):
return m
assert isinstance(m, tuple)
name:str = m[0]
stack = m[1]
if name.startswith('{') and name.endswith('}'):
return '{%s/%d}'%(name[1:-1], stack)
return '%s/%d'%(name, stack)
# 返回包含动作的身体部分
def stringify (self, head = True, body = True, action = False, prec = False):
text = ''
if head:
text += str(self.head) + ': '
act = getattr(self, 'action', {})
if body:
for i, n in enumerate(self.body.m):
if action and act and (i in act):
for m in act[i]:
text += '%s '%self.__action_to_string(m)
text += n.name + ' '
i = len(self.body)
if action and act and (i in act):
for m in act[i]:
text += '%s '%self.__action_to_string(m)
if prec:
text += ' <%s>'%(self.precedence, )
return text.strip('\r\n\t ')
#----------------------------------------------------------------------
# 语法类,一个语法 G 由终结符,非终结符和产生式组成
#----------------------------------------------------------------------
class Grammar (object):
def __init__ (self):
self.production = []
self.symbol = {} # str -> Symbol map
self.terminal = {} # str -> Symbol map
self.rule = {} # str -> list
self.precedence = {} # str -> prec
self.assoc = {} # str -> one of (None, 'left', 'right')
self._anchor = {} # str -> (filename, linenum)
self._dirty = False
self.scanner = [] # scanner rules
self.start = None
def reset (self):
self.production.clear()
self.symbol.clear()
self.terminal.clear()
self.nonterminal.clear()
self.rule.clear()
self._anchor.clear()
self.scanner.clear()
self.start = None
return 0
def _symbol_name (self, symbol):
if isinstance(symbol, Symbol):
return symbol.name
elif isinstance(symbol, str):
return symbol
raise TypeError('bad symbol: %r'%symbol)
def __len__ (self):
return len(self.production)
def __getitem__ (self, index):
return self.production[index]
def __iter__ (self):
return self.production.__iter__()
def __contains__ (self, key):
if isinstance(key, int):
return (key >= 0 and key < len(self.production))
elif isinstance(key, Production):
for p in self.production:
if p == key:
return True
elif isinstance(key, Symbol):
return (key.name in self.symbol)
elif isinstance(key, str):
return (key in self.symbol)
return False
def __copy__ (self):
obj = Grammar()
for p in self.production:
obj.push_production(p.__copy__())
for t in self.terminal:
obj.push_token(t)
for p in self.precedence:
c = self.precedence[p]
obj.push_precedence(p, c[0], c[1])
obj.srcinfo = self.srcinfo.__copy__()
obj.update()
if self.start:
obj.start = obj.symbol[self.start.name]
return obj
def __deepcopy__ (self, memo):
obj = Grammar()
for p in self.production:
obj.push_production(p.__deepcopy__(memo))
for t in self.terminal:
obj.push_token(t)
for p in self.precedence:
c = self.precedence[p]
obj.push_precedence(p, c[0], c[1])
obj.srcinfo = self.srcinfo.__deepcopy__(memo)
obj.update()
if self.start:
obj.start = obj.symbol[self.start.name]
return obj
def insert (self, index, production):
self.production.insert(index, production)
self._dirty = True
def search (self, p, stop = -1):
if stop < 0:
return self.production.index(p)
return self.production.index(p, stop)
def remove (self, index):
if isinstance(index, int):
self.production.pop(index)
else:
index = self.search(index)
self.production.pop(index)
self._dirty = True
def pop (self, index = -1):
self.production.pop(index)
self._dirty = True
def append (self, production):
index = len(self.production)
self.production.append(production)
production.index = index
self._dirty = True
def replace (self, index, source):
if isinstance(source, Production):
self.production[index] = source
elif isinstance(source, list) or isinstance(source, tuple):
for n in source:
assert isinstance(n, Production)
self.production.insert(index + 1, n)
self.production.pop(index)
self._dirty = True
def update (self):
self.symbol.clear()
self.rule.clear()
for i, p in enumerate(self.production):
p.index = i
head = p.head
if head.name not in self.symbol:
self.symbol[head.name] = head
for n in p.body:
if n.name not in self.symbol:
self.symbol[n.name] = n
if head.name not in self.rule:
self.rule[head.name] = []
self.rule[head.name].append(p)
for n in self.terminal:
s = self.terminal[n]
if not s.term:
s.term = True
for n in self.symbol:
s = self.symbol[n]
s.term = (n in self.terminal)
if not s.term:
if s.name not in self.rule:
self.rule[s.name] = []
for p in self.production:
p.head.term = (p.head.name in self.terminal)
for n in p.body:
n.term = (n.name in self.terminal)
for p in self.production:
if p.precedence is None:
rightmost = p.rightmost_terminal()
if rightmost and (rightmost in self.precedence):
p.precedence = rightmost.name
self._dirty = False
return 0
# declare terminal
def push_token (self, token):
name = self._symbol_name(token)
if token not in self.terminal:
t = load_symbol(token)
t.term = True
self.terminal[name] = t
self._dirty = True
return 0
# push precedence
def push_precedence (self, symbol, prec, assoc):
name = self._symbol_name(symbol)
if prec == 'precedence':
prec = 'left'
self.precedence[name] = prec
self.assoc[name] = assoc
# push scanner (aka. lexer) rules
def push_scanner (self, obj):
self.scanner.append(obj)
return 0
# create new symbol according to self.terminal
def create_symbol (self, name):
cc = load_symbol(name)
if name != '':
if name in self.terminal:
cc.term = True
return cc
# argument
def argument (self):
if not self.start:
raise GrammarError('no start point')
if 'S^' in self.symbol:
raise GrammarError('already argumented')
head = 'S^'
p = Production(head, [self.start])
self.insert(0, p)
self.start = p.head
self.update()
return 0
def __anchor_key (self, obj):
if isinstance(obj, str):
return obj
elif isinstance(obj, Symbol):
return str(obj)
elif isinstance(obj, int):
return '^INT/' + str(obj)
elif isinstance(obj, Vector):
return '^VEC/' + str(obj)
elif isinstance(obj, Production):
return '^PROD/' + str(obj)
return str(obj)
# anchor: source file info (filename, line_num)
def anchor_set (self, obj, filename, line_num):
self._anchor[self.__anchor_key(obj)] = (filename, line_num)
return 0
def anchor_get (self, obj):
key = self.__anchor_key(obj)
if key not in self._anchor:
return (None, None)
return self._anchor[key]
def anchor_has (self, obj):
key = self.__anchor_key(obj)
return (key in self._anchor)
def print (self, mode = 0, action = False, prec = False):
if mode == 0:
for i, n in enumerate(self.production):
t = '(%d) %s'%(i, n.stringify(True, True, action, prec))
print(t)
else:
keys = list(self.rule.keys())
for key in keys:
head = str(key) + ': '
padding = ' ' * (len(head) - 2)
for i, p in enumerate(self.rule[key]):
if i == 0:
print(head, end = '')
else:
print(padding + '| ', end = '')
print(p.stringify(False, True, action, prec), end = ' ')
if len(self.rule[key]) > 1:
print('')
if len(self.rule[key]) > 1:
print(padding + ';')
else:
print(';')
return 0
def __str__ (self):
text = []
for i, n in enumerate(self.production):
t = '(%d) %s'%(i, str(n))
text.append(t)
return '\n'.join(text)
#----------------------------------------------------------------------
# Token: (name, value, line, column)
# name represents token type, since "type" is a reserved word in
# python, choose "name" instead
#----------------------------------------------------------------------
class Token (object):
def __init__ (self, name, value, line = 0, column = 0):
self.name = name
self.value = value
self.line = line
self.column = column
def __str__ (self):
if self.line is None:
return '(%s, %s)'%(self.name, self.value)
t = (self.name, self.value, self.line, self.column)
return '(%s, %s, %s, %s)'%t
def __repr__ (self):
n = type(self).__name__
if self.line is None:
return '%s(%r, %r)'%(n, self.name, self.value)
t = (n, self.name, self.value, self.line, self.column)
return '%s(%r, %r, %r, %r)'%t
def __copy__ (self):
return Token(self.name, self.value, self.line, self.column)
#----------------------------------------------------------------------
# tokenize
#----------------------------------------------------------------------
def _tokenize(code, specs, eof = None):
patterns = []
definition = {}
extended = {}
if not specs:
return None
for index in range(len(specs)):
spec = specs[index]
name, pattern = spec[:2]
pn = 'PATTERN%d'%index
definition[pn] = name
if len(spec) >= 3:
extended[pn] = spec[2]
patterns.append((pn, pattern))
tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in patterns)
line_starts = []
pos = 0
index = 0
while 1:
line_starts.append(pos)
pos = code.find('\n', pos)
if pos < 0:
break
pos += 1
line_num = 0
for mo in re.finditer(tok_regex, code):
kind = mo.lastgroup
value = mo.group()
start = mo.start()
while line_num < len(line_starts) - 1:
if line_starts[line_num + 1] > start:
break
line_num += 1
line_start = line_starts[line_num]
name = definition[kind]
if name is None:
continue
if callable(name):
if kind not in extended:
obj = name(value)
else:
obj = name(value, extended[kind])
name = None
if isinstance(obj, list) or isinstance(obj, tuple):
if len(obj) > 0:
name = obj[0]
if len(obj) > 1:
value = obj[1]
else:
name = obj
yield (name, value, line_num + 1, start - line_start + 1)
if eof is not None:
line_start = line_starts[-1]
endpos = len(code)
yield (eof, '', len(line_starts), endpos - line_start + 1)
return 0
#----------------------------------------------------------------------
# Tokenize
#----------------------------------------------------------------------
def tokenize(code, rules, eof = None):
for info in _tokenize(code, rules, eof):
yield Token(info[0], info[1], info[2], info[3])
return 0
#----------------------------------------------------------------------
# validate pattern
#----------------------------------------------------------------------
def validate_pattern(pattern):
try:
re.compile(pattern)
except re.error:
return False
return True
#----------------------------------------------------------------------
# replace '{name}' in a pattern with the text in "macros[name]"
#----------------------------------------------------------------------
def regex_expand(macros, pattern, guarded = True):
output = []
pos = 0
size = len(pattern)
while pos < size:
ch = pattern[pos]
if ch == '\\':
output.append(pattern[pos:pos + 2])
pos += 2
continue
elif ch != '{':
output.append(ch)
pos += 1
continue
p2 = pattern.find('}', pos)
if p2 < 0:
output.append(ch)
pos += 1
continue
p3 = p2 + 1
name = pattern[pos + 1:p2].strip('\r\n\t ')
if name == '':
output.append(pattern[pos:p3])
pos = p3
continue
if name[0].isdigit():
output.append(pattern[pos:p3])
pos = p3
continue
if ('<' in name) or ('>' in name):
raise ValueError('invalid pattern name "%s"'%name)
if name not in macros:
raise ValueError('{%s} is undefined'%name)
if guarded:
output.append('(?:' + macros[name] + ')')
else:
output.append(macros[name])
pos = p3
return ''.join(output)
#----------------------------------------------------------------------
# build regex info
#----------------------------------------------------------------------
def regex_build(code, macros = None, capture = True):
defined = {}
if macros is not None:
for k, v in macros.items():
defined[k] = v
line_num = 0
for line in code.split('\n'):
line_num += 1
line = line.strip('\r\n\t ')
if (not line) or line.startswith('#'):
continue
pos = line.find('=')
if pos < 0:
raise ValueError('%d: not a valid rule'%line_num)
head = line[:pos].strip('\r\n\t ')
body = line[pos + 1:].strip('\r\n\t ')
if (not head):
raise ValueError('%d: empty rule name'%line_num)
elif head[0].isdigit():
raise ValueError('%d: invalid rule name "%s"'%(line_num, head))
elif ('<' in head) or ('>' in head):
raise ValueError('%d: invalid rule name "%s"'%(line_num, head))
try:
pattern = regex_expand(defined, body, guarded = not capture)
except ValueError as e:
raise ValueError('%d: %s'%(line_num, str(e)))
try:
re.compile(pattern)
except re.error:
raise ValueError('%d: invalid pattern "%s"'%(line_num, pattern))
if not capture:
defined[head] = pattern
else:
defined[head] = '(?P<%s>%s)'%(head, pattern)
return defined
#----------------------------------------------------------------------
# predefined patterns
#----------------------------------------------------------------------
PATTERN_WHITESPACE = r'[ \t\r\n]+'
PATTERN_COMMENT1 = r'[#].*'
PATTERN_COMMENT2 = r'\/\/.*'
PATTERN_COMMENT3 = r'\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/'
PATTERN_MISMATCH = r'.'
PATTERN_NAME = r'\w+'
PATTERN_GNAME = r'\w(?:\w|\@)*[\']*'
PATTERN_STRING1 = r"'(?:\\.|[^'\\])*'"
PATTERN_STRING2 = r'"(?:\\.|[^"\\])*"'
PATTERN_NUMBER = r'\d+(\.\d*)?'
PATTERN_CINTEGER = r'(0x)?\d+[uUlLbB]*'
PATTERN_REPLACE = r'(?<!\\)\{\s*[a-zA-Z_]\w*\s*\}'
# PATTERN_CFLOAT = r'\d*(\.\d*)?f*' # bad pattern, don't use
PATTERN_EPSILON = '\u03b5'
PATTERN_GMACRO = r'[%]\s*\w+'
PATTERN_OPERATOR = r'[\+\-\*\/\?\%]'
#----------------------------------------------------------------------
# predefined lexer rules
#----------------------------------------------------------------------
lex_rules = r'''
O = [0-7]
D = [0-9]
NZ = [1-9]
L = [a-zA-Z_]
A = [a-zA-Z_0-9]
H = [a-fA-F0-9]
HP = (0[xX])
E = ([Ee][+-]?{D}+)
P = ([Pp][+-]?{D}+)
FS = (f|F|l|L)
IS = (((u|U)(l|L|ll|LL)?)|((l|L|ll|LL)(u|U)?))
CP = (u|U|L)
SP = (u8|u|U|L)
WHITESPACE = \s+
WS = \s+
EOL = [\n]+
WSEOL = {WS}|{EOL}
COMMENT1 = [#].*
COMMENT2 = \/\/.*
COMMENT3 = \/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/
COMMENT = {COMMENT1}|{COMMENT2}|{COMMENT3}
NAME = {L}{A}*
STRING1 = '(?:\\.|[^'\\])*'
STRING2 = "(?:\\.|[^"\\])*"
STRING = {STRING1}|{STRING2}
DIGIT = [0-9]
DIGITS = {DIGIT}+
HEX = {HP}{H}+
DEC = {NZ}{D}*
INTEGER = ({HEX}|{DEC})(({IS}|{CP})?)
FLOAT = {DIGITS}((\.{DIGITS})?)({E}?)({FS}?)
NUMBER = {INTEGER}|{FLOAT}
'''
#----------------------------------------------------------------------
# build
#----------------------------------------------------------------------
PATTERN = regex_build(lex_rules, capture = False)
#----------------------------------------------------------------------
# internal utils
#----------------------------------------------------------------------
class internal (object):
@staticmethod