File: test_pymeta.py

package info (click to toggle)
python-parsley 1.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,048 kB
  • sloc: python: 9,897; makefile: 127
file content (1597 lines) | stat: -rw-r--r-- 51,783 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
#from __future__ import unicode_literals

import operator
from textwrap import dedent

import pytest
import unittest

from ometa.grammar import OMeta, TermOMeta, TreeTransformerGrammar
from ometa.compat import OMeta1
from ometa.runtime import (ParseError, OMetaBase, OMetaGrammarBase, EOFError,
                           expected, TreeTransformerBase)
from ometa.interp import GrammarInterpreter, TrampolinedGrammarInterpreter
from terml.parser import parseTerm as term
from ometa.test.helpers import TestCase

try:
    basestring
except NameError:
    basestring = str


class HandyWrapper(object):
    """
    Convenient grammar wrapper for parsing strings.
    """
    def __init__(self, klass):
        """
        @param klass: The grammar class to be wrapped.
        """
        self.klass = klass


    def __getattr__(self, name):
        """
        Return a function that will instantiate a grammar and invoke the named
        rule.
        @param: Rule name.
        """
        def doIt(s):
            """
            @param s: The string to be parsed by the wrapped grammar.
            """
            obj = self.klass(s)
            ret, err = obj.apply(name)
            try:
                extra, _ = obj.input.head()
            except EOFError:
                try:
                    return ''.join(ret)
                except TypeError:
                    return ret
            else:
                raise err
        return doIt



