File: demo.py

package info (click to toggle)
yappy 1.9.4-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 548 kB
  • ctags: 291
  • sloc: python: 1,845; perl: 75; makefile: 49
file content (473 lines) | stat: -rw-r--r-- 16,003 bytes parent folder | download | duplicates (2)
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
# -*- coding: utf-8 -*-
#
# 
# This is part of Yappy
#
#
# demo.py -- some simple parsers
#
# Copyright (C) 2000-2003 Rogério Reis & Nelma Moreira {rvr,nam}@ncc.up.pt
#

#from yappy.parser import *
import sys, string
from yappy.parser import *
############## Demos  #####################

class SimpleExp(Yappy):
    """ A parser  for simple arithmetic expresssion. Allows blanks
    between tokens"""
    def __init__(self,no_table=0, table='saexp.tab'):
        grammar = grules([
                ("E -> E + T", self.Add),
                ("E ->T", DefaultSemRule),
                ("T -> T * F", self.Mul ),
                ("T -> F", DefaultSemRule),
                ("F -> ( E )", self.ParSemRule),
                ("F -> id", DefaultSemRule)]
                         )
        tokenize=[("\s+",""),
               ("\d+",lambda x: ("id",int(x))),
               ("\+",lambda x: (x,x)),
               ("\*",lambda x: (x,x)),
               ("\(|\)",lambda x: (x,x)) ]
        Yappy.__init__(self,tokenize,grammar,table,no_table,
    tmpdir='/tmp')
        
    
    def ParSemRule(self,list,context=None):
        return list[1]

    def DoPrint(self,list,context=None):
        print list[0]
        return list[0]

    def Add(self,list,context):
        print list
        return list[0] + list[2]

    def Mul(self,list,context):
        print list
        return list[0] * list[2]

    def test(self):
        st = " 2 + 24 + 34 * 2 + 1"
        print "Input: %s" %st
        print "Result:", self.input(st)   

class SimpleExp3(SimpleExp):
    """ A parser  for simple arithmetic expresssion. Allows blanks
    between tokens"""
    def __init__(self,no_table=0, table='saexp.tab'):
        grammar = """ 
                E -> E + T {{ "sum([$0,$2])"}};
                E ->T ;
                T -> T * F" {{ self.Mul }};
                T -> F ;
                F -> ( E ) {{ self.ParSemRule}};
                F -> id;
                """
        tokenize=[("\s+",""),
               ("\d+",lambda x: ("id",int(x))),
               ("\+",lambda x: (x,x)),
               ("\*",lambda x: (x,x)),
               ("\(|\)",lambda x: (x,x)) ]
        Yappy.__init__(self,tokenize,grammar,table,no_table)
        
class SimpleExp1(Yappy):
    """ A parser  for simple arithmetic expresssions, with operators """
    def __init__(self,no_table=0, table='saexp1.tab', tabletype=LALRtable,noconflicts=1,expect=0):
        grammar = grules([
                ("E -> E add_op T", self.Add),
                ("E ->T", DefaultSemRule),
                ("T -> T mul_op F", self.Mul),
                ("T -> F", DefaultSemRule),
                ("F -> ( E )", self.ParSemRule),
                ("F -> id", DefaultSemRule)])

        tokenize=[("\d+",lambda x: ("id",int(x))),
               ("[+-]",lambda x: ("add_op",self.make_op(x))),
               ("[*/]",lambda x: ("mul_op",self.make_op(x))),
               ("\(|\)",lambda x: (x,x)) ]
        Yappy.__init__(self,tokenize,grammar,table,no_table,tabletype,noconflicts,expect)

    def make_op(self,op):
        return {"+"  : operator.add,
		'-'  : operator.sub,
                '*'   : operator.mul,
                '/'   : operator.div,
                '%'   : operator.mod
                }[op]
    
    def ParSemRule(self,list,context=None):
        return list[1]

    def DoPrint(self,list,context=None):
        print list[0]
        return list[0]

    def Add(self,list,context):
        print list
        return apply(list[1],[list[0],list[2]])

    def Mul(self,list,context):
        print list
        return apply(list[1],[list[0],list[2]])

    def test(self):
        st = "2-24*9"
        st1 = "2-24*9-34*2+1"
        print "Input: %s" %st
        print "Result:", self.input(st)


