-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdrafts.py
2316 lines (1880 loc) · 77.5 KB
/
drafts.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
# -*- coding: utf-8 -*-
"""``metaparse``
A tool for powerful instant parsing.
For typical parsing work, a **Python class[1] declaration** will
already suffice. This pseudo-class includes
- lexical definition
- rule definition
- semantic definition
all-in-one for a grammar.
Example:
.. code:: python
from metaparse import cfg, LALR
# Global stuff
table = {}
class G_Calc(metaclass=cfg):
# ===== Lexical patterns / Terminals =====
IGNORED = r'\s+' # Special token.
EQ = r'='
NUM = r'[0-9]+'
ID = r'[_a-zA-Z]\w*'
POW = r'\*\*', 3 # Can specify token precedence (mainly for LALR).
MUL = r'\*' , 2
ADD = r'\+' , 1
# ===== Syntactic/Semantic rules in SDT-style =====
def assign(ID, EQ, expr): # May rely on global side-effects...
table[ID] = expr
def expr(NUM): # or return local results for purity.
return int(NUM)
def expr(expr_1, ADD, expr_2): # With TeX-subscripts, meaning (expr → expr₁ + expr₂).
return expr_1 + expr_2
def expr(expr, MUL, expr_1): # Can ignore one of the subscripts.
return expr * expr_1
def expr(expr, POW, expr_1):
return expr ** expr_1
Calc = LALR(G_Calc)
Usage:
.. code:: python
>>> Calc.interpret("x = 1 + 2 * 3 ** 4 + 5")
>>> Calc.interpret("y = 3 ** 4 * 5")
>>> Calc.interpret("z = 99")
>>> table
{'x': 168, 'z': 99, 'y': 405}
TODO:
- Support GSS structure for non-deterministic parsing.
- Online-parsing
INFO:
Author: ShellayLee
Mail: [email protected]
License: MIT
.. _Project site:
https://github.com/Shellay
"""
import re
import warnings
import inspect
import ast
import pprint as pp
from collections import OrderedDict
from collections import defaultdict
from collections import namedtuple
from collections import deque
from collections import Iterable
class GrammarWarning(UserWarning):
"""Any way to specify user warning? """
pass
class GrammarError(Exception):
"""Specifies exceptions raised when constructing a grammar."""
pass
class ParserWarning(UserWarning):
"""Any way to specify user warning? """
pass
class ParserError(Exception):
"""Specifies exceptions raised when error occured during parsing."""
pass
# Special lexical element and lexemes
END = 'END'
END_PATTERN_DEFAULT = r'$'
IGNORED = 'IGNORED'
IGNORED_PATTERN_DEFAULT = r'[ \t\n]'
ERROR = 'ERROR'
ERROR_PATTERN_DEFAULT = r'.'
PRECEDENCE_DEFAULT = 1
class Symbol(str):
"""Symbol is a subclass of :str: with unquoted representation. It is
only refered for cleaner presentation.
"""
def __repr__(self):
return self
class Signal(object):
"""Signal is used to denote parsing actions, like some sort of Enum. """
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
DUMMY = Symbol('\0')
EPSILON = Symbol('EPSILON')
PREDICT = Signal('PREDICT')
SHIFT = Signal('SHIFT')
REDUCE = Signal('REDUCE')
ACCEPT = Signal('ACCEPT')
class Token(object):
"""Token object is the lexical element of a grammar, which also
includes the lexeme's position and literal value.
"""
def __init__(self, at, symbol, value):
self.at = at
self.symbol = symbol
self.value = value
def __repr__(self):
return '({}: {})@[{}:{}]'.format(
self.symbol,
repr(self.value),
self.at,
self.at + len(self.value))
def __eq__(self, other):
return self.symbol == other.symbol
def __iter__(self):
yield self.at
yield self.symbol
yield self.value
def is_END(self):
return self.symbol == END
@property
def start(self):
return self.at
@property
def end(self):
return self.at + len(self.value)
class Rule(object):
"""Rule object has the form (LHS -> RHS). It is mainly constructed by
a function, taking its name as LHS and parameter list as RHS. The
function itself is treated as the semantical behavior of this rule.
The equality is needed mainly for detecting rule duplication
during declaring grammar objects.
"""
def __init__(self, func):
self.lhs = func.__name__
rhs = []
# Signature only works in Python 3
# for x in inspect.signature(func).parameters:
for x in inspect.getargspec(func).args:
# Tail digital subscript like xxx_4
s = re.search(r'_(\d+)$', x)
# s = re.search(r'_?(\d+)$', x)
if s:
x = x[:s.start()]
rhs.append(x)
# Make it immutable.
self.rhs = tuple(rhs)
self.seman = func
# Make use of annotations?
# self.anno = func.__annotations__
def __eq__(self, other):
"""Equality of Rule object relies only upon LHS and RHS, not
including semantics! """
if isinstance(other, Rule):
return (self.lhs == other.lhs) and (self.rhs == other.rhs)
else:
return False
def __repr__(self):
"""There are alternative representations for "produces" like '->' or
'::='. Here '=' is used for simplicity.
"""
return '({} = {})'.format(self.lhs, ' '.join(self.rhs))
def __iter__(self):
yield self.lhs
yield self.rhs
@staticmethod
def raw(lhs, rhs, seman):
rl = Rule(seman)
rl.lhs = lhs
rl.rhs = list(rhs)
return rl
def eval(self, *args):
return self.seman(*args)
@property
def size(self):
return len(self.rhs)
@property
def src_info(self):
"""Retrieves source information of this rule's definition for helpful
Traceback information.
"""
co = self.seman.__code__
info = ' File "{}", line {}, in {}\n'.format(
co.co_filename, co.co_firstlineno, self.seman.__module__)
return info
class Item(object):
"""Item contains a pointer to a rule list, a index of rule within that
list and a position indicating current active symbol (namely
actor) in this Item.
"""
def __init__(self, rules, r, pos):
self.rules = rules
self.r = r
self.pos = pos
def __repr__(s):
rule = s.rules[s.r]
lhs = rule.lhs
rhs1 = ' '.join(rule.rhs[:s.pos])
rhs2 = ' '.join(rule.rhs[s.pos:])
return '({} = {}.{})'.format(lhs, rhs1, rhs2)
def __eq__(self, x):
return self.r == x.r and self.pos == x.pos
def __hash__(self):
return hash((self.r, self.pos))
@property
def rule(s):
return s.rules[s.r]
def ended(s):
return s.pos == len(s.rules[s.r].rhs)
def rest(s):
return s.rules[s.r].rhs[s.pos:]
@property
def look_over(s):
return s.rules[s.r].rhs[s.pos+1:]
@property
def prev(s):
return s.rule.rhs[s.pos-1]
@property
def actor(s):
return s.rules[s.r].rhs[s.pos]
@property
def shifted(s):
return Item(s.rules, s.r, s.pos+1)
@property
def unshifted(s):
return s.rules[s.r].rhs[s.pos-1]
@property
def size(s):
return len(s.rules[s.r].rhs)
@property
def target(s):
return s.rules[s.r].lhs
@property
def index_pair(s):
return (s.r, s.pos)
def eval(self, *args):
return self.rule.seman(*args)
# Component for graph structured stacks and prediction trees.
Node = namedtuple('Node', 'value next')
ExpdNode = namedtuple('ExpdNode', 'value forks')
Node.__repr__ \
= lambda s: tuple.__repr__((Symbol(s[0]), s[1]))
ExpdNode.__repr__ \
= lambda s: tuple.__repr__((Symbol(':%s' % s[0]), s[1]))
Bottom = None
class Grammar(object):
def __init__(self, lexes, rules, attrs, prece=None):
"""A grammar object containing lexical rules, syntactic rules and
associating semantics.
Parameters:
:lexes: : odict{str<terminal-name> : str<terminal-pattern>}
A ordered dict representing lexical rules.
:rules: : [Rule]
A list of grammar rules.
:attrs:
A list of extra attributes/methods (may not be advised for usage)
:prece:
A dict of operator's precedence numbers
Notes:
* Checks whether there is a singleton TOP-rule and add such
one if not.
* Needs to check validity and completeness!!
* Undeclared tokens;
* Undeclared nonterminals;
* Unused tokens;
* Unreachable nonterminals/rules;
* FIXME: Cyclic rules; ???
"""
# Operator precedence table may be useful.
self.OP_PRE = dict(prece) if prece else {}
# odict{lex-name: lex-re}
self.terminals = OrderedDict()
for tmn, pat in lexes.items():
# Name trailing with integer subscript indicating
# the precedence.
self.terminals[tmn] = re.compile(pat, re.MULTILINE)
# [<unrepeated-nonterminals>]
self.nonterminals = []
for rl in rules:
if rl.lhs not in self.nonterminals:
self.nonterminals.append(rl.lhs)
# Sort rules with consecutive grouping of LHS.
rules.sort(key=lambda r: self.nonterminals.index(r.lhs))
# This block checks completion of given grammar.
unused_t = set(self.terminals).difference([IGNORED, END, ERROR])
unused_nt = set(self.nonterminals).difference([rules[0].lhs])
# Raise grammar error in case any symbol is undeclared
msg = ''
for r, rl in enumerate(rules):
for j, X in enumerate(rl.rhs):
unused_t.discard(X)
unused_nt.discard(X)
if X not in self.terminals and X not in self.nonterminals:
msg += '\n'.join([
'Undeclared symbol:',
"@{}`th symbol '{}' in {}`th rule {}. Source info:".format(j, X, r, rl),
rl.src_info,
])
if msg:
msg += '\n...Failed to construct the grammar.'
raise GrammarError(msg)
# Raise warnings in case any symbol is unused.
for t in unused_t:
# warnings.warn('Warning: referred terminal symbol {}'.format(t))
warnings.warn('Unreferred terminal symbol {}'.format(repr(t)))
for nt in unused_nt:
# warnings.warn('Warning: referred nonterminal symbol {}'.format(nt))
warnings.warn('Unreferred nonterminal symbol {}'.format(repr(nt)))
# Generate top rule as Augmented Grammar only if
# the singleton top rule is not explicitly given.
fst_rl = rules[0]
if len(fst_rl.rhs) != 1 or 1 < [rl.lhs for rl in rules].count(fst_rl.lhs):
tp_lhs = "{}^".format(fst_rl.lhs)
tp_rl = Rule.raw(
tp_lhs,
(fst_rl.lhs, ),
lambda x: x)
self.nonterminals.insert(0, tp_lhs)
rules = [tp_rl] + rules
# Register other attributes/methods (should not be relied on).
# self.attrs = attrs
self.rules = rules
self.symbols = self.nonterminals + [a for a in lexes if a != END]
# Top rule of Augmented Grammar.
self.top_rule = self.rules[0]
self.top_symbol = self.top_rule.lhs
# Helper for fast accessing with Trie like structure.
self._ngraph = defaultdict(list)
for r, rl in enumerate(self.rules):
self._ngraph[rl.lhs].append((r, rl))
# Prepare useful information for parsing.
self._calc_nullable()
self._calc_pred_trees()
def __repr__(self):
return 'Grammar\n{}\n'.format(pp.pformat(self.rules))
def __getitem__(self, X):
"""Note retrieved rules are enumerated with original indices."""
if X in self._ngraph:
return self._ngraph[X]
else:
raise ValueError('No such LHS {} in grammar.'.format(repr(X)))
def item(G, r, pos):
"""Create a pair of integers indexing the rule and active position.
"""
return Item(G.rules, r, pos)
def pred_tree(G, ntml, bottom=None):
"""Build a prediction tree for the given :ntml:. A prediction tree
concludes all information about FIRST and NULLABLE.
This tree may contain cycles due to LOOP in the grammar.
Conceptually, this tree/graph is represented by a list of leaf
nodes, namely :top list:, of which each one points to a parent
node.
Once the tree is built, the FIRST set is exactly the terminal
node values in this top list. A :expanded node: appears in the
top list iff it is nullable. If there is a path from the top
list to the bottom passing a sequence of :expanded node:s,
then this nonterminal is transitively nullable.
For example, given the grammar
S = A; A = B c; B = S c d
The closure for kernel item (S = .A):
S = .A; A = .B c; B = .S c d
Treat them in reversed direction, where >> means completion:
S $ >> {ACCEPT} ; A >> S ; B c >> A ; S c A >> B
S >> $
A >> [S] >> $
B >> c >> [A] >> [S] >> $
S >> c >> A >> [B] >> c >> [A] >> [S] >> $
But S already gets expanded, link it back.
c >> A >> [B] >> c >> [A] >> [S] >> $
| |
--------------<<---------------
It is teasing that the 'prediction graph' is indeed a
'completion graph', denoting paths for completion.
"""
global PREDICT, REDUCE
# None for root/bottom.
# - should bottom be mutable like [] to allow transplant?
toplst = [Node(ntml, bottom)]
expdd = {}
z = 0
while z < len(toplst):
n = (X, nxt) = toplst[z]
if X in G.nonterminals:
if isinstance(n, ExpdNode):
assert X in G.NULLABLE
z += 1
# Skip and append
# for fk in n.forks:
# if fk not in toplst:
# if fk is not bottom:
# toplst.append(fk)
else:
toplst.pop(z) # Discard normal nonterminal node
if X in expdd:
assert isinstance(expdd[X], ExpdNode)
expdd[X].forks.append(nxt)
else:
# New expanded node - shared by alternative rules.
enxt = expdd[X] = ExpdNode(X, [nxt])
for r, rl in G[X]:
nxt1 = enxt # Share this expanded.
for sub in reversed(rl.rhs):
# New normal node.
nxt1 = Node(sub, nxt1)
# If `rl` is a null-rule, the expanded node
# gets appended.
toplst.append(nxt1)
else:
# Path led by terminal stays.
z += 1
assert all(isinstance(nd, ExpdNode) or nd.value in G.terminals for nd in toplst)
return toplst
def _calc_nullable(G):
# There may be multiple alternative nullable rules
# for the same nonterminal, use a ddict<list> to
# remenber them all.
G.NULLABLE = defaultdict(list)
candis = []
# Find order-1 nullable.
for rl in G.rules:
lhs, rhs = rl
if not rhs:
G.NULLABLE[lhs].append(rl)
elif all(X in G.nonterminals for X in rhs):
candis.append(rl)
# Find order-n nullable use stupid but clear More-Pass.
while 1:
has_new = False
for rl in candis:
lhs, rhs = rl
if all(X in G.NULLABLE for X in rhs):
if rl not in G.NULLABLE[lhs]:
G.NULLABLE[lhs].append(rl)
has_new = True
break
if not has_new:
break
# Compute singly transitive derivations
G.DERIV1 = defaultdict(set)
for lhs, rhs in G.rules:
for i, X in enumerate(rhs):
if X in G.nonterminals:
if all(Y in G.NULLABLE for Y in rhs[:i] + rhs[i+1:]):
G.DERIV1[lhs].add(X)
# Compute LOOP clusters
def _calc_pred_trees(G):
G.PRED_TREE = {}
G.FIRST = {}
for nt in reversed(G.nonterminals):
pt = G.pred_tree(nt)
G.PRED_TREE[nt] = pt
G.FIRST[nt] = f = set()
for nd in pt:
if isinstance(nd, ExpdNode):
f.add(EPSILON)
elif isinstance(nd, Node):
assert nd.value in G.terminals
f.add(nd.value)
else:
raise ValueError('Not valid elem in toplist.')
def first_of_seq(G, seq, tail=DUMMY):
"""Find the FIRST set of a sequence of symbols. This relies
on the precompulated order-n nullables.
:seq: A list of strings
"""
# FIXME: This relies on higher-order NULLABLE!
assert not isinstance(seq, str)
fs = set()
for X in seq:
if X in G.nonterminals:
fs.update(G.FIRST[X])
else:
fs.add(X)
if X not in G.NULLABLE:
fs.discard(EPSILON)
return fs
fs.discard(EPSILON)
# Note :tail: can also be EPSILON
fs.add(tail)
return fs
def is_nullable_seq(G, seq):
return all(X in G.NULLABLE for X in seq)
def closure(G, I):
"""Naive CLOSURE calculation without lookaheads.
Fig 4.32:
SetOfItems CLOSURE(I)
J = I.copy()
for (A -> α.Bβ) in J
for (B -> γ) in G:
if (B -> γ) not in J:
J.add((B -> γ))
return J
"""
C = I[:]
z = 0
while z < len(C):
itm = C[z]
if not itm.ended():
if itm.actor in G.nonterminals:
for j, jrl in G[itm.actor]:
jtm = G.item(j, 0)
if jtm not in C:
C.append(jtm)
z += 1
return C
def closure1_with_lookahead(G, item, a):
"""Fig 4.40 in Dragon Book.
CLOSURE(I)
J = I.copy()
for (A -> α.Bβ, a) in J:
for (B -> γ) in G:
for b in FIRST(βa):
if (B -> γ, b) not in J:
J.add((B -> γ, b))
return J
This can be done before calculating LALR-Item-Sets, thus avoid
computing closures repeatedly by applying the virtual DUMMY
lookahead(`#` in the dragonbook). Since this lookahead must
not be shared by any symbols within any instance of Grammar, a
special value is used as the dummy(Not including None, since
None is already used as epsilon in FIRST set).
For similar implementations within lower-level language like
C, this value can be replaced by any special number which
would never represent a unicode character.
"""
C = [(item, a)]
z = 0
while z < len(C):
itm, a = C[z]
if not itm.ended():
if itm.actor in G.nonterminals:
for j, jrl in G[itm.actor]:
for b in G.first_of_seq(itm.look_over, a):
jtm = G.item(j, 0)
if (jtm, b) not in C:
C.append((jtm, b))
z += 1
return C
def tokenize(G, inp, with_end):
"""Perform lexical analysis with given input string and yield matched
tokens with defined lexical patterns.
* Ambiguity is resolved by the definition order.
It must be reported if `pos` is not strictly increasing when
any of the valid lexical pattern matches zero-length string!!
This might lead to non-termination.
Here only matches with positive length is retrieved, though
expresiveness may be harmed by this restriction.
"""
pos = 0
while pos < len(inp):
for lex, rgx in G.terminals.items():
m = rgx.match(inp, pos=pos)
# The first match with non-zero length is yielded.
if m and len(m.group()) > 0:
break
if m and lex == IGNORED:
at, pos = m.span()
elif m and lex != IGNORED:
at, pos = m.span()
yield Token(at, lex, m.group())
else:
# Report unrecognized Token here!
at = pos
pos += 1
yield Token(at, ERROR, inp[at])
if with_end:
yield Token(pos, END, END_PATTERN_DEFAULT)
def find_loop(G, ntml):
"""LOOP is the case that for some terminal S there is
S => ... => S
(not including partial LOOP like S => ... => S a)
Some properties:
- Along the path the rule must be ALL nonterminals;
- If S => .. => A and some non-singleton rule exits (A = B C D),
there LOOP may exits only when all except one of {B, C, D} are
nullable.
- Thus LOOP can be found by testing reachability through
single-derivations.
"""
paths = [[ntml]]
while paths:
path = paths.pop()
act = path[-1]
# Whole cycle from start.
if act == path[0] and len(path) > 1:
# cluster.update(path)
yield path
# Parital cycle linking to middle.
elif act in path[:-1]:
# j = path.index(act)
# yield path[j:]
pass
# Still no cycle, try explore further.
else:
for nxt in G.DERIV1[act]:
paths.append(path + [nxt])
class assoclist(list):
"""This class intends to be cooperated with metaclass definition
through __prepare__ method. When returned in __prepare__, it will
be used by registering class-level method definitions. Since it
overrides the setter and getter of default `dict` supporting class
definition, it allows repeated method declaration to be registered
sequentially in a list. As the result of such class definition,
declarated stuff can be then extracted in the __new__ method in
metaclass definition.
Assoclist :: [(<key>, <value>)]
"""
def __setitem__(self, k, v):
"""Overides alist[k] = v"""
ls = super(assoclist, self)
ls.append((k, v))
def __getitem__(self, k0):
"""Overrides: ys = alist[k]"""
vs = [v for k, v in self if k == k0]
if vs:
return vs[0]
else:
raise KeyError('No such attribute.')
def items(self):
"""Yield key-value pairs."""
for k, v in self:
yield (k, v)
class cfg(type):
"""This metaclass performs accumulation for all declared grammar
lexical and syntactical rules at class level, where declared
variables are registered as lexical elements and methods are
registered as Rule objects defined above.
"""
@staticmethod
def read_from_raw_lists(*lsts):
"""Extract named objects from a sequence of lists and translate some
of them into something necessary for building a grammar
object.
Note the ORDER of registering lexical rules matters. Here it is assumed
the k-v pairs for such rules preserve orignial declaration order.
"""
lexes = []
lexpats = []
rules = []
prece = {}
attrs = []
for lst in lsts:
for k, v in lst:
# Built-ins are of no use
if k.startswith('__') and k.endswith('__'):
continue
# Handle implicit rule declaration through methods.
elif callable(v):
r = Rule(v)
if r in rules:
raise GrammarError('Repeated declaration of Rule {}.\n{}'.format(r, r.src_info))
rules.append(r)
# Lexical declaration without precedence
elif isinstance(v, str):
if k in lexes:
raise GrammarError('Repeated declaration of lexical symbol {}.'.format(k))
lexes.append(k)
lexpats.append(v)
# With precedence
elif isinstance(v, tuple):
assert len(v) == 2, 'Lexical pattern as tuple should be of length 2.'
assert isinstance(v[0], str) and isinstance(v[1], int), \
'Lexical pattern as tuple should be of type (str, int)'
if k in lexes:
raise GrammarError('Repeated declaration of lexical symbol {}.'.format(k))
lexes.append(k)
lexpats.append(v[0])
prece[k] = v[1]
# Handle normal private attributes/methods.
else:
attrs.append((k, v))
# Default matching order of special patterns:
# Always match IGNORED secondly after END, if it is not specified;
if IGNORED not in lexes:
# lexes.move_to_end(IGNORED, last=False)
lexes.append(IGNORED)
lexpats.append(IGNORED_PATTERN_DEFAULT)
# Always match END first
if END not in lexes:
lexes.insert(0, END)
lexpats.insert(0, END_PATTERN_DEFAULT)
else:
i_e = lexes.index(END)
lexes.insert(0, lexes.pop(i_e))
lexpats.insert(0, lexpats.pop(i_e))
# Always match ERROR at last
# It may be overriden by the user.
if ERROR not in lexes:
# lexes[ERROR] = ERROR_PATTERN_DEFAULT
lexes.append(ERROR)
lexpats.append(ERROR_PATTERN_DEFAULT)
return Grammar(OrderedDict(zip(lexes, lexpats)), rules, attrs, prece)
@classmethod
def __prepare__(mcls, n, bs, **kw):
return assoclist()
def __new__(mcls, n, bs, accu):
"""After gathering definition of grammar elements, reorganization
and first checkings are done in this method, resulting in creating
a Grammar object.
"""
return cfg.read_from_raw_lists(accu)
@staticmethod
def extract_list(decl):
"""Retrieve structural information of the function :decl: (i.e. the
body and its components IN ORDER). Then transform these
information into a list of lexical elements and rules as well
as semantics.
"""
import textwrap
# The context for the rule semantics is `decl`'s belonging
# namespace, here `__globals__`.
glb_ctx = decl.__globals__
# The local context for registering a function definition
# by `exec`.
lcl_ctx = {}
# Prepare the source. If the `decl` is a method, the source
# then contains indentation spaces thus should be dedented in
# order to be parsed independently. `textwrap.dedent`
# performs dedenation until no leading spaces.
src = inspect.getsource(decl)
src = textwrap.dedent(src)
# Parse the source to Python syntax tree.
t = ast.parse(src)
# Something about :ast.parse: and :compile: with
# - literal string code;
# - target form
# - target mode
# e = ast.parse("(3, x)", mode='eval')
# e = compile("(3, x)", '<ast>', 'eval')
# s = ast.parse("def foo(): return 123", mode='exec')
# s = compile("def foo(): return 123", '<ast>', 'exec')
lst = []
for obj in t.body[0].body:
if isinstance(obj, ast.Assign):
k = obj.targets[0].id
ov = obj.value
# :ast.literal_eval: evaluates an node instantly!
try:
v = ast.literal_eval(ov)
lst.append((k, v))
# Some context values may be used for defining
# following functions.
lcl_ctx[k] = v
except ValueError:
pass
elif isinstance(obj, ast.FunctionDef):
name = obj.name
# Conventional fix
ast.fix_missing_locations(obj)
# :ast.Module: is the unit of program codes.
# FIXME: Is :md: necessary??
md = ast.Module(body=[obj])
# Compile a module-ast with '<ast>' mode targeting
# :exec:.
code = compile(md, '<ast>', 'exec')
# Register function into local context, within the
# circumference of global context.
exec(code, glb_ctx, lcl_ctx)
func = lcl_ctx.pop(name)
lst.append((name, func))
else:
# Ignore structures other than :Assign: and :FuncionDef:
pass
return lst
@staticmethod
def v2(func):
lst = cfg.extract_list(func)