class OMeta1TestCase(TestCase):
    """
    Tests of OMeta grammar compilation, with v1 syntax.
    """

    classTested = OMeta1

    def compile(self, grammar):
        """
        Produce an object capable of parsing via this grammar.

        @param grammar: A string containing an OMeta grammar.
        """
        m = self.classTested.makeGrammar(dedent(grammar), 'TestGrammar')
        g = m.createParserClass(OMetaBase, globals())
        return HandyWrapper(g)



    def test_literals(self):
        """
        Input matches can be made on literal characters.
        """
        g = self.compile("digit ::= '1'")
        self.assertEqual(g.digit("1"), "1")
        self.assertRaises(ParseError, g.digit, "4")


    def test_multipleRules(self):
        """
        Grammars with more than one rule work properly.
        """
        g = self.compile("""
                          digit ::= '1'
                          aLetter ::= 'a'
                          """)
        self.assertEqual(g.digit("1"), "1")
        self.assertRaises(ParseError, g.digit, "4")


    def test_escapedLiterals(self):
        """
        Input matches can be made on escaped literal characters.
        """
        g = self.compile(r"newline ::= '\n'")
        self.assertEqual(g.newline("\n"), "\n")


    def test_integers(self):
        """
        Input matches can be made on literal integers.
        """
        g = self.compile("stuff ::= 17 0x1F -2 0177")
        self.assertEqual(g.stuff([17, 0x1f, -2, 0o177]), 0o177)
        self.assertRaises(ParseError, g.stuff, [1, 2, 3])


    def test_star(self):
        """
        Input matches can be made on zero or more repetitions of a pattern.
        """
        g = self.compile("xs ::= 'x'*")
        self.assertEqual(g.xs(""), "")
        self.assertEqual(g.xs("x"), "x")
        self.assertEqual(g.xs("xxxx"), "xxxx")
        self.assertRaises(ParseError, g.xs, "xy")


    def test_plus(self):
        """
        Input matches can be made on one or more repetitions of a pattern.
        """
        g = self.compile("xs ::= 'x'+")
        self.assertEqual(g.xs("x"), "x")
        self.assertEqual(g.xs("xxxx"), "xxxx")
        self.assertRaises(ParseError, g.xs, "xy")
        self.assertRaises(ParseError, g.xs, "")


    def test_sequencing(self):
        """
        Input matches can be made on a sequence of patterns.
        """
        g = self.compile("twelve ::= '1' '2'")
        self.assertEqual(g.twelve("12"), "2");
        self.assertRaises(ParseError, g.twelve, "1")


    def test_alternatives(self):
        """
        Input matches can be made on one of a set of alternatives.
        """
        g = self.compile("digit ::= '0' | '1' | '2'")
        self.assertEqual(g.digit("0"), "0")
        self.assertEqual(g.digit("1"), "1")
        self.assertEqual(g.digit("2"), "2")
        self.assertRaises(ParseError, g.digit, "3")


    def test_optional(self):
        """
        Subpatterns can be made optional.
        """
        g = self.compile("foo ::= 'x' 'y'? 'z'")
        self.assertEqual(g.foo("xyz"), 'z')
        self.assertEqual(g.foo("xz"), 'z')


    def test_apply(self):
        """
        Other productions can be invoked from within a production.
        """
        g = self.compile("""
              digit ::= '0' | '1'
              bits ::= <digit>+
            """)
        self.assertEqual(g.bits('0110110'), '0110110')


    def test_negate(self):
        """
        Input can be matched based on its failure to match a pattern.
        """
        g = self.compile("foo ::= ~'0' <anything>")
        self.assertEqual(g.foo("1"), "1")
        self.assertRaises(ParseError, g.foo, "0")


    def test_ruleValue(self):
        """
        Productions can specify a Python expression that provides the result
        of the parse.
        """
        g = self.compile("foo ::= '1' => 7")
        self.assertEqual(g.foo('1'), 7)


    def test_ruleValueEscapeQuotes(self):
        """
        Escaped quotes are handled properly in Python expressions.
        """
        g = self.compile(r"""escapedChar ::= '\'' => '\\\''""")
        self.assertEqual(g.escapedChar("'"), "\\'")


    def test_ruleValueEscapeSlashes(self):
        """
        Escaped slashes are handled properly in Python expressions.
        """
        g = self.compile(r"""escapedChar ::= '\\' => '\\'""")
        self.assertEqual(g.escapedChar("\\"), "\\")


    def test_lookahead(self):
        """
        Doubled negation does lookahead.
        """
        g = self.compile("""
                         foo ::= ~~(:x) <bar x>
                         bar :x ::= :a :b ?(x == a == b) => x
                         """)
        self.assertEqual(g.foo("11"), '1')
        self.assertEqual(g.foo("22"), '2')


    def test_binding(self):
        """
        The result of a parsing expression can be bound to a name.
        """
        g = self.compile("foo ::= '1':x => int(x) * 2")
        self.assertEqual(g.foo("1"), 2)


    def test_bindingAccess(self):
        """
        Bound names in a rule can be accessed on the grammar's "locals" dict.
        """
        G = self.classTested.makeGrammar(
            "stuff ::= '1':a ('2':b | '3':c)", 'TestGrammar').createParserClass(OMetaBase, {})
        g = G("12")
        self.assertEqual(g.apply("stuff")[0], '2')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['b'], '2')
        g = G("13")
        self.assertEqual(g.apply("stuff")[0], '3')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['c'], '3')


    def test_predicate(self):
        """
        Python expressions can be used to determine the success or failure of a
        parse.
        """
        g = self.compile("""
              digit ::= '0' | '1'
              double_bits ::= <digit>:a <digit>:b ?(a == b) => int(b)
           """)
        self.assertEqual(g.double_bits("00"), 0)
        self.assertEqual(g.double_bits("11"), 1)
        self.assertRaises(ParseError, g.double_bits, "10")
        self.assertRaises(ParseError, g.double_bits, "01")


    def test_parens(self):
        """
        Parens can be used to group subpatterns.
        """
        g = self.compile("foo ::= 'a' ('b' | 'c')")
        self.assertEqual(g.foo("ab"), "b")
        self.assertEqual(g.foo("ac"), "c")


    def test_action(self):
        """
        Python expressions can be run as actions with no effect on the result
        of the parse.
        """
        g = self.compile("""foo ::= ('1'*:ones !(False) !(ones.insert(0, '0')) => ''.join(ones))""")
        self.assertEqual(g.foo("111"), "0111")


    def test_bindNameOnly(self):
        """
        A pattern consisting of only a bind name matches a single element and
        binds it to that name.
        """
        g = self.compile("foo ::= '1' :x '2' => x")
        self.assertEqual(g.foo("132"), "3")


    def test_args(self):
        """
        Productions can take arguments.
        """
        g = self.compile("""
              digit ::= ('0' | '1' | '2'):d => int(d)
              foo :x :ignored ::= (?(int(x) > 1) '9' | ?(int(x) <= 1) '8'):d => int(d)
              baz ::= <digit>:a <foo a None>:b => [a, b]
            """)
        self.assertEqual(g.baz("18"), [1, 8])
        self.assertEqual(g.baz("08"), [0, 8])
        self.assertEqual(g.baz("29"), [2, 9])
        self.assertRaises(ParseError, g.baz, "28")


    def test_patternMatch(self):
        """
        Productions can pattern-match on arguments.
        Also, multiple definitions of a rule can be done in sequence.
        """
        g = self.compile("""
              fact 0                       => 1
              fact :n ::= <fact (n - 1)>:m => n * m
           """)
        self.assertEqual(g.fact([3]), 6)


    def test_listpattern(self):
        """
        Brackets can be used to match contents of lists.
        """
        g = self.compile("""
             digit  ::= :x ?(x.isdigit())          => int(x)
             interp ::= [<digit>:x '+' <digit>:y] => x + y
           """)
        self.assertEqual(g.interp([['3', '+', '5']]), 8)

    def test_listpatternresult(self):
        """
        The result of a list pattern is the entire list.
        """
        g = self.compile("""
             digit  ::= :x ?(x.isdigit())          => int(x)
             interp ::= [<digit>:x '+' <digit>:y]:z => (z, x + y)
        """)
        e = ['3', '+', '5']
        self.assertEqual(g.interp([e]), (e, 8))

    def test_recursion(self):
        """
        Rules can call themselves.
        """
        g = self.compile("""
             interp ::= (['+' <interp>:x <interp>:y] => x + y
                       | ['*' <interp>:x <interp>:y] => x * y
                       | :x ?(isinstance(x, str) and x.isdigit()) => int(x))
             """)
        self.assertEqual(g.interp([['+', '3', ['*', '5', '2']]]), 13)


    def test_leftrecursion(self):
         """
         Left-recursion is detected and compiled appropriately.
         """
         g = self.compile("""
               num ::= (<num>:n <digit>:d   => n * 10 + d
                      | <digit>)
               digit ::= :x ?(x.isdigit()) => int(x)
              """)
         self.assertEqual(g.num("3"), 3)
         self.assertEqual(g.num("32767"), 32767)


    def test_characterVsSequence(self):
        """
        Characters (in single-quotes) are not regarded as sequences.
        """
        g = self.compile("""
        interp ::= ([<interp>:x '+' <interp>:y] => x + y
                  | [<interp>:x '*' <interp>:y] => x * y
                  | :x ?(isinstance(x, basestring) and x.isdigit()) => int(x))
        """)
        self.assertEqual(g.interp([['3', '+', ['5', '*', '2']]]), 13)
        self.assertEqual(g.interp([['3', '+', ['5', '*', '2']]]), 13)


    def test_string(self):
        """
        Strings in double quotes match string objects.
        """
        g = self.compile("""
             interp ::= ["Foo" 1 2] => 3
           """)
        self.assertEqual(g.interp([["Foo", 1, 2]]), 3)

    def test_argEscape(self):
        """
        Regression test for bug #239344.
        """
        g = self.compile("""
            memo_arg :arg ::= <anything> ?(False)
            trick ::= <letter> <memo_arg 'c'>
            broken ::= <trick> | <anything>*
        """)
        self.assertEqual(g.broken('ab'), 'ab')


    def test_comments(self):
        """
        Comments in grammars are accepted and ignored.
        """
        g = self.compile("""
        #comment here
        digit ::= ( '0' #second comment
                  | '1') #another one
        #comments after rules are cool too
        bits ::= <digit>+   #last one
        """)
        self.assertEqual(g.bits('0110110'), '0110110')


    def test_accidental_bareword(self):
        """
        Accidental barewords are treated as syntax errors in the grammar.
        """
        self.assertRaises(ParseError,
                          self.compile, """
                          atom ::= ~('|') :a => Regex_Atom(a)
                                   | ' ' atom:a
                          """)