class SimpleExp2(SimpleExp1):
    """ A parser  for simple arithmetic expresssions with prec and associativity"""
    def __init__(self,no_table=0, table='saexp2.tab',
    tabletype=LALRtable,noconflicts=1,expect=0):
        self.line = 0
        grammar = grules([
                ("E -> E add_op T", self.Add),
                ("E ->T", DefaultSemRule),
                ("T -> T mul_op F", self.Mul),
                ("T -> F", DefaultSemRule),
                ("F -> ( E )", self.ParSemRule),
                ("F -> id", DefaultSemRule)])

        tokenize=[("\d+",lambda x: ("id",int(x))),
                  ("\n+",lambda x: (x,self.countline())),
               ("[+-]",lambda x: ("add_op",self.make_op(x)),("add_op",100,'left')),
               ("[*/]",lambda x: ("mul_op",self.make_op(x)),("mul_op",200,'left')),
               ("\(|\)",lambda x: (x,x)) ]
        Yappy.__init__(self,tokenize,grammar,table,no_table,tabletype,noconflicts,expect)
        

    def countline(self):
        self.line+=1
        return ""
    
    def make_op(self,op):
        """ """
        return {"+"  : operator.add,
		'-'  : operator.sub,
                '*'   : operator.mul,
                '/'   : operator.div,
                '%'   : operator.mod
                }[op]
    
    def ParSemRule(self,list,context=None):
        return list[1]

    def DoPrint(self,list,context=None):
        print list[0]
        return list[0]

    def Add(self,list,context):
        print list
        return apply(list[1],[list[0],list[2]])

    def Mul(self,list,context):
        print list
        return apply(list[1],[list[0],list[2]])

class SimpleExpAmb(SimpleExp2):
    """A parser  for simple arithmetic expresssions with an ambiguous grammar """
    def __init__(self,no_table=0, table='expamb.tab',tabletype=LALRtable,noconflicts=1,expect=0):
        grammar = grules([
                ("E -> E add_op E", self.Add),
                ("E -> E mul_op E", self.Mul),
                ("E -> ( E )", self.ParSemRule),
                ("E -> id", DefaultSemRule)])

        sinal = "[+-]"
        integer ="\d" 
        tokenize=[("(%s)+"%integer,lambda x: ("id",int(x))),
               (sinal,lambda x: ("add_op",self.make_op(x)),("add_op",100,'left')),
               ("[*/]",lambda x: ("mul_op",self.make_op(x)),("mul_op",200,'left')),
               ("\(|\)",lambda x: (x,x)) ]

        Yappy.__init__(self,tokenize,grammar,table,no_table,tabletype,noconflicts,expect)


class SimpleExpAmb2(SimpleExp2):
    """A parser  for simple arithmetic expresssions with an ambiguous
    grammar, and context-dependent precedence """
    def __init__(self,no_table=0, table='expamb.tab',tabletype=LALRtable,noconflicts=1,expect=0):
        grammar = grules([
                ("E -> E add_op E", self.Add),
                ("E -> E mul_op E", self.Mul),
                ("E -> n_op E", lambda l,c: -1*l[1]),
                ("E -> ( E )", self.ParSemRule),
                
                ("E -> id", DefaultSemRule)])

        plus = "[+-]"
        integer = "\d" 
        tokenize=[("(%s)+"%integer,lambda x: ("id",int(x))),
               ("%s"%plus,lambda x:
                ("add_op",self.make_op(x)),("add_op",100,'left')),
                ("~",lambda x: ("n_op",self.make_op('-')),("n_op",300,'left')),
               ("[*/]",lambda x: ("mul_op",self.make_op(x)),("mul_op",200,'left')),
               ("\(|\)",lambda x: (x,x)) ]

        Yappy.__init__(self,tokenize,grammar,table,no_table,tabletype,noconflicts,expect)
    def test(self):
        st=[
         "~2",
        "2-24*9",
        "2-24*9-34*2+1",
        "~2-24*9-34*2+1",
         "2+3+(~5*(2+3)*2)-24*9-34*2+1"
         ]
        for i in st:
            print "Input: %s" %i
            print "Result:", self.input(i)


