-
Notifications
You must be signed in to change notification settings - Fork 7
/
Core.py
2522 lines (2321 loc) · 82.6 KB
/
Core.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
#-------------------------------------------------------------------------
#Core.py -- the computation routines
#Compiler Generator Coco/R,
#Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz
#extended by M. Loeberbauer & A. Woess, Univ. of Linz
#ported from Java to Python by Ronald Longo
#
#This program is free software; you can redistribute it and/or modify it
#under the terms of the GNU General Public License as published by the
#Free Software Foundation; either version 2, or (at your option) any
#later version.
#
#This program is distributed in the hope that it will be useful, but
#WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
#or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
#for more details.
#
#You should have received a copy of the GNU General Public License along
#with this program; if not, write to the Free Software Foundation, Inc.,
#59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#As an exception, it is allowed to write an extension of Coco/R that is
#used as a plugin in non-free software.
#
#If not otherwise stated, any source coe generated by Coco/R (other than
#Coco/R itself) does not fall under the GNU General Public License.
#-------------------------------------------------------------------------*/
import os.path
import sys
import copy
from optparse import OptionParser
from Trace import Trace
from Errors import Errors
from CharClass import CharClass
class Comment( object ):
''' info about comment syntax'''
first = None # list of comments
def __init__( self, frm, to, nested):
assert isinstance(frm,Node)
assert isinstance(to,Node)
assert isinstance(nested,bool)
self.start = self.Str(frm)
self.stop = self.Str(to)
self.nested = nested
self.next = Comment.first
Comment.first = self
def Str(self, p):
assert isinstance(p,Node)
s = '' # StringBuffer
while p is not None:
if p.typ == Node.chr:
s += chr(p.val)
elif p.typ == Node.clas:
st = CharClass.Set(p.val) # BitSet
if len(st) != 1:
Errors.SemErr("character set contains more than 1 character")
s += chr(min(st))
#s += chr(st.First())
else:
Errors.SemErr("comment delimiters may not be structured")
p = p.next
if len(s) == 0 or len(s) > 2:
Errors.SemErr("comment delimiters must be 1 or 2 characters long")
s = '?'
return s
class Symbol( object ):
terminals = [ ] # of Symbol
pragmas = [ ]
nonterminals = [ ]
# token kinds
fixedToken = 0 # e.g. 'a' ('b' | 'c') (structure of literals)
classToken = 1 # e.g. digit {digit} (at least one char class)
litToken = 2 # e.g. "while"
classLitToken = 3 # e.g. letter {letter} but without literals that have the same structure
def __init__( self, typ, name, line ):
assert isinstance( typ, int )
assert isinstance( name, (str,unicode) )
assert isinstance( line, int )
self.n = 0 # symbol number
self.typ = 0 # t, nt, pr, unknown, rslv
self.name = 0 # symbol name
self.graph = None # Node, nt: to first node of syntax graph
self.tokenKind = 0 # t: token kind (fixedToken, classToken, ...)
self.deletable = False # nt: true if nonterminal is deletable
self.firstReady = False # nt: true if terminal start symbols have already been computed
self.first = None # set, nt: terminal start symbols
self.follow = None # set, nt: terminal followers
self.nts = None # set, nt: nonterminals whose followers have to be added to this sym
self.line = 0 # source text line number of item in this node
self.attrPos = None # Position, nt: position of attributes in source text (or None)
self.semPos = None # Position, pr: pos of semantic action in source text (or None)
# nt: pos of local declarations in source text (or None)
self.retType = '' # AH - nt: Type of output attribute (or None)
self.retVar = None # str - AH - nt: Name of output attribute (or None)
self.symName = None # str, symbolic name /* pdt */
if len(name) == 2 and name[0] == '"':
Errors.SemErr( 'empty token not allowed' )
name = '???'
self.typ = typ
self.name = name
self.line = line
if typ == Node.t:
self.n = len(Symbol.terminals)
Symbol.terminals.append( self )
elif typ == Node.pr:
Symbol.pragmas.append( self )
elif typ == Node.nt:
self.n = len(Symbol.nonterminals)
Symbol.nonterminals.append( self )
@staticmethod
def Find( name ):
assert isinstance( name, ( str, unicode ) )
for s in Symbol.terminals:
if s.name == name:
return s
for s in Symbol.nonterminals:
if s.name == name:
return s
return None
def compareTo( self, x ):
assert isinstance( x, Symbol )
return self.name.__cmp__( x.name )
class Target( object ):
''' set of states that are reached by an action'''
def __init__( self, s ):
assert isinstance( s, State )
self.state = s # target state
self.next = None # Target instance
class Node( object ):
nodes = [ ]
nTyp = [" ", "t ", "pr ", "nt ", "clas", "chr ", "wt ", "any ", "eps ",
"sync", "sem ", "alt ", "iter", "opt ", "rslv"]
# constants for node kinds
t = 1 # terminal symbol
pr = 2 # pragma
nt = 3 # nonterminal symbol
clas = 4 # character class
chr = 5 # character
wt = 6 # weak terminal symbol
any = 7 #
eps = 8 # empty
sync = 9 # synchronization symbol
sem = 10 # semantic action: (. .)
alt = 11 # alternative: |
iter = 12 # iteration: { }
opt = 13 # option: [ ]
rslv = 14 # resolver expr /* ML */ /* AW 03-01-13 renamed slv --> rslv */
normalTrans = 0 # transition codes
contextTrans = 1
def __init__( self, typ, symOrNodeOrInt, line=None ):
assert isinstance( typ, int )
assert isinstance( symOrNodeOrInt, Symbol ) or isinstance( symOrNodeOrInt, Node ) or isinstance( symOrNodeOrInt, int ) or (symOrNodeOrInt is None)
assert isinstance( line, int ) or (line is None)
self.n = 0 # node number
self.typ = 0 # t, nt, wt, chr, clas, any, eps, sem, sync, alt, iter, opt, rslv
self.next = None # Node, to successor node
self.down = None # Node, alt: to next alternative
self.sub = None # Node, alt, iter, opt: to first node of substructure
self.up = False # true: "next" leads to successor in enclosing structure
self.sym = None # Symbol, nt, t, wt: symbol represented by this node
self.val = 0 # chr: ordinal character value
# clas: index of character class
self.code = 0 # chr, clas: transition code
self.set = None # set, any, sync: the set represented by this node
self.pos = None # Position, nt, t, wt: pos of actual attributes
# sem: pos of semantic action in source text
self.line = 0 # source text line number of item in this node
self.state = None # State, DFA state corresponding to this node
# (only used in DFA.ConvertToStates)
self.retVar= None # str, nt: name of output attribute (or None)
if isinstance(symOrNodeOrInt, int) and isinstance(line, int):
self.typ = typ
self.sym = None
self.line = line
self.n = len(Node.nodes)
Node.nodes.append( self )
self.val = symOrNodeOrInt
elif line is None:
self.typ = typ
self.sym = None
self.line = 0
self.n = len(Node.nodes)
Node.nodes.append( self )
self.sub = symOrNodeOrInt
else:
self.typ = typ
self.sym = symOrNodeOrInt
self.line = line
self.n = len(Node.nodes)
Node.nodes.append( self )
@staticmethod
def DelGraph( p ):
return (p is None) or Node.DelNode(p) and Node.DelGraph(p.next)
@staticmethod
def DelSubGraph( p ):
return p is None or Node.DelNode(p) and (p.up or Node.DelSubGraph(p.next))
@staticmethod
def DelAlt( p ):
return p is None or Node.DelNode(p) and (p.up or Node.DelAlt(p.next))
@staticmethod
def DelNode( p ):
if p.typ == Node.nt:
return p.sym.deletable
elif p.typ == Node.alt:
return Node.DelAlt( p.sub ) or p.down != None and Node.DelAlt(p.down)
else:
return p.typ in ( Node.eps, Node.iter, Node.opt, Node.sem, Node.sync, Node.rslv )
#----------------- for printing ----------------------
@staticmethod
def Ptr( p, up ):
assert isinstance( p, Node ) or ( p is None )
assert isinstance( up, bool )
if p is None:
return 0
elif up:
return -p.n
else:
return p.n
@staticmethod
def Pos( pos ):
if pos is None:
return ' '
else:
return Trace.formatString( str(pos.beg), 5 )
@staticmethod
def Name( name ):
assert isinstance( name, (str,unicode) )
return (name + ' ')[0:12]
# found no simpler way to get the first 12 characters of the name
# padded with blanks on the right
@staticmethod
def PrintNodes( ):
Trace.WriteLine("Graph nodes:")
Trace.WriteLine("----------------------------------------------------")
Trace.WriteLine(" n type name next down sub pos line")
Trace.WriteLine(" val code")
Trace.WriteLine("----------------------------------------------------")
for p in Node.nodes:
Trace.Write(str(p.n), 4)
Trace.Write(" " + Node.nTyp[p.typ] + " ")
if p.sym is not None:
Trace.Write(Node.Name(p.sym.name), 12)
Trace.Write(" ")
elif p.typ == Node.clas:
c = CharClass.classes[ p.val ]
Trace.Write(Node.Name(c.name), 12)
Trace.Write(" ")
else:
Trace.Write(" ")
Trace.Write(str(Node.Ptr(p.next, p.up)), 5)
Trace.Write(" ")
if p.typ in ( Node.t, Node.nt, Node.wt ):
Trace.Write(" ")
Trace.Write(Node.Pos(p.pos), 5)
elif p.typ == Node.chr:
Trace.Write(str(p.val), 5)
Trace.Write(" ")
Trace.Write(str(p.code), 5)
Trace.Write(" ")
elif p.typ == Node.clas:
Trace.Write(" ")
Trace.Write(str(p.code), 5)
Trace.Write(" ")
elif p.typ in ( Node.alt, Node.iter, Node.opt ):
Trace.Write(str(Node.Ptr(p.down, False)), 5)
Trace.Write(" ")
Trace.Write(str(Node.Ptr(p.sub, False)), 5)
Trace.Write(" ")
elif p.typ == Node.sem:
Trace.Write(" ")
Trace.Write(Node.Pos(p.pos), 5)
elif p.typ in ( Node.eps, Node.any, Node.sync ):
Trace.Write(" ")
Trace.WriteLine(str(p.line), 5);
Trace.WriteLine();
class State( object ):
''' state of finite automaton'''
lastNr = 0 # highest state number
def __init__( self ):
self.nr = 0 # state number
self.firstAction = None # Action, to first action of this state
self.endOf = None # Symbol, recognized token if state is final
self.ctx = False # true if state is reached via contextTrans
self.next = None # State
State.lastNr += 1
self.nr = State.lastNr
def AddAction(self, act):
assert isinstance(act,Action)
lasta = None # Action
a = self.firstAction # Action
while (a is not None) and (act.typ >= a.typ):
lasta = a
a = a.next
# collecting classes at the beginning gives better performance
act.next = a
if a == self.firstAction:
self.firstAction = act
else:
lasta.next = act
def DetachAction(self, act):
assert isinstance(act,Action)
lasta = None # Action
a = self.firstAction # Action
while (a is not None) and a != act:
lasta = a
a = a.next
if a is not None:
if a == self.firstAction:
self.firstAction = a.next
else:
lasta.next = a.next
def TheAction(self, ch):
assert isinstance(ch,(str,unicode))
if isinstance( ch, (str,unicode) ):
ch = ord(ch)
a = self.firstAction
while a is not None:
if a.typ == Node.chr and ch == a.sym:
return a
elif a.typ == Node.clas:
s = CharClass.Set(a.sym)
if ch in s:
return a
a = a.next
return None
def MeltWith(self, s):
'''copy actions of s to state'''
assert isinstance( s, State )
action = s.firstAction
while action is not None:
a = Action(action.typ, action.sym, action.tc)
a.AddTargets(action)
self.AddAction(a)
action = action.next
class Action( object ):
''' action of finite automaton'''
def __init__( self, typ, sym, tc):
assert isinstance(typ,int)
assert isinstance(sym,int)
assert isinstance(tc,int)
self.typ = typ # type of action symbol: clas, chr
self.sym = sym # action symbol
self.tc = tc # transition code: normalTrans, contextTrans
self.target = None # Target # states reached from this action
self.next = None # Action
def AddTarget(self,t):
''' add t to the action.targets'''
assert isinstance( t, Target )
last = None # Target
p = self.target # Target
while (p is not None) and (t.state.nr >= p.state.nr):
if t.state == p.state:
return
last = p
p = p.next
t.next = p
if (p == self.target):
self.target = t
else:
last.next = t
def AddTargets(self, a):
'''add copy of a.targets to action.targets'''
assert isinstance( a, Action )
p = a.target
while p is not None:
t = Target(p.state)
self.AddTarget(t)
p = p.next
if a.tc == Node.contextTrans:
self.tc = Node.contextTrans
def Symbols(self):
if self.typ == Node.clas:
s = copy.copy(CharClass.Set(self.sym))
else:
s = set( )
s.add(self.sym)
return s
def ShiftWith(self,s):
if len(s) == 1:
self.typ = Node.chr
self.sym = min(s) #.First()
else:
c = CharClass.Find(s)
if c is None:
c = CharClass("#", s) # class with dummy name
self.typ = Node.clas
self.sym = c.n
def GetTargetStates(self,param):
assert isinstance( param, list ) # Object[]
# compute the set of target states
targets = set( ) # BitSet
endOf = None # Symbol
ctx = False # boolean
t = self.target
while t is not None:
stateNr = t.state.nr # int
if stateNr <= DFA.lastSimState:
targets.add(stateNr)
else:
try:
targets |= Melted.Set(stateNr)
except:
print sys.exc_info()[1]
Errors.count += 1
if t.state.endOf is not None:
if (endOf is None) or (endOf == t.state.endOf):
endOf = t.state.endOf
else:
print "Tokens " + endOf.name + " and " + t.state.endOf.name + " cannot be distinguished"
Errors.count += 1
if t.state.ctx:
ctx = True
t = t.next
param[0] = targets
param[1] = endOf
return ctx
class Melted( object ): # info about melted states
first = None # Melted instance, head of melted state list
def __init__( self, st, state ):
assert isinstance( st, set )
assert isinstance( state, State )
self.set = st # set of old states
self.state = state # new state
self.next = Melted.first # Melted instance
Melted.first = self
@staticmethod
def Set( nr ):
assert isinstance( nr, int )
m = Melted.first
while m is not None:
if m.state.nr == nr:
return m.set
else:
m = m.next
raise RuntimeError( '-- compiler error in Melted.Set()' )
@staticmethod
def StateWithSet( s ):
assert isinstance( s, set )
m = Melted.first
while m is not None:
if s == m.set: #s.equals( m.set ):
return m
m = m.next
return None
class Graph( object ):
dummyNode = Node( Node.eps, None, 0 )
def __init__( self, p=None ):
assert isinstance(p, Node) or (p is None)
self.l = p #Node, left end of graph = head
self.r = p #Node, right end of graph = list of nodes to be linked to successor graph
@staticmethod
def MakeFirstAlt( g ):
assert isinstance( g, Graph )
g.l = Node(Node.alt, g.l)
g.l.line = g.l.sub.line # make line available for error handling */
g.l.next = g.r
g.r = g.l
@staticmethod
def MakeAlternative( g1, g2 ):
assert isinstance( g1, Graph )
assert isinstance( g2, Graph )
g2.l = Node(Node.alt, g2.l)
g2.l.line = g2.l.sub.line
p = g1.l
while p.down is not None:
p = p.down
p.down = g2.l
p = g1.r
while p.next is not None:
p = p.next
p.next = g2.r
@staticmethod
def MakeSequence( g1, g2 ):
assert isinstance( g1, Graph)
assert isinstance( g2, Graph)
p = g1.r.next
g1.r.next = g2.l # link head node
while p is not None: # link substructure
q = p.next
p.next = g2.l
p.up = True
p = q
g1.r = g2.r
@staticmethod
def MakeIteration( g ):
assert isinstance(g, Graph)
g.l = Node(Node.iter, g.l)
p = g.r
g.r = g.l
while p is not None:
q = p.next
p.next = g.l
p.up = True
p = q
@staticmethod
def MakeOption( g ):
assert isinstance( g, Graph)
g.l = Node(Node.opt, g.l)
g.l.next = g.r
g.r = g.l
@staticmethod
def Finish( g ):
assert isinstance( g, Graph)
p = g.r
while p is not None:
q = p.next
p.next = None
p = q
@staticmethod
def SetContextTrans( p ):
'''set transition code in the graph rooted at p'''
assert isinstance(p, Node) or (p is None)
DFA.hasCtxMoves = True
while p is not None:
if p.typ == Node.chr or p.typ == Node.clas:
p.code = Node.contextTrans
elif p.typ == Node.opt or p.typ == Node.iter:
Graph.SetContextTrans(p.sub)
elif p.typ == Node.alt:
Graph.SetContextTrans(p.sub)
Graph.SetContextTrans(p.down)
if p.up:
break
p = p.next
@staticmethod
def DeleteNodes( ):
Node.nodes = [ ]
Graph.dummyNode = Node(Node.eps, None, 0)
@staticmethod
def StrToGraph( st ):
assert isinstance(st,(str,unicode))
s = DFA.Unescape(st[1:-1])
if len(s) == 0:
Errors.SemErr("empty token not allowed")
g = Graph()
g.r = Graph.dummyNode
for i in xrange(0, len(s)):
p = Node(Node.chr, ord(s[i]), 0)
g.r.next = p
g.r = p
g.l = Graph.dummyNode.next
Graph.dummyNode.next = None
return g
class UserDefinedTokenName(object):
NameTab = [ ]
alias = ''
name = ''
def __init__(self, alias, name):
assert isinstance(alias, str)
assert isinstance(name, str)
self.alias = alias
self.name = name
UserDefinedTokenName.NameTab.append(self)
class Tab:
semDeclPos = None #Position, position of global semantic declarations
ignored = None #Set, characters ignored by the scanner
ddt = [ False ] * 20 # boolean[20], debug and test switches
gramSy = None #Symbol, root nonterminal; filled by ATG
eofSy = None #Symbol, end of file symbol
noSym = None #Symbol, used in case of an error
allSyncSets = None #set, union of all synchronisation sets
nsName = '' #namespace for generated files
frameDir = None #directory containing the frame files
literals = { } #Hashtable, symbols that are used as literals
visited = None #set, mark list for graph traversals
curSy = None #Symbol, current symbol in computation of sets
@staticmethod
def parseArgs( argv, testArgCt=False ):
usage = 'usage: %prog [options] filename.atg'
optParser = OptionParser( usage )
optParser.add_option( '-a', '-A', dest='traceAutomaton',
action='store_true', default=False,
help='Include automaton tracing in the trace file.' )
optParser.add_option( '-c', '-C', dest='generateDriver',
action='store_true', default=False,
help='Generate a main compiler source file.' )
optParser.add_option( '-f', '-F', dest='firstAndFollow',
action='store_true', default=False,
help='Include first & follow sets in the trace file.' )
optParser.add_option( '-g', '-G', dest='syntaxGraph',
action='store_true', default=False,
help='Include syntax graph in the trace file.' )
optParser.add_option( '-i', '-I', dest='traceComputations',
action='store_true', default=False,
help='Include a trace of the computations for first sets in the trace file.' )
optParser.add_option( '-j', '-J', dest='listAnyAndSync',
action='store_true', default=False,
help='Inclue a listing of the ANY and SYNC sets in the trace file.' )
optParser.add_option( '-m', '-M', dest='mergeErrors',
action='store_true', default=False,
help='Merge error messages in the source listing.' )
optParser.add_option( '-n', '-N', dest='tokenNames',
action='store_true', default=False,
help='Generate token names in the source listing.' )
optParser.add_option( '-p', '-P', dest='statistics',
action='store_true', default=False,
help='Include a listing of statistics in the trace file.' )
optParser.add_option( '-r', '-R', dest='frameFileDir',
default=None,
help='Use scanner.frame and parser.frame in directory DIR.', metavar='DIR' )
optParser.add_option( '-s', '-S', dest='symbolTable',
action='store_true', default=False,
help='Include the symbol table listing in the trace file.' )
optParser.add_option( '-t', '-T', dest='testOnly',
action='store_true', default=False,
help='Test the grammar only, don\'t generate any files.' )
optParser.add_option( '-x', '-X', dest='crossReferences',
action='store_true', default=False,
help='Include a cross reference listing in the trace file.' )
if argv is None:
options, args = optParser.parse_args( )
else:
options, args = optParser.parse_args( argv )
Tab.SetDDT( options )
if testArgCt:
if len(args) != 2:
optParser.print_help( )
sys.exit( )
return options,args
#---------------------------------------------------------------------
# Symbol set computations
#---------------------------------------------------------------------
@staticmethod
def First0( p, mark ):
'''Computes the first set for the given Node.'''
assert isinstance( p, Node ) or (p is None)
assert isinstance( mark, set )
fs = set( )
while (p is not None) and not (p.n in mark):
mark.add(p.n)
if p.typ == Node.nt:
if p.sym.firstReady:
fs |= p.sym.first
else:
fs |= Tab.First0( p.sym.graph, mark )
elif p.typ in ( Node.t, Node.wt ):
fs.add(p.sym.n)
elif p.typ == Node.any:
fs |= p.set
elif p.typ == Node.alt:
fs |= Tab.First0(p.sub, mark)
fs |= Tab.First0(p.down, mark)
elif p.typ in ( Node.iter, Node.opt ):
fs |= Tab.First0(p.sub, mark)
if not Node.DelNode(p):
break
p = p.next
return fs
@staticmethod
def First( p ):
assert isinstance( p, Node) or (p is None)
fs = Tab.First0(p, set( ) )
if Tab.ddt[3]:
Trace.WriteLine( )
if p is not None:
Trace.WriteLine("First: node = " + str(p.n) )
else:
Trace.WriteLine("First: node = None");
Tab.PrintSet(fs,0)
return fs
@staticmethod
def CompFirstSets( ):
assert isinstance( Symbol.nonterminals, list)
nt = Symbol.nonterminals
for sym in nt:
sym.first = set( )
sym.firstReady = False
for sym in nt:
sym.first = Tab.First(sym.graph)
sym.firstReady = True
@staticmethod
def CompFollow( p ):
assert isinstance(p, Node) or (p is None)
assert isinstance(Tab.visited, set)
while (p is not None) and (p.n not in Tab.visited):
Tab.visited.add(p.n)
if p.typ == Node.nt:
s = Tab.First(p.next)
p.sym.follow |= s
if Node.DelGraph(p.next):
p.sym.nts.add(Tab.curSy.n)
elif p.typ == Node.opt or p.typ == Node.iter:
Tab.CompFollow(p.sub)
elif p.typ == Node.alt:
Tab.CompFollow(p.sub)
Tab.CompFollow(p.down)
p = p.next
@staticmethod
def Complete( sym ):
assert isinstance( sym, Symbol )
if sym.n not in Tab.visited:
Tab.visited.add(sym.n)
nt = Symbol.nonterminals
for s in nt:
if s.n in sym.nts:
Tab.Complete(s)
sym.follow |= s.follow
if sym == Tab.curSy:
sym.nts.discard(s.n)
@staticmethod
def CompFollowSets():
nt = Symbol.nonterminals;
for sym in nt:
sym.follow = set()
sym.nts = set()
Tab.gramSy.follow.add(Tab.eofSy.n)
Tab.visited = set( )
for sym in nt:
Tab.curSy = sym
Tab.CompFollow(sym.graph)
for sym in nt:
Tab.visited = set()
Tab.curSy = sym
Tab.Complete(sym)
@staticmethod
def LeadingAny( p ):
assert isinstance( p, Node) or (p is None)
if p is None:
return None
a = None
if p.typ == Node.any:
a = p
elif p.typ == Node.alt:
a = Tab.LeadingAny(p.sub)
if a is None:
a = Tab.LeadingAny(p.down)
elif p.typ == Node.opt or p.typ == Node.iter:
a = Tab.LeadingAny(p.sub)
elif Node.DelNode(p) and not p.up:
a = Tab.LeadingAny(p.next)
return a
@staticmethod
def FindAS( p ):
'''find ANY sets'''
assert isinstance( p, Node ) or ( p is None )
while p is not None:
if p.typ == Node.opt or p.typ == Node.iter:
Tab.FindAS(p.sub)
a = Tab.LeadingAny(p.sub)
if a is not None:
a.set -= Tab.First(p.next)
elif p.typ == Node.alt:
s1 = set( )
q = p
while q is not None:
Tab.FindAS(q.sub)
a = Tab.LeadingAny(q.sub)
if a is not None:
h = Tab.First(q.down)
h |= s1
a.set -= h
else:
s1 |= Tab.First(q.sub)
q = q.down
if p.up:
break
p = p.next;
@staticmethod
def CompAnySets():
nt = Symbol.nonterminals
for sym in nt:
Tab.FindAS(sym.graph)
@staticmethod
def Expected( p, curSy):
assert isinstance( p, Node ) or (p is None)
assert isinstance( curSy, Symbol )
s = Tab.First(p)
if Node.DelGraph(p):
s |= curSy.follow
return s
@staticmethod
# does not look behind resolvers; only called during LL(1) test and in CheckRes
def Expected0( p, curSy ):
assert isinstance( p, Node)
assert isinstance(curSy,Symbol)
if p.typ == Node.rslv:
return set( )
else:
return Tab.Expected(p, curSy)
@staticmethod
def CompSync(p):
assert isinstance( p, Node) or (p is None)
while (p is not None) and (p.n not in Tab.visited):
Tab.visited.add(p.n)
if p.typ == Node.sync:
s = Tab.Expected(p.next, Tab.curSy)
s.add(Tab.eofSy.n)
Tab.allSyncSets |= s
p.set = s
elif p.typ == Node.alt:
Tab.CompSync(p.sub)
Tab.CompSync(p.down)
elif p.typ == Node.opt or p.typ == Node.iter:
Tab.CompSync(p.sub)
p = p.next
@staticmethod
def CompSyncSets():
nt = Symbol.nonterminals
Tab.allSyncSets = set( )
Tab.allSyncSets.add(Tab.eofSy.n)
Tab.visited = set( )
for sym in nt:
Tab.curSy = sym
Tab.CompSync(Tab.curSy.graph)
@staticmethod
def SetupAnys():
for p in Node.nodes:
if p.typ == Node.any:
p.set = set( )
for j in xrange(0,len(Symbol.terminals)):
p.set.add(j)
p.set.discard(Tab.eofSy.n)
@staticmethod
def CompDeletableSymbols():
nt = Symbol.nonterminals
changed = False
for sym in nt:
if (not sym.deletable) and (sym.graph is not None) and Node.DelGraph(sym.graph):
sym.deletable = True
changed = True
while changed:
changed = False
for sym in nt:
if (not sym.deletable) and (sym.graph is not None) and Node.DelGraph(sym.graph):
sym.deletable = True
changed = True
for sym in nt:
if sym.deletable:
print " " + sym.name + " deletable"
@staticmethod
def RenumberPragmas():
n = len(Symbol.terminals)
for sym in Symbol.pragmas:
sym.n = n
n += 1
@staticmethod
def CompSymbolSets():
Tab.CompDeletableSymbols()
Tab.CompFirstSets()
Tab.CompFollowSets()
Tab.CompAnySets()
Tab.CompSyncSets()
if Tab.ddt[1]:
Trace.WriteLine()
Trace.WriteLine("First & follow symbols:")
Trace.WriteLine("----------------------")
Trace.WriteLine()
nt = Symbol.nonterminals
for sym in nt:
Trace.WriteLine(sym.name)
Trace.Write("first: ")
Tab.PrintSet(sym.first, 10)
Trace.Write("follow: ")
Tab.PrintSet(sym.follow,10)
Trace.WriteLine()
if Tab.ddt[4]:
Trace.WriteLine()
Trace.WriteLine("ANY and SYNC sets:")
Trace.WriteLine("-----------------")
for p in Node.nodes:
if p.typ == Node.any or p.typ == Node.sync:
Trace.Write(str(p.n), 4)
Trace.Write(" ")
Trace.Write(Node.nTyp[p.typ], 4)
Trace.Write(": ")
Tab.PrintSet(p.set,12)
Trace.WriteLine()
#---------------------------------------------------------------------
# Grammar checks
#---------------------------------------------------------------------
@staticmethod
def GrammarOk():
ok = ( Tab.NtsComplete()
and Tab.AllNtReached()
and Tab.NoCircularProductions()
and Tab.AllNtToTerm()
and Tab.ResolversOk() )
assert isinstance(ok,bool)
if ok:
Tab.CheckLL1()
return ok
#--------------- check for circular productions ----------------------
@staticmethod
def GetSingles(p, singles):
assert isinstance(p,Node) or (p is None)
assert isinstance(singles,list)
if p is None:
return # end of graph
if p.typ == Node.nt:
if p.up or Node.DelGraph(p.next):
singles.append(p.sym)
elif p.typ == Node.alt or p.typ == Node.iter or p.typ == Node.opt:
if p.up or Node.DelGraph(p.next):
Tab.GetSingles(p.sub, singles)
if p.typ == Node.alt:
Tab.GetSingles(p.down, singles)
if (not p.up) and Node.DelNode(p):
Tab.GetSingles(p.next, singles)
@staticmethod
def NoCircularProductions():