class OMetaTestCase(TestCase):
    """
    Tests of OMeta grammar compilation.
    """

    classTested = OMeta


    def compile(self, grammar, globals=None):
        """
        Produce an object capable of parsing via this grammar.

        @param grammar: A string containing an OMeta grammar.
        """
        g = self.classTested.makeGrammar(grammar, 'TestGrammar').createParserClass(OMetaBase, globals or {})
        return HandyWrapper(g)


    def test_literals(self):
        """
        Input matches can be made on literal characters.
        """
        g = self.compile("digit = '1'")
        self.assertEqual(g.digit("1"), "1")
        self.assertRaises(ParseError, g.digit, "4")


    def test_escaped_char(self):
        """
        Hex escapes are supported in strings in grammars.
        """
        g = self.compile(r"bel = '\x07'")
        self.assertEqual(g.bel("\x07"), "\x07")


    def test_literals_multi(self):
        """
        Input matches can be made on multiple literal characters at
        once.
        """
        g = self.compile("foo = 'foo'")
        self.assertEqual(g.foo("foo"), "foo")
        self.assertRaises(ParseError, g.foo, "for")

    def test_token(self):
        """
        Input matches can be made on tokens, which default to
        consuming leading whitespace.
        """
        g = self.compile('foo = "foo"')
        self.assertEqual(g.foo("    foo"), "foo")
        self.assertRaises(ParseError, g.foo, "fog")


    def test_multipleRules(self):
        """
        Grammars with more than one rule work properly.
        """
        g = self.compile("""
                          digit = '1'
                          aLetter = 'a'
                          """)
        self.assertEqual(g.digit("1"), "1")
        self.assertRaises(ParseError, g.digit, "4")


    def test_escapedLiterals(self):
        """
        Input matches can be made on escaped literal characters.
        """
        g = self.compile(r"newline = '\n'")
        self.assertEqual(g.newline("\n"), "\n")


    def test_integers(self):
        """
        Input matches can be made on literal integers.
        """
        g = self.compile("stuff = 17 0x1F -2 0177")
        self.assertEqual(g.stuff([17, 0x1f, -2, 0o177]), 0o177)
        self.assertRaises(ParseError, g.stuff, [1, 2, 3])


    def test_star(self):
        """
        Input matches can be made on zero or more repetitions of a pattern.
        """
        g = self.compile("xs = 'x'*")
        self.assertEqual(g.xs(""), "")
        self.assertEqual(g.xs("x"), "x")
        self.assertEqual(g.xs("xxxx"), "xxxx")
        self.assertRaises(ParseError, g.xs, "xy")


    def test_plus(self):
        """
        Input matches can be made on one or more repetitions of a pattern.
        """
        g = self.compile("xs = 'x'+")
        self.assertEqual(g.xs("x"), "x")
        self.assertEqual(g.xs("xxxx"), "xxxx")
        self.assertRaises(ParseError, g.xs, "xy")
        self.assertRaises(ParseError, g.xs, "")


    def test_repeat(self):
        """
        Match repetitions can be specifically numbered.
        """
        g = self.compile("xs = 'x'{2, 4}:n 'x'* -> n")
        self.assertEqual(g.xs("xx"), "xx")
        self.assertEqual(g.xs("xxxx"), "xxxx")
        self.assertEqual(g.xs("xxxxxx"), "xxxx")
        self.assertRaises(ParseError, g.xs, "x")
        self.assertRaises(ParseError, g.xs, "")


    def test_repeat_single(self):
        """
        Match repetitions can be specifically numbered.
        """
        g = self.compile("xs = 'x'{3}:n 'x'* -> n")
        self.assertEqual(g.xs("xxx"), "xxx")
        self.assertEqual(g.xs("xxxxxx"), "xxx")
        self.assertRaises(ParseError, g.xs, "xx")

    def test_repeat_zero(self):
        """
        Match repetitions can be specifically numbered.
        """
        g = self.compile("xs = 'x'{0}:n 'y' -> n")
        self.assertEqual(g.xs("y"), "")
        self.assertRaises(ParseError, g.xs, "xy")

    def test_repeat_zero_n(self):
        """
        Match repetitions can be specifically numbered.
        """
        g = self.compile("""
                         xs :n = 'x'{n}:a 'y' -> a
                         start = xs(0)
                         """)
        self.assertEqual(g.start("y"), "")
        self.assertRaises(ParseError, g.start, "xy")


    def test_repeat_var(self):
        """
        Match repetitions can be variables.
        """
        g = self.compile("xs = (:v -> int(v)):n 'x'{n}:xs 'x'* -> xs")
        self.assertEqual(g.xs("2xx"), "xx")
        self.assertEqual(g.xs("4xxxx"), "xxxx")
        self.assertEqual(g.xs("3xxxxxx"), "xxx")
        self.assertRaises(ParseError, g.xs, "2x")
        self.assertRaises(ParseError, g.xs, "1")


    def test_sequencing(self):
        """
        Input matches can be made on a sequence of patterns.
        """
        g = self.compile("twelve = '1' '2'")
        self.assertEqual(g.twelve("12"), "2");
        self.assertRaises(ParseError, g.twelve, "1")


    def test_alternatives(self):
        """
        Input matches can be made on one of a set of alternatives.
        """
        g = self.compile("digit = '0' | '1' | '2'")
        self.assertEqual(g.digit("0"), "0")
        self.assertEqual(g.digit("1"), "1")
        self.assertEqual(g.digit("2"), "2")
        self.assertRaises(ParseError, g.digit, "3")


    def test_optional(self):
        """
        Subpatterns can be made optional.
        """
        g = self.compile("foo = 'x' 'y'? 'z'")
        self.assertEqual(g.foo("xyz"), 'z')
        self.assertEqual(g.foo("xz"), 'z')


    def test_apply(self):
        """
        Other productions can be invoked from within a production.
        """
        g = self.compile("""
              digit = '0' | '1'
              bits = digit+
            """)
        self.assertEqual(g.bits('0110110'), '0110110')


    def test_negate(self):
        """
        Input can be matched based on its failure to match a pattern.
        """
        g = self.compile("foo = ~'0' anything")
        self.assertEqual(g.foo("1"), "1")
        self.assertRaises(ParseError, g.foo, "0")


    def test_ruleValue(self):
        """
        Productions can specify a Python expression that provides the result
        of the parse.
        """
        g = self.compile("foo = '1' -> 7")
        self.assertEqual(g.foo('1'), 7)


    def test_lookahead(self):
        """
        Doubled negation does lookahead.
        """
        g = self.compile("""
                         foo = ~~(:x) bar(x)
                         bar :x = :a :b ?(x == a == b) -> x
                         """)
        self.assertEqual(g.foo("11"), '1')
        self.assertEqual(g.foo("22"), '2')


    def test_binding(self):
        """
        The result of a parsing expression can be bound to a single name
        or names surrounded by parentheses.
        """
        g = self.compile("foo = '1':x -> int(x) * 2")
        self.assertEqual(g.foo("1"), 2)
        g = self.compile("foo = '1':(x) -> int(x) * 2")
        self.assertEqual(g.foo("1"), 2)
        g = self.compile("foo = (-> 3, 4):(x, y) -> x")
        self.assertEqual(g.foo(""), 3)
        g = self.compile("foo = (-> 1, 2):(x, y) -> int(x) * 2 + int(y)")
        self.assertEqual(g.foo(""), 4)


    def test_bindingAccess(self):
        """
        Bound names in a rule can be accessed on the grammar's "locals" dict.
        """
        G = self.classTested.makeGrammar(
            "stuff = '1':a ('2':b | '3':c)", 'TestGrammar').createParserClass(OMetaBase, {})
        g = G("12")
        self.assertEqual(g.apply("stuff")[0], '2')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['b'], '2')
        g = G("13")
        self.assertEqual(g.apply("stuff")[0], '3')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['c'], '3')
        G = self.classTested.makeGrammar(
            "stuff = '1':a ('2':(b) | '345':(c, d, e))", 'TestGrammar').createParserClass(OMetaBase, {})
        g = G("12")
        self.assertEqual(g.apply("stuff")[0], '2')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['b'], '2')
        g = G("1345")
        self.assertEqual(g.apply("stuff")[0], '345')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['c'], '3')
        self.assertEqual(g.locals['stuff']['d'], '4')
        self.assertEqual(g.locals['stuff']['e'], '5')


    def test_predicate(self):
        """
        Python expressions can be used to determine the success or
        failure of a parse.
        """
        g = self.compile("""
              digit = '0' | '1'
              double_bits = digit:a digit:b ?(a == b) -> int(b)
           """)
        self.assertEqual(g.double_bits("00"), 0)
        self.assertEqual(g.double_bits("11"), 1)
        self.assertRaises(ParseError, g.double_bits, "10")
        self.assertRaises(ParseError, g.double_bits, "01")


    def test_parens(self):
        """
        Parens can be used to group subpatterns.
        """
        g = self.compile("foo = 'a' ('b' | 'c')")
        self.assertEqual(g.foo("ab"), "b")
        self.assertEqual(g.foo("ac"), "c")


    def test_action(self):
        """
        Python expressions can be run as actions with no effect on the
        result of the parse.
        """
        g = self.compile("""foo = ('1'*:ones !(False) !(ones.insert(0, '0')) -> ''.join(ones))""")
        self.assertEqual(g.foo("111"), "0111")


    def test_bindNameOnly(self):
        """
        A pattern consisting of only a bind name matches a single element and
        binds it to that name.
        """
        g = self.compile("foo = '1' :x '2' -> x")
        self.assertEqual(g.foo("132"), "3")


    def test_args(self):
        """
        Productions can take arguments.
        """
        g = self.compile("""
              digit = ('0' | '1' | '2'):d -> int(d)
              foo :x = (?(int(x) > 1) '9' | ?(int(x) <= 1) '8'):d -> int(d)
              baz = digit:a foo(a):b -> [a, b]
            """)
        self.assertEqual(g.baz("18"), [1, 8])
        self.assertEqual(g.baz("08"), [0, 8])
        self.assertEqual(g.baz("29"), [2, 9])
        self.assertRaises(ParseError, g.baz, "28")


    def test_patternMatch(self):
        """
        Productions can pattern-match on arguments.
        Also, multiple definitions of a rule can be done in sequence.
        """
        g = self.compile("""
              fact 0                    -> 1
              fact :n = fact((n - 1)):m -> n * m
           """)
        self.assertEqual(g.fact([3]), 6)


    def test_listpattern(self):
        """
        Brackets can be used to match contents of lists.
        """
        g = self.compile("""
             digit  = :x ?(x.isdigit())     -> int(x)
             interp = [digit:x '+' digit:y] -> x + y
           """)
        self.assertEqual(g.interp([['3', '+', '5']]), 8)

    def test_listpatternresult(self):
        """
        The result of a list pattern is the entire list.
        """
        g = self.compile("""
             digit  = :x ?(x.isdigit())       -> int(x)
             interp = [digit:x '+' digit:y]:z -> (z, x + y)
        """)
        e = ['3', '+', '5']
        self.assertEqual(g.interp([e]), (e, 8))

    def test_recursion(self):
        """
        Rules can call themselves.
        """
        g = self.compile("""
             interp = (['+' interp:x interp:y] -> x + y
                       | ['*' interp:x interp:y] -> x * y
                       | :x ?(isinstance(x, str) and x.isdigit()) -> int(x))
             """)
        self.assertEqual(g.interp([['+', '3', ['*', '5', '2']]]), 13)


    def test_leftrecursion(self):
         """
         Left-recursion is detected and compiled appropriately.
         """
         g = self.compile("""
               num = (num:n digit:d   -> n * 10 + d
                      | digit)
               digit = :x ?(x.isdigit()) -> int(x)
              """)
         self.assertEqual(g.num("3"), 3)
         self.assertEqual(g.num("32767"), 32767)


    def test_characterVsSequence(self):
        """
        Characters (in single-quotes) are not regarded as sequences.
        """
        g = self.compile("""
        interp = ([interp:x '+' interp:y] -> x + y
                  | [interp:x '*' interp:y] -> x * y
                  | :x ?(isinstance(x, basestring) and x.isdigit()) -> int(x))
        """)
        self.assertEqual(g.interp([['3', '+', ['5', '*', '2']]]), 13)
        self.assertEqual(g.interp([['3', '+', ['5', '*', '2']]]), 13)


    def test_stringConsumedBy(self):
        """
        OMeta2's "consumed-by" operator works on strings.
        """
        g = self.compile("""
        ident = <letter (letter | digit)*>
        """)
        self.assertEqual(g.ident("a"), "a")
        self.assertEqual(g.ident("abc"), "abc")
        self.assertEqual(g.ident("a1z"), "a1z")
        self.assertRaises(ParseError, g.ident, "1a")


    def test_label(self):
        """
        Custom labels change the 'expected' in the raised exceptions.
        """
        label = 'Letter not starting with digit'
        g = self.compile("ident = (<letter (letter | digit)*>) ^ (" + label + ")")
        self.assertEqual(g.ident("a"), "a")
        self.assertEqual(g.ident("abc"), "abc")
        self.assertEqual(g.ident("a1z"), "a1z")

        e = self.assertRaises(ParseError, g.ident, "1a")
        self.assertEqual(e, ParseError(0, 0, expected(label)).withMessage([("Custom Exception:", label, None)]))

    def test_label2(self):
        """
        Custom labels change the 'expected' in the raised exceptions.
        """
        label = 'lots of xs'
        g = self.compile("xs = ('x'*) ^ (" + label + ")")
        self.assertEqual(g.xs(""), "")
        self.assertEqual(g.xs("x"), "x")
        self.assertEqual(g.xs("xxx"), "xxx")
        e = self.assertRaises(ParseError, g.xs, "xy")
        self.assertEqual(e, ParseError(0, 1, expected(label)).withMessage([("Custom Exception:", label, None)]))


    def test_listConsumedBy(self):
        """
        OMeta2's "consumed-by" operator works on lists.
        """
        g = self.compile("""
        ands = [<"And" (ors | vals)*>:x] -> x
        ors = [<"Or" vals*:x>] -> x
        vals = 1 | 0
        """)
        self.assertEqual(g.ands([["And", ["Or", 1, 0], 1]]),
                         ["And", ["Or", 1, 0], 1])


    def test_string(self):
        """
        Strings in double quotes match string objects.
        """
        g = self.compile("""
             interp = ["Foo" 1 2] -> 3
           """)
        self.assertEqual(g.interp([["Foo", 1, 2]]), 3)

    def test_argEscape(self):
        """
        Regression test for bug #239344.
        """
        g = self.compile("""
            memo_arg :arg = anything ?(False)
            trick = letter memo_arg('c')
            broken = trick | anything*
        """)
        self.assertEqual(g.broken('ab'), 'ab')