class ListAVG(Yappy):
    """A parser  for transforming a list atrib=value into a python dictionary """
    def __init__(self,no_table=0, table='Listavg.tab'):
        grammar =   """
            E -> ( ) {{self.EmptyDict}};
            E ->  ( AVL ) {{self.ParSemRule}} ;
            AVL ->   AV , AVL  | AV {{EmptySemRule}} ;
            AV -> tok = tok {{ self.AddItem }};
            """
    
        tokenize = [
             ("\s+",""),
             ("[A-Za-z0-9]+",lambda x: ("tok",x)),
             ("\=",lambda x: (x,x)),
             (",",lambda x: (x,x)),
             ("\(|\)",lambda x: (x,x)) ]

        Yappy.__init__(self,tokenize,grammar,table,no_table)


    def ParSemRule(self,list,context=None):
        return list[1]

    def DoPrint(self,list,context=None):
        print list[0]
        return list[0]


    def EmptyDict(self,list,context):
        return []

    def AddItem(self,list,context):
        if not isinstance(list[0], StringType):
            raise NameError, "Key %s must be a string" % list[0] 
        context[list[0]] = list[2] 
        return []

    def test(self):
        st = "(a=5,b=6,c=7)"
        print "Input: %s" %st      
        self.input(st,context={})
        print self.context

class ListAVG1(ListAVG):
    """A parser  for transforming a list atrib=value into a python dictionary """
    def __init__(self,no_table=0, table='Listavg1.tab'):
        grammar =   """
            E -> ( ) {{self.EmptyDict}};
            E -> ( AVL ) {{self.ParSemRule}} ;
            AVL ->   AV , AVL   | AV {{EmptySemRule}} ;
            AV -> tok = tok {{ self.AddItem }};
            """
        tokenize = [
             ("\s+",""),
             ("[A-Za-z0-9]+",lambda x: ("tok",x)),
             ("\=",lambda x: (x,x)),
             (",",lambda x: (x,x)),
             ("\(|\)",lambda x: (x,x)) ]

        Yappy.__init__(self,tokenize,grammar,table,no_table)
        
class ListAVG2(ListAVG):
    """A parser  for transforming a list atrib=value into a python dictionary """
    def __init__(self,no_table=0, table='Listavg1.tab'):
        grammar =   """
            E -> ( AVL ) {{self.ParSemRule}} ;
            AVL ->   AV , AVL  {{DefaultSemRule}} | ;
            AV -> tok = tok {{ self.AddItem }};
            """
        tokenize = [
             ("\s+",""),
             ("[A-Za-z0-9]+",lambda x: ("tok",x)),
             ("\=",lambda x: (x,x)),
             (",",lambda x: (x,x)),
             ("\(|\)",lambda x: (x,x)) ]

        Yappy.__init__(self,tokenize,grammar,table,no_table)


    def test(self):
        st = "(a=5,b=6,c=7,)"
        
        print "Input: %s" %st      
        self.input(st,context={})
        print self.context

        
class RegExp(Yappy):
     def __init__(self,no_table=0, table='regamb.tab',
     tabletype=LALRtable,
                  noconflicts=1,expect=0):
        """ A parser for regular expressions with operators. Semantic
     rules are dummy..."""
        grammar = grules([("r -> r | r",self.OrSemRule),
                        ("r -> r . r",self.ConcatSemRule),
                    ("r -> r *",self.StarSemRule, (300,'left')),
                    ("r -> ( r )",self.ParSemRule),
                    ("r -> id",self.BaseSemRule),
                   ])
        tokenize =[
                    ("[A-Za-z0-9]",lambda x: ("id",x)),
                    ("[+|]",lambda x: ("|",x),("|",100,'left')),
                    ("[\.]",lambda x: (".",""),(".",200,'left')),
                    ("[*]",lambda x: (x,x), ("*",300,'left')),
                    ("\(|\)",lambda x: (x,x)) ]
        Yappy.__init__(self,tokenize,grammar,table,no_table,tabletype)

     ##Semantic rules build a parse tree...
     def OrSemRule(self,list,context):
         return "(%s+%s)" %(list[0],list[2])

     def ConcatSemRule(self,list,context):
         return "(%s%s)" %(list[0],list[2])

     def ParSemRule(self,list,context):
         return "(%s)" %list[1]

     def BaseSemRule(self,list,context):
         return list[0]

     def StarSemRule(self,list,context):
         return "(%s*)" %list[0]

     def test(self):
         st  = ["(a+b)*.a.a.b*",
                "a+a.b+a.b.(a+a)*",
                "a+a.b+a.(a+a)**",
                 "a+a.b.c",
                "a+a.b.(c+b)",
                "a+a.b.(c+b)*",
                 "a+a.b*.(a+b)"]
         for i in st:
             print "Input: %s" %i
             print self.input(i)

