Mercurial > lcfOS
comparison python/testparserlib.py @ 212:62386bcee1ba
Added parser combinator lib
author | Windel Bouwman |
---|---|
date | Sun, 30 Jun 2013 19:00:41 +0200 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
211:99164160fb0b | 212:62386bcee1ba |
---|---|
1 import unittest | |
2 from parserlib import OneOrMore, Literal, Or, Sequence, Optional | |
3 | |
4 class ParserCombinatorTestCase(unittest.TestCase): | |
5 def test1(self): | |
6 #p = Parser() | |
7 # parse and interpret: | |
8 n40 = Literal('40') | |
9 plus = Literal('+') | |
10 n2 = Literal('2') | |
11 n40.ParseAction = int | |
12 plus.ParseAction = replaceWith(0) | |
13 n2.ParseAction = int | |
14 p = Sequence([n40,plus,n2]) | |
15 p.ParseAction = wordsum | |
16 | |
17 result = p.parse('40+2') | |
18 self.assertEqual(42, result[0]) | |
19 | |
20 def replaceWith(s): | |
21 def _repFunc(*args): | |
22 return s | |
23 return _repFunc | |
24 | |
25 wordsum = lambda t: sum(t) | |
26 | |
27 class WordToNumTestCase(unittest.TestCase): | |
28 def setUp(self): | |
29 numWords = OneOrMore() | |
30 def makeLit(s, val): | |
31 ret = Literal(s) | |
32 ret.ParseAction = replaceWith(val) | |
33 return ret | |
34 unitDefs = [('zero', 0), ('three', 3), ('one', 1)] | |
35 units = Or( [makeLit(s, v) for s, v in unitDefs] ) | |
36 tensDefs = [('twenty', 20)] | |
37 tens = Or( [makeLit(s, v) for s, v in tensDefs] ) | |
38 | |
39 numPart = Sequence([Optional(tens), units]) | |
40 numPart.ParseAction = wordsum | |
41 self.p = numPart | |
42 | |
43 def check(self, i, o): | |
44 result = self.p.parse(i)[0] | |
45 self.assertEqual(o, result) | |
46 | |
47 def test0(self): | |
48 self.check('zero', 0) | |
49 | |
50 def test23(self): | |
51 self.check('twentythree', 23) | |
52 | |
53 @unittest.skip | |
54 def test321(self): | |
55 # TODO | |
56 self.check('three hundred and twenty one', 321) | |
57 | |
58 | |
59 if __name__ == '__main__': | |
60 unittest.main() | |
61 |