class TermActionGrammarTests(OMetaTestCase):

    classTested = TermOMeta

    def test_binding(self):
        """
        The result of a parsing expression can be bound to a name.
        """
        g = self.compile("foo = '1':x -> mul(int(x), 2)",
                         {"mul": operator.mul})
        self.assertEqual(g.foo("1"), 2)


    def test_bindingAccess(self):
        """
        Bound names in a rule can be accessed on the grammar's "locals" dict.
        """
        G = self.classTested.makeGrammar(
            "stuff = '1':a ('2':b | '3':c)", 'TestGrammar').createParserClass(OMetaBase, {})
        g = G("12")
        self.assertEqual(g.apply("stuff")[0], '2')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['b'], '2')
        g = G("13")
        self.assertEqual(g.apply("stuff")[0], '3')
        self.assertEqual(g.locals['stuff']['a'], '1')
        self.assertEqual(g.locals['stuff']['c'], '3')


    def test_predicate(self):
        """
        Term actions can be used to determine the success or
        failure of a parse.
        """
        g = self.compile("""
              digit = '0' | '1'
              double_bits = digit:a digit:b ?(equal(a, b)) -> int(b)
           """, {"equal": operator.eq})
        self.assertEqual(g.double_bits("00"), 0)
        self.assertEqual(g.double_bits("11"), 1)
        self.assertRaises(ParseError, g.double_bits, "10")
        self.assertRaises(ParseError, g.double_bits, "01")


    def test_action(self):
        """
        Term actions can be run as actions with no effect on the
        result of the parse.
        """
        g = self.compile(
            """foo = ('1'*:ones !(False)
                     !(nconc(ones, '0')) -> join(ones))""",
            {"nconc": lambda lst, val: lst.insert(0, val),
             "join": ''.join})
        self.assertEqual(g.foo("111"), "0111")


    def test_patternMatch(self):
        """
        Productions can pattern-match on arguments.
        Also, multiple definitions of a rule can be done in sequence.
        """
        g = self.compile("""
              fact 0                    -> 1
              fact :n = fact(decr(n)):m -> mul(n, m)
           """, {"mul": operator.mul, "decr": lambda x: x -1})
        self.assertEqual(g.fact([3]), 6)


    def test_listpattern(self):
        """
        Brackets can be used to match contents of lists.
        """
        g = self.compile("""
             digit  = :x ?(x.isdigit())     -> int(x)
             interp = [digit:x '+' digit:y] -> add(x, y)
           """, {"add": operator.add})
        self.assertEqual(g.interp([['3', '+', '5']]), 8)


    def test_listpatternresult(self):
        """
        The result of a list pattern is the entire list.
        """
        g = self.compile("""
             digit  = :x ?(x.isdigit())       -> int(x)
             interp = [digit:x '+' digit:y]:z -> [z, plus(x, y)]
        """, {"plus": operator.add})
        e = ['3', '+', '5']
        self.assertEqual(g.interp([e]), [e, 8])


    def test_recursion(self):
        """
        Rules can call themselves.
        """
        g = self.compile("""
             interp = (['+' interp:x interp:y]   -> add(x, y)
                       | ['*' interp:x interp:y] -> mul(x, y)
                       | :x ?(isdigit(x)) -> int(x))
             """, {"mul": operator.mul,
                   "add": operator.add,
                   "isdigit": lambda x: str(x).isdigit()})
        self.assertEqual(g.interp([['+', '3', ['*', '5', '2']]]), 13)


    def test_leftrecursion(self):
         """
         Left-recursion is detected and compiled appropriately.
         """
         g = self.compile("""
               num = (num:n digit:d   -> makeInt(n, d)
                      | digit)
               digit = :x ?(isdigit(x)) -> int(x)
              """, {"makeInt": lambda x, y: x * 10 + y,
                    "isdigit": lambda x: x.isdigit()})
         self.assertEqual(g.num("3"), 3)
         self.assertEqual(g.num("32767"), 32767)

    def test_characterVsSequence(self):
        """
        Characters (in single-quotes) are not regarded as sequences.
        """
        g = self.compile(
            """
        interp = ([interp:x '+' interp:y] -> add(x, y)
                  | [interp:x '*' interp:y] -> mul(x, y)
                  | :x ?(isdigit(x)) -> int(x))
        """,
            {"add": operator.add, "mul": operator.mul,
             "isdigit": lambda x: isinstance(x, basestring) and x.isdigit()})

        self.assertEqual(g.interp([['3', '+', ['5', '*', '2']]]), 13)
        self.assertEqual(g.interp([['3', '+', ['5', '*', '2']]]), 13)


    def test_string(self):
        """
        Strings in double quotes match string objects.
        """
        g = self.compile("""
             interp = ["Foo" 1 2] -> 3
           """)
        self.assertEqual(g.interp([["Foo", 1, 2]]), 3)

    def test_argEscape(self):
        """
        Regression test for bug #239344.
        """
        g = self.compile("""
            memo_arg :arg = anything ?(False)
            trick = letter memo_arg('c')
            broken = trick | anything*
        """)
        self.assertEqual(g.broken('ab'), 'ab')


    def test_lookahead(self):
        """
        Doubled negation does lookahead.
        """
        g = self.compile("""
                         foo = ~~(:x) bar(x)
                         bar :x = :a :b ?(equal(x, a, b)) -> x
                         """,
                         {"equal": lambda i, j, k: i == j == k})
        self.assertEqual(g.foo("11"), '1')
        self.assertEqual(g.foo("22"), '2')


    def test_args(self):
        """
        Productions can take arguments.
        """
        g = self.compile("""
              digit = ('0' | '1' | '2'):d -> int(d)
              foo :x = (?(gt(int(x), 1)) '9' | ?(lte(int(x), 1)) '8'):d -> int(d)
              baz = digit:a foo(a):b -> [a, b]
            """, {"lte": operator.le, "gt": operator.gt})
        self.assertEqual(g.baz("18"), [1, 8])
        self.assertEqual(g.baz("08"), [0, 8])
        self.assertEqual(g.baz("29"), [2, 9])
        self.assertRaises(ParseError, g.foo, "28")