class RegExp1(RegExp):
     def __init__(self,no_table=0, table='tableambreg1',tabletype=LALRtable,
                  noconflicts=1,expect=0):
        """A parser for regular expressions with ambiguous rules  """
        grammar = grules([("reg -> reg + reg",self.OrSemRule),
                                ("reg -> reg reg",self.ConcatSemRule,(200,'left')),
                               ("reg -> reg *",self.StarSemRule),
                               ("reg -> ( reg )",self.ParSemRule),
                               ("reg -> id",self.BaseSemRule)
                   ])
        tokenize =[
                    ("[A-Za-z0-9]",lambda x: ("id",x)),
                    ("[+|]",lambda x: ("+",x),("+",100,'left')),
                    ("[*]",lambda x: (x,x)),
                    ("\(|\)",lambda x: (x,x)) ]
        Yappy.__init__(self,tokenize,grammar,table,no_table,tabletype,noconflicts,expect)
        
     def ConcatSemRule(self,list,context=None):
         return "(%s%s)" %(list[0],list[1])


     def test(self):
         st  = ["(a+b)*aab*",
                "(a+ab)*a*",
                "(a+a)a+ab",
                "a+ab+(a(a+a)*)*",
                "a+ab+a(a+a)**",
                "(a+a)**ab(a+b)**",
                "aa+bb**",
                "(a+ab)(a+ab)(ac+a)",
                "a+abc+ad",
                "abc+b+ad",
                "a+ab",
                "a+b+ab+cccaaaaaa",
                "a+ab(a+a)",
                "ab+ab(a+a)a*",
                "a+ab*",
                "(a+ab*(a+b))*",
                "a+ab*(a+b)",
                "a+c+ab(a+b)",
                "a+c+(a+b)ab",
                "a+b*",
                "aa+b*",
                "aab*ab+a*+aa",
                "aab*ab**+(a+aa)**"
                ]
         for i in st:
             print "Input: %s" %i
             print self.input(i)


class RegExp2(RegExp1):
     def __init__(self,no_table=0, table='tableambreg2'):
         grammar = """
        reg -> reg + reg {{ self.OrSemRule }} |
               reg reg {{ self.ConcatSemRule}} // 200 left|
               reg * {{ self.StarSemRule }} |
               ( reg ) {{self.ParSemRule }} |
               id {{ self.BaseSemRule }} ;
        """
         tokenize = [("@epsilon",lambda x: ("id",x)),
                    ("@empty_set",lambda x: ("id",x)),
                    ("[A-Za-z0-9]",lambda x: ("id",x)),
                    ("[+|]",lambda x: ("+",x),("+",100,'left')),
                    ("[*]",lambda x: (x,x)),
                    ("\(|\)",lambda x: (x,x)) ]

         Yappy.__init__(self,tokenize,grammar,table,no_table)

class RegExp3(RegExp):
     def __init__(self,no_table=0, table='tableambreg3'):
        """A erronous parser for regular expressions with ambiguous rules and
     no precedence information """
        grammar = grules([("reg -> reg | reg",self.OrSemRule),
                                ("reg -> reg reg",self.ConcatSemRule),
                               ("reg -> reg *",self.StarSemRule),
                               ("reg -> ( reg )",self.ParSemRule),
                               ("reg -> id",self.BaseSemRule),
                   ])
        tokenize =[
                    ("[A-Za-z0-9]",lambda x: ("id",x)),
                    ("[+|]",lambda x: ("|",x)),
                    ("[*]",lambda x: (x,x)),
                    ("\(|\)",lambda x: (x,x)) ]
        Yappy.__init__(self,tokenize,grammar,table,no_table,LALRtable,1)
        
     def ConcatSemRule(self,list,context=None):
         return list[0]+list[1]

     def test(self):
         st  = "(a+b)*aab*"
         print "Input: %s" %st
         print self.input(st)
        
def Sum(a,b):
    return a+b

def curry(f,*a,**kw):
    def curried(*more_a,**more_kw):
        return f(*(a+more_a),**dict(kw,**more_kw))
    return curried

if __name__ == '__main__':
    d = SimpleExpAmb()
    st = "2-24*9"
    print "Input:", st
    print "Result:", d.input(st)
    st = "2-24*9-34*2+1"
    print "Input:", st
    print "Result:", d.input(st)
    d = RegExp2()
    print "Result:", d.input("a+b*")