comparison python/testpyy.py @ 192:6cd6260789a1

Added more tests for parser generator
author Windel Bouwman
date Sun, 26 May 2013 23:19:27 +0200
parents 6b2bec5653f1
children b01429a5d695
comparison
equal deleted inserted replaced
191:6b2bec5653f1 192:6cd6260789a1
1 import unittest, pprint 1 import unittest, pprint
2 from pyyacc import Grammar, Item, EOF 2 from pyyacc import Grammar, Item, EOF, ParserGenerationException
3 from ppci import Token 3 from ppci import Token
4 4
5 def genTokens(lst): 5 def genTokens(lst):
6 for t in lst: 6 for t in lst:
7 yield Token(t, t, 0) 7 yield Token(t, t, 0)
25 tokens = genTokens(['identifier', '+', 'identifier', '+', 'identifier']) 25 tokens = genTokens(['identifier', '+', 'identifier', '+', 'identifier'])
26 # 3. build parser: 26 # 3. build parser:
27 p = g.genParser() 27 p = g.genParser()
28 # 4. feed input: 28 # 4. feed input:
29 p.parse(tokens) 29 p.parse(tokens)
30 def testReduceReduceConflict(self):
31 """ Check if a reduce-reduce conflict is detected """
32 # Define a grammar with an obvious reduce-reduce conflict:
33 g = Grammar([EOF, 'id'])
34 g.add_production('goal', ['a'])
35 g.add_production('a', ['b'])
36 g.add_production('a', ['c'])
37 g.add_production('b', ['id'])
38 g.add_production('c', ['id'])
39 g.start_symbol = 'goal'
40 with self.assertRaises(ParserGenerationException):
41 p = g.genParser()
42 def testShiftReduceConflict(self):
43 g = Grammar([EOF, 'if', 'then', 'else'])
44 g.add_production('if_stmt', ['if', 'then'])
45 g.add_production('if_stmt', ['if', 'then', 'else'])
46 g.add_production('stmt', ['if_stmt', 'else'])
47 g.start_symbol = 'stmt'
48 with self.assertRaises(ParserGenerationException):
49 g.genParser()
50 def testUndefinedTerminal(self):
51 """ Test correct behavior when a terminal is undefined """
52 g = Grammar([EOF, 'b'])
53 g.add_production('goal', ['a'])
54 g.add_production('a', ['b'])
55 g.add_production('a', ['c'])
56 g.start_symbol = 'goal'
57 with self.assertRaises(ParserGenerationException):
58 g.genParser()
59 def testRedefineTerminal(self):
60 """ Test correct behavior when a terminal is redefined """
61 g = Grammar([EOF, 'b', 'c'])
62 g.add_production('goal', ['a'])
63 with self.assertRaises(ParserGenerationException):
64 g.add_production('b', ['c']) # Not allowed
65 g.add_production('a', ['c'])
66 g.start_symbol = 'goal'
67 g.genParser()
30 68
31 class testExpressionGrammar(unittest.TestCase): 69 class testExpressionGrammar(unittest.TestCase):
32 def setUp(self): 70 def setUp(self):
33 g = Grammar(['EOF', 'identifier', '(', ')', '+', '*', 'num']) 71 g = Grammar(['EOF', 'identifier', '(', ')', '+', '*', 'num'])
34 g.add_production('input', ['expression']) 72 g.add_production('input', ['expression'])