class PyExtractorTest(TestCase):
    """
    Tests for finding Python expressions in OMeta grammars.
    """

    def findInGrammar(self, expr):
        """
        L{OMeta.pythonExpr()} can extract a single Python expression from a
        string, ignoring the text following it.
        """
        o = OMetaGrammarBase(expr + "\nbaz = ...\n")
        self.assertEqual(o.pythonExpr()[0][0], expr)


    def test_expressions(self):
        """
        L{OMeta.pythonExpr()} can recognize various paired delimiters properly
        and include newlines in expressions where appropriate.
        """
        self.findInGrammar("x")
        self.findInGrammar("(x + 1)")
        self.findInGrammar("{x: (y)}")
        self.findInGrammar("x, '('")
        self.findInGrammar('x, "("')
        self.findInGrammar('x, """("""')
        self.findInGrammar('(x +\n 1)')
        self.findInGrammar('[x, "]",\n 1]')
        self.findInGrammar('{x: "]",\ny: "["}')

        o = OMetaGrammarBase("foo(x[1]])\nbaz = ...\n")
        self.assertRaises(ParseError, o.pythonExpr)
        o = OMetaGrammarBase("foo(x[1]\nbaz = ...\n")
        self.assertRaises(ParseError, o.pythonExpr)


class MakeGrammarTest(TestCase):
    """
    Test the definition of grammars via the 'makeGrammar' method.
    """


    def test_makeGrammar(self):
        results = []
        grammar = """
        digit = :x ?('0' <= x <= '9') -> int(x)
        num = (num:n digit:d !(results.append(True)) -> n * 10 + d
               | digit)
        """
        TestGrammar = OMeta.makeGrammar(grammar, "G").createParserClass(OMetaBase, {'results':results})
        g = TestGrammar("314159")
        self.assertEqual(g.apply("num")[0], 314159)
        self.assertNotEqual(len(results), 0)


    def test_brokenGrammar(self):
        grammar = """
        andHandler = handler:h1 'and handler:h2 -> And(h1, h2)
        """
        e = self.assertRaises(ParseError, OMeta.makeGrammar, grammar,
                              "Foo")
        self.assertEqual(e.position, 57)
        self.assertEqual(e.error, [("message", "end of input")])


    def test_subclassing(self):
        """
        A subclass of an OMeta subclass should be able to call rules on its
        parent, and access variables in its scope.
        """
        grammar1 = """
        dig = :x ?(a <= x <= b) -> int(x)
        """
        TestGrammar1 = OMeta.makeGrammar(grammar1, "G").createParserClass(OMetaBase, {'a':'0', 'b':'9'})

        grammar2 = """
        num = (num:n dig:d -> n * base + d
                | dig)
        """
        TestGrammar2 = OMeta.makeGrammar(grammar2, "G2").createParserClass(TestGrammar1, {'base':10})
        g = TestGrammar2("314159")
        self.assertEqual(g.apply("num")[0], 314159)

        grammar3 = """
        dig = :x ?(a <= x <= b or c <= x <= d) -> int(x, base)
        """
        TestGrammar3 = OMeta.makeGrammar(grammar3, "G3").createParserClass(
            TestGrammar2, {'c':'a', 'd':'f', 'base':16})
        g = TestGrammar3("abc123")
        self.assertEqual(g.apply("num")[0], 11256099)


    def test_super(self):
        """
        Rules can call the implementation in a superclass.
        """
        grammar1 = "expr = letter"
        TestGrammar1 = OMeta.makeGrammar(grammar1, "G").createParserClass(OMetaBase, {})
        grammar2 = "expr = super | digit"
        TestGrammar2 = OMeta.makeGrammar(grammar2, "G2").createParserClass(TestGrammar1, {})
        self.assertEqual(TestGrammar2("x").apply("expr")[0], "x")
        self.assertEqual(TestGrammar2("3").apply("expr")[0], "3")

    def test_foreign(self):
        """
        Rules can call the implementation in a superclass.
        """
        grammar_letter = "expr = letter"
        GrammarLetter = OMeta.makeGrammar(grammar_letter, "G").createParserClass(OMetaBase, {})

        grammar_digit = "expr '5' = digit"
        GrammarDigit = OMeta.makeGrammar(grammar_digit, "H").createParserClass(OMetaBase, {})

        grammar = ("expr = !(grammar_digit_global):grammar_digit "
                        "grammar_letter.expr | grammar_digit.expr('5')")
        TestGrammar = OMeta.makeGrammar(grammar, "I").createParserClass(
            OMetaBase,
            {"grammar_letter": GrammarLetter,
             "grammar_digit_global": GrammarDigit
         })

        self.assertEqual(TestGrammar("x").apply("expr")[0], "x")
        self.assertEqual(TestGrammar("3").apply("expr")[0], "3")


class HandyInterpWrapper(object):
    """
    Convenient grammar wrapper for parsing strings.
    """
    def __init__(self, interp):
        self._interp = interp


    def __getattr__(self, name):
        """
        Return a function that will instantiate a grammar and invoke the named
        rule.
        @param: Rule name.
        """
        def doIt(s):
            """
            @param s: The string to be parsed by the wrapped grammar.
            """
            # totally cheating
            tree = not isinstance(s, basestring)

            input, ret, err = self._interp.apply(s, name, tree)
            try:
                extra, _ = input.head()
            except EOFError:
                try:
                    return ''.join(ret)
                except TypeError:
                    return ret
            else:
                raise err
        return doIt


class InterpTestCase(OMetaTestCase):

    def compile(self, grammar, globals=None):
        """
        Produce an object capable of parsing via this grammar.

        @param grammar: A string containing an OMeta grammar.
        """
        g = OMeta(grammar)
        tree = g.parseGrammar('TestGrammar')
        g = GrammarInterpreter(tree, OMetaBase, globals)
        return HandyInterpWrapper(g)


class TrampolinedInterpWrapper(object):
    """
    Convenient grammar wrapper for parsing strings.
    """
    def __init__(self, tree, globals):
        self._tree = tree
        self._globals = globals


    def __getattr__(self, name):
        """
        Return a function that will instantiate a grammar and invoke the named
        rule.
        @param: Rule name.
        """
        def doIt(s):
            """
            @param s: The string to be parsed by the wrapped grammar.
            """
            tree = not isinstance(s, basestring)
            if tree:
                raise unittest.SkipTest("Not applicable for push parsing")
            results = []
            def whenDone(val, err):
                results.append(val)
            parser = TrampolinedGrammarInterpreter(self._tree, name, whenDone,
                                                   self._globals)
            for i, c in enumerate(s):
                assert len(results) == 0
                parser.receive(c)
            parser.end()
            if results and parser.input.position == len(parser.input.data):
                try:
                    return ''.join(results[0])
                except TypeError:
                    return results[0]
            else:
                raise parser.currentError
        return doIt



class TrampolinedInterpreterTestCase(OMetaTestCase):

    def compile(self, grammar, globals=None):
        g = OMeta(grammar)
        tree = g.parseGrammar('TestGrammar')
        return TrampolinedInterpWrapper(tree, globals)


    def test_failure(self):
        g = OMeta("""
           foo = 'a':one baz:two 'd'+ 'e' -> (one, two)
           baz = 'b' | 'c'
           """, {})
        tree = g.parseGrammar('TestGrammar')
        i = TrampolinedGrammarInterpreter(
            tree, 'foo', callback=lambda x: setattr(self, 'result', x))
        e = self.assertRaises(ParseError, i.receive, 'foobar')
        self.assertEqual(str(e),
        "\nfoobar\n^\nParse error at line 1, column 0:"
        " expected the character 'a'. trail: []\n")


    def test_stringConsumedBy(self):
        called = []
        grammarSource = "rule = <'x'+>:y -> y"
        grammar = OMeta(grammarSource).parseGrammar("Parser")
        def interp(result, error):
            called.append(result)
        trampoline = TrampolinedGrammarInterpreter(grammar, "rule", interp)
        trampoline.receive("xxxxx")
        trampoline.end()
        self.assertEqual(called, ["xxxxx"])



class TreeTransformerTestCase(TestCase):

    def compile(self, grammar, namespace=None):
        """
        Produce an object capable of parsing via this grammar.

        @param grammar: A string containing an OMeta grammar.
        """
        if namespace is None:
            namespace = globals()
        g = TreeTransformerGrammar.makeGrammar(
            dedent(grammar), 'TestGrammar').createParserClass(
                TreeTransformerBase, namespace)
        return g

    def test_termForm(self):
        g = self.compile("Foo(:left :right) -> left.data + right.data")
        self.assertEqual(g.transform(term("Foo(1, 2)"))[0], 3)

    def test_termFormNest(self):
        g = self.compile("Foo(:left Baz(:right)) -> left.data + right.data")
        self.assertEqual(g.transform(term("Foo(1, Baz(2))"))[0], 3)

    def test_listForm(self):
        g = self.compile("Foo(:left [:first :second]) -> left.data + first.data + second.data")
        self.assertEqual(g.transform(term("Foo(1, [2, 3])"))[0], 6)

    def test_emptyList(self):
        g = self.compile("Foo([]) -> 6")
        self.assertEqual(g.transform(term("Foo([])"))[0], 6)

    def test_emptyArgs(self):
        g = self.compile("Foo() -> 6")
        self.assertEqual(g.transform(term("Foo()"))[0], 6)

    def test_emptyArgsMeansEmpty(self):
        g = self.compile("""
                         Foo() -> 6
                         Foo(:x) -> x
                         """)
        self.assertEqual(g.transform(term("Foo(3)"))[0].data, 3)

    def test_subTransform(self):
        g = self.compile("""
                         Foo(:left @right) -> left.data + right
                         Baz(:front :back) -> front.data * back.data
                         """)
        self.assertEqual(g.transform(term("Foo(1, Baz(2, 3))"))[0], 7)

    def test_defaultExpand(self):
        g = self.compile("""
                         Foo(:left @right) -> left.data + right
                         Baz(:front :back) -> front.data * back.data
                         """)
        self.assertEqual(g.transform(term("Blee(Foo(1, 2), Baz(2, 3))"))[0],
                         term("Blee(3, 6)"))

    def test_wide_template(self):
        g = self.compile(
            """
            Pair(@left @right) --> $left, $right
            Name(@n) = ?(n == "a") --> foo
                     |             --> baz
            """)
        self.assertEqual(g.transform(term('Pair(Name("a"), Name("b"))'))[0],
                         "foo, baz")

    def test_tall_template(self):
        g = self.compile(
            """
            Name(@n) = ?(n == "a") --> foo
                     |             --> baz
            Pair(@left @right) {{{
            $left
            also, $right
            }}}
            """)
        self.assertEqual(g.transform(term('Pair(Name("a"), Name("b"))'))[0],
                         "foo\nalso, baz")

    def test_tall_template_suite(self):
        g = self.compile(
            """
            Name(@n) -> n
            If(@test @suite) {{{
            if $test:
              $suite
            }}}
            """)
        self.assertEqual(g.transform(term('If(Name("a"), [Name("foo"), Name("baz")])'))[0],
                         "if a:\n  foo\n  baz")

    def test_foreign(self):
        """
        Rules can call the implementation in a superclass.
        """
        grammar_letter = "expr = letter"
        GrammarLetter = self.compile(grammar_letter, {})

        grammar_digit = "expr '5' = digit"
        GrammarDigit = self.compile(grammar_digit, {})

        grammar = ("expr = !(grammar_digit_global):grammar_digit "
                   "GrammarLetter.expr | grammar_digit.expr('5')")
        TestGrammar = self.compile(grammar, {
            "GrammarLetter": GrammarLetter,
            "grammar_digit_global": GrammarDigit
        })

        self.assertEqual(TestGrammar("x").apply("expr")[0], "x")
        self.assertEqual(TestGrammar("3").apply("expr")[0], "3")



class ErrorReportingTests(TestCase):


    def compile(self, grammar):
        """
        Produce an object capable of parsing via this grammar.

        @param grammar: A string containing an OMeta grammar.
        """
        g = OMeta.makeGrammar(grammar, 'TestGrammar').createParserClass(OMetaBase, {})
        return HandyWrapper(g)


    def test_rawReporting(self):
        """
        Errors from parsing contain enough info to figure out what was
        expected and where.
        """
        g = self.compile("""

        start = ( (person feeling target)
                  | (adjective animal feeling token("some") target))
        adjective = token("crazy") | token("clever") | token("awesome")
        feeling = token("likes") | token("loves") | token("hates")
        animal = token("monkey") | token("horse") | token("unicorn")
        person = token("crazy horse") | token("hacker")
        target = (token("bananas") | token("robots") | token("americans")
                   | token("bacon"))
        """)

        #some warmup
        g.start("clever monkey hates some robots")
        g.start("awesome unicorn loves some bacon")
        g.start("crazy horse hates americans")
        g.start("hacker likes robots")

        e = self.assertRaises(ParseError, g.start,
                              "clever hacker likes bacon")
        self.assertEqual(e.position, 8)
        self.assertEqual(e.error, [('expected', "token", "horse")])

        e = self.assertRaises(ParseError, g.start,
                              "crazy horse likes some grass")

        #matching "some" means second branch of 'start' is taken
        self.assertEqual(e.position, 23)
        self.assertEqual(set(e.error),
                set([('expected', "token", "bananas"),
                     ('expected', 'token', "bacon"),
                     ('expected', "token", "robots"),
                     ('expected', "token", "americans")]))

        e = self.assertRaises(ParseError, g.start,
                              "crazy horse likes mountains")

        #no "some" means first branch of 'start' is taken...
        #but second is also viable
        self.assertEqual(e.position, 18)
        self.assertEqual(set(e.error),
                set([('expected', "token", "some"),
                     ('expected', "token", "bananas"),
                     ('expected', 'token', "bacon"),
                     ('expected', "token", "robots"),
                     ('expected', "token", "americans")]))


    def test_formattedReporting(self):
        """
        Parse errors can be formatted into a nice human-readable view
        containing the erroneous input and possible fixes.
        """
        g = self.compile("""
        dig = '1' | '2' | '3'
        bits = <dig>+
        """)

        input = "123x321"
        e = self.assertRaises(ParseError, g.bits, input)
        self.assertEqual(e.formatError(),
                         dedent("""
                         123x321
                            ^
                         Parse error at line 1, column 3: expected one of '1', '2', or '3'. trail: [dig]
                         """))
        input = "foo\nbaz\nboz\ncharlie\nbuz"
        e = ParseError(input, 12, expected('token', 'foo') + expected(None, 'b'))
        self.assertEqual(e.formatError(),
                         dedent("""
                         charlie
                         ^
                         Parse error at line 4, column 0: expected one of 'b', or token 'foo'. trail: []
                         """))

        input = '123x321'
        e = ParseError(input, 3, expected('digit'))
        self.assertEqual(e.formatError(),
                         dedent("""
                         123x321
                            ^
                         Parse error at line 1, column 3: expected a digit. trail: []
                         """))

    def test_customLabels(self):
        """
        Custom labels replace the 'expected' part of the exception.
        """
        g = self.compile("""
        dig = ('1' | '2' | '3') ^ (1 2 or 3)
        bits = <dig>+
        """)

        input = "123x321"
        e = self.assertRaises(ParseError, g.bits, input)
        self.assertEqual(e.formatError(),
                         dedent("""
                         123x321
                            ^
                         Parse error at line 1, column 3: expected a 1 2 or 3. trail: [dig]
                         """))

    def test_customLabelsFormatting(self):
        """
        Custom labels replace the 'expected' part of the exception.
        """

        input = "foo\nbaz\nboz\ncharlie\nbuz"
        label = 'Fizz Buzz'
        e = ParseError(input, 12, None).withMessage([("Custom Exception:", label, None)])
        self.assertEqual(e.formatError(),
                         dedent("""
                         charlie
                         ^
                         Parse error at line 4, column 0: expected a Fizz Buzz. trail: []
                         """))

    def test_eof(self):
        """
        EOF should raise a nice error.
        """
        import parsley
        g = parsley.makeGrammar("""
        dig = '1' | '2' | '3'
        bits = <dig>+
        """, {})

        input = '123x321'
        e = self.assertRaises(ParseError, g(input).dig)
        self.assertEqual(e.formatError(),
                         dedent("""
                         123x321
                          ^
                         Parse error at line 1, column 1: expected EOF. trail: []
                         """))