summaryrefslogtreecommitdiffstats
path: root/src/xmlpatterns/parser/querytransformparser.ypp
blob: 64a30434b2694e68144576fe5d97264a60191740 (plain)
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
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.

%{
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.

#include <limits>

#include <QUrl>

#include "qabstractfloat_p.h"
#include "qandexpression_p.h"
#include "qanyuri_p.h"
#include "qapplytemplate_p.h"
#include "qargumentreference_p.h"
#include "qarithmeticexpression_p.h"
#include "qatomicstring_p.h"
#include "qattributeconstructor_p.h"
#include "qattributenamevalidator_p.h"
#include "qaxisstep_p.h"
#include "qbuiltintypes_p.h"
#include "qcalltemplate_p.h"
#include "qcastableas_p.h"
#include "qcastas_p.h"
#include "qcombinenodes_p.h"
#include "qcommentconstructor_p.h"
#include "qcommonnamespaces_p.h"
#include "qcommonsequencetypes_p.h"
#include "qcommonvalues_p.h"
#include "qcomputednamespaceconstructor_p.h"
#include "qcontextitem_p.h"
#include "qcopyof_p.h"
#include "qcurrentitemstore_p.h"
#include "qdebug_p.h"
#include "qdelegatingnamespaceresolver_p.h"
#include "qdocumentconstructor_p.h"
#include "qelementconstructor_p.h"
#include "qemptysequence_p.h"
#include "qemptysequencetype_p.h"
#include "qevaluationcache_p.h"
#include "qexpressionfactory_p.h"
#include "qexpressionsequence_p.h"
#include "qexpressionvariablereference_p.h"
#include "qexternalvariablereference_p.h"
#include "qforclause_p.h"
#include "qfunctioncall_p.h"
#include "qfunctionfactory_p.h"
#include "qfunctionsignature_p.h"
#include "qgeneralcomparison_p.h"
#include "qgenericpredicate_p.h"
#include "qgenericsequencetype_p.h"
#include "qifthenclause_p.h"
#include "qinstanceof_p.h"
#include "qletclause_p.h"
#include "qliteral_p.h"
#include "qlocalnametest_p.h"
#include "qnamespaceconstructor_p.h"
#include "qnamespacenametest_p.h"
#include "qncnameconstructor_p.h"
#include "qnodecomparison_p.h"
#include "qnodesort_p.h"
#include "qorderby_p.h"
#include "qorexpression_p.h"
#include "qparsercontext_p.h"
#include "qpath_p.h"
#include "qpatternistlocale_p.h"
#include "qpositionalvariablereference_p.h"
#include "qprocessinginstructionconstructor_p.h"
#include "qqnameconstructor_p.h"
#include "qqnametest_p.h"
#include "qqnamevalue_p.h"
#include "qquantifiedexpression_p.h"
#include "qrangeexpression_p.h"
#include "qrangevariablereference_p.h"
#include "qreturnorderby_p.h"
#include "qschemanumeric_p.h"
#include "qschematypefactory_p.h"
#include "qsimplecontentconstructor_p.h"
#include "qstaticbaseuristore_p.h"
#include "qstaticcompatibilitystore_p.h"
#include "qtemplateparameterreference_p.h"
#include "qtemplate_p.h"
#include "qtextnodeconstructor_p.h"
#include "qtokenizer_p.h"
#include "qtreatas_p.h"
#include "qtypechecker_p.h"
#include "qunaryexpression_p.h"
#include "qunresolvedvariablereference_p.h"
#include "quserfunctioncallsite_p.h"
#include "qvaluecomparison_p.h"
#include "qxpathhelper_p.h"
#include "qxsltsimplecontentconstructor_p.h"

/*
 * The cpp generated with bison 2.1 wants to
 * redeclare the C-like prototypes of 'malloc' and 'free', so we avoid that.
 */
#define YYMALLOC malloc
#define YYFREE free

QT_BEGIN_NAMESPACE

/* Due to Qt's QT_BEGIN_NAMESPACE magic, we can't use `using namespace', for some
 * undocumented reason. */
namespace QPatternist
{

/**
 * "Macro that you define with #define in the Bison declarations
 * section to request verbose, specific error message strings when
 * yyerror is called."
 */
#define YYERROR_VERBOSE 1

#undef YYLTYPE_IS_TRIVIAL
#define YYLTYPE_IS_TRIVIAL 0

/* Suppresses `warning: "YYENABLE_NLS" is not defined`
 * @c YYENABLE_NLS enables Bison internationalization, and we don't
 * use that, so disable it. See the Bison Manual, section 4.5 Parser Internationalization.
 */
#define YYENABLE_NLS 0

static inline QSourceLocation fromYYLTYPE(const YYLTYPE &sourceLocator,
                                          const ParserContext *const parseInfo)
{
    return QSourceLocation(parseInfo->tokenizer->queryURI(),
                           sourceLocator.first_line,
                           sourceLocator.first_column);
}

/**
 * @internal
 * @relates QXmlQuery
 */
typedef QFlags<QXmlQuery::QueryLanguage> QueryLanguages;

/**
 * @short Flags invalid expressions and declarations in the currently
 * parsed language.
 *
 * Since this grammar is used for several languages: XQuery 1.0, XSL-T 2.0, and
 * XPath 2.0 inside XSL-T, and field and selector patterns in W3C XML Schema's
 * identity constraints, it is the union of all the constructs in these
 * languages. However, when dealing with each language individually, we
 * regularly need to disallow some expressions, such as direct element
 * constructors when parsing XSL-T, or the typeswitch when parsing XPath.
 *
 * This is further complicated by that XSLTTokenizer sometimes generates code
 * which is allowed in XQuery but not in XPath. For that reason the token
 * INTERNAL is sometimes generated, which signals that an expression, for
 * instance the @c let clause, should not be flagged as an error, because it's
 * used for internal purposes.
 *
 * Hence, this function is called from each expression and declaration with @p
 * allowedLanguages stating what languages it is allowed in.
 *
 * If @p isInternal is @c true, no error is raised. Otherwise, if the current
 * language is not in @p allowedLanguages, an error is raised.
 */
static void allowedIn(const QueryLanguages allowedLanguages,
                      const ParserContext *const parseInfo,
                      const YYLTYPE &sourceLocator,
                      const bool isInternal = false)
{
    /* We treat XPath 2.0 as a subset of XSL-T 2.0, so if XPath 2.0 is allowed
     * and XSL-T is the language, it's ok. */
    if(!isInternal &&
       (!allowedLanguages.testFlag(parseInfo->languageAccent) && !(allowedLanguages.testFlag(QXmlQuery::XPath20) && parseInfo->languageAccent == QXmlQuery::XSLT20)))
    {

        QString langName;

        switch(parseInfo->languageAccent)
        {
            case QXmlQuery::XPath20:
                langName = QLatin1String("XPath 2.0");
                break;
            case QXmlQuery::XSLT20:
                langName = QLatin1String("XSL-T 2.0");
                break;
            case QXmlQuery::XQuery10:
                langName = QLatin1String("XQuery 1.0");
                break;
            case QXmlQuery::XmlSchema11IdentityConstraintSelector:
                langName = QtXmlPatterns::tr("W3C XML Schema identity constraint selector");
                break;
            case QXmlQuery::XmlSchema11IdentityConstraintField:
                langName = QtXmlPatterns::tr("W3C XML Schema identity constraint field");
                break;
        }

        parseInfo->staticContext->error(QtXmlPatterns::tr("A construct was encountered "
                                                          "which is disallowed in the current language(%1).").arg(langName),
                                        ReportContext::XPST0003,
                                        fromYYLTYPE(sourceLocator, parseInfo));

    }
}

static inline bool isVariableReference(const Expression::ID id)
{
    return    id == Expression::IDExpressionVariableReference
           || id == Expression::IDRangeVariableReference
           || id == Expression::IDArgumentReference;
}

class ReflectYYLTYPE : public SourceLocationReflection
{
public:
    inline ReflectYYLTYPE(const YYLTYPE &sourceLocator,
                          const ParserContext *const pi) : m_sl(sourceLocator)
                                                         , m_parseInfo(pi)
    {
    }

    virtual const SourceLocationReflection *actualReflection() const
    {
        return this;
    }

    virtual QSourceLocation sourceLocation() const
    {
        return fromYYLTYPE(m_sl, m_parseInfo);
    }

    virtual QString description() const
    {
        Q_ASSERT(false);
        return QString();
    }

private:
    const YYLTYPE &m_sl;
    const ParserContext *const m_parseInfo;
};

/**
 * @short Centralizes a translation string for the purpose of increasing consistency.
 */
static inline QString unknownType()
{
    return QtXmlPatterns::tr("%1 is an unknown schema type.");
}

static inline Expression::Ptr create(Expression *const expr,
                                     const YYLTYPE &sourceLocator,
                                     const ParserContext *const parseInfo)
{
    parseInfo->staticContext->addLocation(expr, fromYYLTYPE(sourceLocator, parseInfo));
    return Expression::Ptr(expr);
}

static inline Template::Ptr create(Template *const expr,
                                   const YYLTYPE &sourceLocator,
                                   const ParserContext *const parseInfo)
{
    parseInfo->staticContext->addLocation(expr, fromYYLTYPE(sourceLocator, parseInfo));
    return Template::Ptr(expr);
}

static inline Expression::Ptr create(const Expression::Ptr &expr,
                                     const YYLTYPE &sourceLocator,
                                     const ParserContext *const parseInfo)
{
    parseInfo->staticContext->addLocation(expr.data(), fromYYLTYPE(sourceLocator, parseInfo));
    return expr;
}

static Expression::Ptr createSimpleContent(const Expression::Ptr &source,
                                           const YYLTYPE &sourceLocator,
                                           const ParserContext *const parseInfo)
{
    return create(parseInfo->isXSLT() ? new XSLTSimpleContentConstructor(source) : new SimpleContentConstructor(source),
                  sourceLocator,
                  parseInfo);
}

static void loadPattern(const Expression::Ptr &matchPattern,
                        TemplatePattern::Vector &ourPatterns,
                        const TemplatePattern::ID id,
                        const PatternPriority priority,
                        const Template::Ptr &temp)
{
    Q_ASSERT(temp);

    const PatternPriority effectivePriority = qIsNaN(priority) ? matchPattern->patternPriority() : priority;

    ourPatterns.append(TemplatePattern::Ptr(new TemplatePattern(matchPattern, effectivePriority, id, temp)));
}

static Expression::Ptr typeCheckTemplateBody(const Expression::Ptr &body,
                                             const SequenceType::Ptr &reqType,
                                             const ParserContext *const parseInfo)
{
    return TypeChecker::applyFunctionConversion(body, reqType,
                                                parseInfo->staticContext,
                                                ReportContext::XTTE0505,
                                                TypeChecker::Options(TypeChecker::AutomaticallyConvert | TypeChecker::GeneratePromotion));
}

static void registerNamedTemplate(const QXmlName &name,
                                  const Expression::Ptr &body,
                                  ParserContext *const parseInfo,
                                  const YYLTYPE &sourceLocator,
                                  const Template::Ptr &temp)
{
    Template::Ptr &e = parseInfo->namedTemplates[name];

    if(e)
    {
        parseInfo->staticContext->error(QtXmlPatterns::tr("A template by name %1 "
                                                          "has already been declared.")
                                        .arg(formatKeyword(parseInfo->staticContext->namePool(),
                                                                         name)),
                                        ReportContext::XTSE0660,
                                        fromYYLTYPE(sourceLocator, parseInfo));
    }
    else
    {
        e = temp;
        e->body = body;
    }
}

/**
 * @short Centralizes code for creating numeric literals.
 */
template<typename TNumberClass>
Expression::Ptr createNumericLiteral(const QString &in,
                                     const YYLTYPE &sl,
                                     const ParserContext *const parseInfo)
{
    const Item num(TNumberClass::fromLexical(in));

    if(num.template as<AtomicValue>()->hasError())
    {
        parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is not a valid numeric literal.")
                                           .arg(formatData(in)),
                                        ReportContext::XPST0003, fromYYLTYPE(sl, parseInfo));
        return Expression::Ptr(); /* Avoid compiler warning. */
    }
    else
        return create(new Literal(num), sl, parseInfo);
}

/**
 * @short The generated Bison parser calls this function when there is a parse error.
 *
 * It is not called, nor should be, for logical errors(which the Bison not know about). For those,
 * ReportContext::error() is called.
 */
static int XPatherror(YYLTYPE *sourceLocator, const ParserContext *const parseInfo, const char *const msg)
{
    Q_UNUSED(sourceLocator);
    Q_ASSERT(parseInfo);

    parseInfo->staticContext->error(escape(QLatin1String(msg)), ReportContext::XPST0003, fromYYLTYPE(*sourceLocator, parseInfo));
    return 1;
}

/**
 * When we want to connect the OrderBy and ReturnOrderBy, it might be that we have other expressions, such
 * as @c where and @c let inbetween. We need to continue through them. This function does that.
 */
static ReturnOrderBy *locateReturnClause(const Expression::Ptr &expr)
{
    Q_ASSERT(expr);

    const Expression::ID id = expr->id();
    if(id == Expression::IDLetClause || id == Expression::IDIfThenClause || id == Expression::IDForClause)
        return locateReturnClause(expr->operands()[1]);
    else if(id == Expression::IDReturnOrderBy)
        return expr->as<ReturnOrderBy>();
    else
        return 0;
}

static inline bool isPredicate(const Expression::ID id)
{
    return id == Expression::IDGenericPredicate ||
           id == Expression::IDFirstItemPredicate;
}

/**
 * Assumes expr is an AxisStep wrapped in some kind of predicates or paths. Filters
 * through the predicates and returns the AxisStep.
 */
static Expression::Ptr findAxisStep(const Expression::Ptr &expr,
                                    const bool throughStructures = true)
{
    Q_ASSERT(expr);

    if(!throughStructures)
        return expr;

    Expression *candidate = expr.data();
    Expression::ID id = candidate->id();

    while(isPredicate(id) || id == Expression::IDPath)
    {
        const Expression::List &children = candidate->operands();
        if(children.isEmpty())
            return Expression::Ptr();
        else
        {
            candidate = children.first().data();
            id = candidate->id();
        }
    }

    if(id == Expression::IDEmptySequence)
        return Expression::Ptr();
    else
    {
        Q_ASSERT(candidate->is(Expression::IDAxisStep));
        return Expression::Ptr(candidate);
    }
}

static void changeToTopAxis(const Expression::Ptr &op)
{
    /* This axis must have been written away by now. */
    Q_ASSERT(op->as<AxisStep>()->axis() != QXmlNodeModelIndex::AxisChild);

    if(op->as<AxisStep>()->axis() != QXmlNodeModelIndex::AxisSelf)
        op->as<AxisStep>()->setAxis(QXmlNodeModelIndex::AxisAttributeOrTop);
}

/**
 * @short Writes @p operand1 and @p operand2, two operands in an XSL-T pattern,
 * into an equivalent XPath expression.
 *
 * Essentially, the following rewrite is done:
 *
 * <tt>
 * axis1::test1(a)/axis2::test2(b)
 *              =>
 * child-or-top::test2(b)[parent::test1(a)]
 * </tt>
 *
 * Section 5.5.3 The Meaning of a Pattern talks about rewrites that are applied to
 * only the first step in a pattern, but since we're doing rewrites more radically,
 * its line of reasoning cannot be followed.
 *
 * Keep in mind the rewrites that non-terminal PatternStep do.
 *
 * @see createIdPatternPath()
 */
static inline Expression::Ptr createPatternPath(const Expression::Ptr &operand1,
                                                const Expression::Ptr &operand2,
                                                const QXmlNodeModelIndex::Axis axis,
                                                const YYLTYPE &sl,
                                                const ParserContext *const parseInfo)
{
    const Expression::Ptr operandL(findAxisStep(operand1, false));

    if(operandL->is(Expression::IDAxisStep))
        operandL->as<AxisStep>()->setAxis(axis);
    else
        findAxisStep(operand1)->as<AxisStep>()->setAxis(axis);

    return create(GenericPredicate::create(operand2, operandL,
                                           parseInfo->staticContext, fromYYLTYPE(sl, parseInfo)), sl, parseInfo);
}

/**
 * @short Performs the same role as createPatternPath(), but is tailored
 * for @c fn:key() and @c fn:id().
 *
 * @c fn:key() and @c fn:id() can be part of path patterns(only as the first step,
 * to be precise) and that poses a challenge to rewriting because what
 * createPatternPath() is not possible to express, since the functions cannot be
 * node tests. E.g, this rewrite is not possible:
 *
 * <tt>
 * id-or-key/abc
 *  =>
 * child-or-top::abc[parent::id-or-key]
 * </tt>
 *
 * Our approach is to rewrite like this:
 *
 * <tt>
 * id-or-key/abc
 * =>
 * child-or-top::abc[parent::node is id-or-key]
 * </tt>
 *
 * @p operand1 is the call to @c fn:key() or @c fn:id(), @p operand2
 * the right operand, and @p axis the target axis to rewrite to.
 *
 * @see createPatternPath()
 */
static inline Expression::Ptr createIdPatternPath(const Expression::Ptr &operand1,
                                                  const Expression::Ptr &operand2,
                                                  const QXmlNodeModelIndex::Axis axis,
                                                  const YYLTYPE &sl,
                                                  const ParserContext *const parseInfo)
{
    const Expression::Ptr operandR(findAxisStep(operand2));
    Q_ASSERT(operandR);
    changeToTopAxis(operandR);

    const Expression::Ptr parentStep(create(new AxisStep(axis, BuiltinTypes::node),
                                            sl,
                                            parseInfo));
    const Expression::Ptr isComp(create(new NodeComparison(parentStep,
                                                           QXmlNodeModelIndex::Is,
                                                           operand1),
                                         sl,
                                         parseInfo));

    return create(GenericPredicate::create(operandR, isComp,
                                           parseInfo->staticContext, fromYYLTYPE(sl, parseInfo)), sl, parseInfo);
}

/**
 * @short Centralizes a translation message, for the
 * purpose of consistency and modularization.
 */
static inline QString prologMessage(const char *const msg)
{
    Q_ASSERT(msg);
    return QtXmlPatterns::tr("Only one %1 declaration can occur in the query prolog.").arg(formatKeyword(msg));
}

/**
 * @short Resolves against the static base URI and checks that @p collation
 * is a supported Unicode Collation.
 *
 * "If a default collation declaration specifies a collation by a
 *  relative URI, that relative URI is resolved to an absolute
 *  URI using the base URI in the static context."
 *
 * @returns the Unicode Collation properly resolved, if @p collation is a valid collation
 */
template<const ReportContext::ErrorCode errorCode>
static QUrl resolveAndCheckCollation(const QString &collation,
                                     const ParserContext *const parseInfo,
                                     const YYLTYPE &sl)
{
    Q_ASSERT(parseInfo);
    const ReflectYYLTYPE ryy(sl, parseInfo);

    QUrl uri(AnyURI::toQUrl<ReportContext::XQST0046>(collation, parseInfo->staticContext, &ryy));

    if(uri.isRelative())
        uri = parseInfo->staticContext->baseURI().resolved(uri);

    XPathHelper::checkCollationSupport<errorCode>(uri.toString(), parseInfo->staticContext, &ryy);

    return uri;
}

/* The Bison generated parser declares macros that aren't used
 * so suppress the warnings by fake usage of them.
 *
 * We do the same for some more defines in the first action. */
#if    defined(YYLSP_NEEDED)    \
    || defined(YYBISON)         \
    || defined(YYBISON_VERSION) \
    || defined(YYPURE)          \
    || defined(yydebug)         \
    || defined(YYSKELETON_NAME)
#endif

/**
 * Wraps @p operand with a CopyOf in case it makes any difference.
 *
 * There is no need to wrap the return value in a call to create(), it's
 * already done.
 */
static Expression::Ptr createCopyOf(const Expression::Ptr &operand,
                                    const ParserContext *const parseInfo,
                                    const YYLTYPE &sl)
{
    return create(new CopyOf(operand, parseInfo->inheritNamespacesMode,
                             parseInfo->preserveNamespacesMode), sl, parseInfo);
}

static Expression::Ptr createCompatStore(const Expression::Ptr &expr,
                                         const YYLTYPE &sourceLocator,
                                         const ParserContext *const parseInfo)
{
    return create(new StaticCompatibilityStore(expr), sourceLocator, parseInfo);
}

/**
 * @short Creates an Expression that corresponds to <tt>/</tt>. This is literally
 * <tt>fn:root(self::node()) treat as document-node()</tt>.
 */
static Expression::Ptr createRootExpression(const ParserContext *const parseInfo,
                                            const YYLTYPE &sl)
{
    Q_ASSERT(parseInfo);
    const QXmlName name(StandardNamespaces::fn, StandardLocalNames::root);

    Expression::List args;
    args.append(create(new ContextItem(), sl, parseInfo));

    const ReflectYYLTYPE ryy(sl, parseInfo);

    const Expression::Ptr fnRoot(parseInfo->staticContext->functionSignatures()
                                 ->createFunctionCall(name, args, parseInfo->staticContext, &ryy));
    Q_ASSERT(fnRoot);

    return create(new TreatAs(create(fnRoot, sl, parseInfo), CommonSequenceTypes::ExactlyOneDocumentNode), sl, parseInfo);
}

static int XPathlex(YYSTYPE *lexVal, YYLTYPE *sourceLocator, const ParserContext *const parseInfo)
{
#ifdef Patternist_DEBUG_PARSER
    /**
     * "External integer variable set to zero by default. If yydebug
     *  is given a nonzero value, the parser will output information on
     *  input symbols and parser action. See section Debugging Your Parser."
     */
#   define YYDEBUG 1

    extern int XPathdebug;
    XPathdebug = 1;
#endif

    Q_ASSERT(parseInfo);

    const Tokenizer::Token tok(parseInfo->tokenizer->nextToken(sourceLocator));

    (*lexVal).sval = tok.value;

    return static_cast<int>(tok.type);
}

/**
 * @short Creates a path expression which contains the step <tt>//</tt> between
 * @p begin and and @p end.
 *
 * <tt>begin//end</tt> is a short form for: <tt>begin/descendant-or-self::node()/end</tt>
 *
 * This will be compiled as two-path expression: <tt>(/)/(//.)/step/</tt>
 */
static Expression::Ptr createSlashSlashPath(const Expression::Ptr &begin,
                                            const Expression::Ptr &end,
                                            const YYLTYPE &sourceLocator,
                                            const ParserContext *const parseInfo)
{
    const Expression::Ptr twoSlash(create(new AxisStep(QXmlNodeModelIndex::AxisDescendantOrSelf, BuiltinTypes::node), sourceLocator, parseInfo));
    const Expression::Ptr p1(create(new Path(begin, twoSlash), sourceLocator, parseInfo));

    return create(new Path(p1, end), sourceLocator, parseInfo);
}

/**
 * @short Creates a call to <tt>fn:concat()</tt> with @p args as the arguments.
 */
static inline Expression::Ptr createConcatFN(const ParserContext *const parseInfo,
                                             const Expression::List &args,
                                             const YYLTYPE &sourceLocator)
{
    Q_ASSERT(parseInfo);
    const QXmlName name(StandardNamespaces::fn, StandardLocalNames::concat);
    const ReflectYYLTYPE ryy(sourceLocator, parseInfo);

    return create(parseInfo->staticContext->functionSignatures()->createFunctionCall(name, args, parseInfo->staticContext, &ryy),
                  sourceLocator, parseInfo);
}

static inline Expression::Ptr createDirAttributeValue(const Expression::List &content,
                                                      const ParserContext *const parseInfo,
                                                      const YYLTYPE &sourceLocator)
{
    if(content.isEmpty())
        return create(new EmptySequence(), sourceLocator, parseInfo);
    else if(content.size() == 1)
        return content.first();
    else
        return createConcatFN(parseInfo, content, sourceLocator);
}

/**
 * @short Checks for variable initialization circularity.
 *
 * "A recursive function that checks for recursion is full of ironies."
 *
 *      -- The Salsa Master
 *
 * Issues an error via @p parseInfo's StaticContext if the initialization
 * expression @p checkee for the global variable @p var, contains a variable
 * reference to @p var. That is, if there's a circularity.
 *
 * @see <a href="http://www.w3.org/TR/xquery/#ERRXQST0054">XQuery 1.0: An XML
 * Query Language, err:XQST0054</a>
 */
static void checkVariableCircularity(const VariableDeclaration::Ptr &var,
                                     const Expression::Ptr &checkee,
                                     const VariableDeclaration::Type type,
                                     FunctionSignature::List &signList,
                                     const ParserContext *const parseInfo)
{
    Q_ASSERT(var);
    Q_ASSERT(checkee);
    Q_ASSERT(parseInfo);

    const Expression::ID id = checkee->id();

    if(id == Expression::IDExpressionVariableReference)
    {
        const ExpressionVariableReference *const ref =
                    static_cast<const ExpressionVariableReference *>(checkee.data());

        if(var->slot == ref->slot() && type == ref->variableDeclaration()->type)
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("The initialization of variable %1 "
                                                              "depends on itself").arg(formatKeyword(var, parseInfo->staticContext->namePool())),
                                            parseInfo->isXSLT() ? ReportContext::XTDE0640 : ReportContext::XQST0054, ref);
            return;
        }
        else
        {
            /* If the variable we're checking is below another variable, it can be a recursive
             * dependency through functions, so we need to check variable references too. */
            checkVariableCircularity(var, ref->sourceExpression(), type, signList, parseInfo);
            return;
        }
    }
    else if(id == Expression::IDUserFunctionCallsite)
    {
        const UserFunctionCallsite::Ptr callsite(checkee);
        const FunctionSignature::Ptr sign(callsite->callTargetDescription());
        const FunctionSignature::List::const_iterator end(signList.constEnd());
        FunctionSignature::List::const_iterator it(signList.constBegin());
        bool noMatch = true;

        for(; it != end; ++it)
        {
            if(*it == sign)
            {
                /* The variable we're checking is depending on a function that's recursive. The
                 * user has written a weird query, in other words. Since it's the second time
                 * we've encountered a callsite, we now skip it. */
                noMatch = false;
                break;
            }
        }

        if(noMatch)
        {
            signList.append(sign);
            /* Check the body of the function being called. */
            checkVariableCircularity(var, callsite->body(), type, signList, parseInfo);
        }
        /* Continue with the operands, such that we also check the arguments of the callsite. */
    }
    else if(id == Expression::IDUnresolvedVariableReference)
    {
        /* We're called before it has rewritten itself. */
        checkVariableCircularity(var, checkee->as<UnresolvedVariableReference>()->replacement(), type, signList, parseInfo);
    }

    /* Check the operands. */
    const Expression::List ops(checkee->operands());
    if(ops.isEmpty())
        return;

    const Expression::List::const_iterator end(ops.constEnd());
    Expression::List::const_iterator it(ops.constBegin());

    for(; it != end; ++it)
        checkVariableCircularity(var, *it, type, signList, parseInfo);
}

static void variableUnavailable(const QXmlName &variableName,
                                const ParserContext *const parseInfo,
                                const YYLTYPE &location)
{
    parseInfo->staticContext->error(QtXmlPatterns::tr("No variable with name %1 exists")
                                       .arg(formatKeyword(parseInfo->staticContext->namePool(), variableName)),
                                    ReportContext::XPST0008, fromYYLTYPE(location, parseInfo));
}

/**
 * The Cardinality in a TypeDeclaration for a variable in a quantification has no effect,
 * and this function ensures this by changing @p type to Cardinality Cardinality::zeroOrMore().
 *
 * @see <a href="http://www.w3.org/Bugs/Public/show_bug.cgi?id=3305">Bugzilla Bug 3305
 * Cardinality + on range variables</a>
 * @see ParserContext::finalizePushedVariable()
 */
static inline SequenceType::Ptr quantificationType(const SequenceType::Ptr &type)
{
    Q_ASSERT(type);
    return makeGenericSequenceType(type->itemType(), Cardinality::zeroOrMore());
}

/**
 * @p seqType and @p expr may be @c null.
 */
static Expression::Ptr pushVariable(const QXmlName name,
                                    const SequenceType::Ptr &seqType,
                                    const Expression::Ptr &expr,
                                    const VariableDeclaration::Type type,
                                    const YYLTYPE &sourceLocator,
                                    ParserContext *const parseInfo,
                                    const bool checkSource = true)
{
    Q_ASSERT(!name.isNull());
    Q_ASSERT(parseInfo);

    /* -2 will cause Q_ASSERTs to trigger if it isn't changed. */
    VariableSlotID slot = -2;

    switch(type)
    {
        case VariableDeclaration::FunctionArgument:
        /* Fallthrough. */
        case VariableDeclaration::ExpressionVariable:
        {
            slot = parseInfo->allocateExpressionSlot();
            break;
        }
        case VariableDeclaration::GlobalVariable:
        {
            slot = parseInfo->allocateGlobalVariableSlot();
            break;
        }
        case VariableDeclaration::RangeVariable:
        {
            slot = parseInfo->staticContext->allocateRangeSlot();
            break;
        }
        case VariableDeclaration::PositionalVariable:
        {
            slot = parseInfo->allocatePositionalSlot();
            break;
        }
        case VariableDeclaration::TemplateParameter:
            /* Fallthrough. We do nothing, template parameters
             * doesn't use context slots at all, they're hashed
             * on the name. */
        case VariableDeclaration::ExternalVariable:
            /* We do nothing, external variables doesn't use
             *context slots/stack frames at all. */
            ;
    }

    const VariableDeclaration::Ptr var(new VariableDeclaration(name, slot, type, seqType));

    Expression::Ptr checked;

    if(checkSource && seqType)
    {
        if(expr)
        {
            /* We only want to add conversion for function arguments, and variables
             * if we're XSL-T.
             *
             * We unconditionally skip TypeChecker::CheckFocus because the StaticContext we
             * pass hasn't set up the focus yet, since that's the parent's responsibility. */
            const TypeChecker::Options options((   type == VariableDeclaration::FunctionArgument
                                                || type == VariableDeclaration::TemplateParameter
                                                || parseInfo->isXSLT())
                                               ? TypeChecker::AutomaticallyConvert : TypeChecker::Options());

            checked = TypeChecker::applyFunctionConversion(expr, seqType, parseInfo->staticContext,
                                                           parseInfo->isXSLT() ? ReportContext::XTTE0570 : ReportContext::XPTY0004,
                                                           options);
        }
    }
    else
        checked = expr;

    /* Add an evaluation cache for all expression variables. No EvaluationCache is needed for
     * positional variables because in the end they are calls to Iterator::position(). Similarly,
     * no need to cache range variables either because they are calls to DynamicContext::rangeVariable().
     *
     * We don't do it for function arguments because the Expression being cached depends -- it depends
     * on the callsite. UserFunctionCallsite is responsible for the evaluation caches in that case.
     *
     * In some cases the EvaluationCache instance isn't necessary, but in those cases EvaluationCache
     * optimizes itself away. */
    if(type == VariableDeclaration::ExpressionVariable)
        checked = create(new EvaluationCache<false>(checked, var, parseInfo->allocateCacheSlot()), sourceLocator, parseInfo);
    else if(type == VariableDeclaration::GlobalVariable)
        checked = create(new EvaluationCache<true>(checked, var, parseInfo->allocateCacheSlot()), sourceLocator, parseInfo);

    var->setExpression(checked);

    parseInfo->variables.push(var);
    return checked;
}

static inline VariableDeclaration::Ptr variableByName(const QXmlName name,
                                                      const ParserContext *const parseInfo)
{
    Q_ASSERT(!name.isNull());
    Q_ASSERT(parseInfo);

    /* We walk the list backwards. */
    const VariableDeclaration::Stack::const_iterator start(parseInfo->variables.constBegin());
    VariableDeclaration::Stack::const_iterator it(parseInfo->variables.constEnd());

    while(it != start)
    {
        --it;
        Q_ASSERT(*it);
        if((*it)->name == name)
            return *it;
    }

    return VariableDeclaration::Ptr();
}

static Expression::Ptr resolveVariable(const QXmlName &name,
                                       const YYLTYPE &sourceLocator,
                                       ParserContext *const parseInfo,
                                       const bool raiseErrorOnUnavailability)
{
    const VariableDeclaration::Ptr var(variableByName(name, parseInfo));
    Expression::Ptr retval;

    if(var && var->type != VariableDeclaration::ExternalVariable)
    {
        switch(var->type)
        {
            case VariableDeclaration::RangeVariable:
            {
                retval = create(new RangeVariableReference(var->expression(), var->slot), sourceLocator, parseInfo);
                break;
            }
            case VariableDeclaration::GlobalVariable:
            /* Fallthrough. From the perspective of an ExpressionVariableReference, it can't tell
             * a difference between a global and a local expression variable. However, the cache
             * mechanism must. */
            case VariableDeclaration::ExpressionVariable:
            {
                retval = create(new ExpressionVariableReference(var->slot, var), sourceLocator, parseInfo);
                break;
            }
            case VariableDeclaration::FunctionArgument:
            {
                retval = create(new ArgumentReference(var->sequenceType, var->slot), sourceLocator, parseInfo);
                break;
            }
            case VariableDeclaration::PositionalVariable:
            {
                retval = create(new PositionalVariableReference(var->slot), sourceLocator, parseInfo);
                break;
            }
            case VariableDeclaration::TemplateParameter:
            {
                retval = create(new TemplateParameterReference(var), sourceLocator, parseInfo);
                break;
            }
            case VariableDeclaration::ExternalVariable:
                /* This code path will never be hit, but the case
                 * label silences a warning. See above. */
                ;
        }
        Q_ASSERT(retval);
        var->references.append(retval);
    }
    else
    {
        /* Let's see if your external variable loader can provide us with one. */
        const SequenceType::Ptr varType(parseInfo->staticContext->
                                        externalVariableLoader()->announceExternalVariable(name, CommonSequenceTypes::ZeroOrMoreItems));

        if(varType)
        {
            const Expression::Ptr extRef(create(new ExternalVariableReference(name, varType), sourceLocator, parseInfo));
            const Expression::Ptr checked(TypeChecker::applyFunctionConversion(extRef, varType, parseInfo->staticContext));
            retval = checked;
        }
        else if(!raiseErrorOnUnavailability && parseInfo->isXSLT())
        {
            /* In XSL-T, global variables are in scope for the whole
             * stylesheet, so we must resolve this first at the end. */
            retval = create(new UnresolvedVariableReference(name), sourceLocator, parseInfo);
            parseInfo->unresolvedVariableReferences.insert(name, retval);
        }
        else
            variableUnavailable(name, parseInfo, sourceLocator);
    }

    return retval;
}

static Expression::Ptr createReturnOrderBy(const OrderSpecTransfer::List &orderSpecTransfer,
                                           const Expression::Ptr &returnExpr,
                                           const OrderBy::Stability stability,
                                           const YYLTYPE &sourceLocator,
                                           const ParserContext *const parseInfo)
{
    // TODO do resize(orderSpec.size() + 1)
    Expression::List exprs;
    OrderBy::OrderSpec::Vector orderSpecs;

    exprs.append(returnExpr);

    const int len = orderSpecTransfer.size();

    for(int i = 0; i < len; ++i)
    {
        exprs.append(orderSpecTransfer.at(i).expression);
        orderSpecs.append(orderSpecTransfer.at(i).orderSpec);
    }

    return create(new ReturnOrderBy(stability, orderSpecs, exprs), sourceLocator, parseInfo);
}

%}

/* This grammar shouldn't be compiled with anything older than the Bison version
 * specified below. This '%require' directive was introduced in Bison 2.2. */
%require "2.3a"

%name-prefix="XPath"

/* Specifies the name of the generated parser. */
%output="qquerytransformparser.cpp"

/* Output the .output file. */
%verbose

/* Yes, we want descriptive error messages. */
%error-verbose

/* We'd like to be reentrant/thread-safe */
%pure-parser

/* We want code for line/columns to be generated. */
%locations

/* Create a header file and put declarations there. */
%defines

%parse-param    {ParserContext *const parseInfo}
%lex-param      {ParserContext *const parseInfo}

%expect 4
/* Silences the following:

state 327

  293 SequenceType: ItemType . OccurrenceIndicator

    "+"  shift, and go to state 379
    "*"  shift, and go to state 380
    "?"  shift, and go to state 381

    "+"       [reduce using rule 295 (OccurrenceIndicator)]
    "*"       [reduce using rule 295 (OccurrenceIndicator)]
    $default  reduce using rule 295 (OccurrenceIndicator)

    OccurrenceIndicator  go to state 382

state 45

  200 PathExpr: "/" . RelativePathExpr
  203         | "/" .

    [...]

    "<"       [reduce using rule 203 (PathExpr)]
    "*"       [reduce using rule 203 (PathExpr)]
    $default  reduce using rule 203 (PathExpr)
*/

%token <sval> STRING_LITERAL                "<string literal>"

/**
 * This token is only used in element content and signals content that
 * is not Boundary whitespace. Nevertheless, the token value can be all whitespace,
 * but it was specified using character references or CDATA sections by the user. */
%token <sval> NON_BOUNDARY_WS               "<non-boundary text node>"

/* XPath 2.0 allows quotes and apostrophes to be escaped with "" and ''; this token is
   is used for XPath 2.0 literals such that we can flag syntax errors if running in
   1.0 mode. */
%token <sval> XPATH2_STRING_LITERAL         "<string literal(XPath 2.0)>"
%token <sval> QNAME                         "QName"
%token <sval> NCNAME                        "NCName"

/* A QName as a clark name. See QXmlName::toClarkName(). */
%token <sval> CLARK_NAME                    "ClarkName"

/**
 * Is "ncname:*". The token value does not include the colon and the star.
 */
%token <sval> ANY_LOCAL_NAME

/**
 * Is "*:ncname". The token value does not include the colon and the star.
 */
%token <sval> ANY_PREFIX

/**
 * An XPath 1.0 number literal. It is a string value because
 * Numeric::fromLexical() does the tokenization.
 */
%token <sval> NUMBER                        "<number literal>"

/**
 * XPath 2.0 number literal. It includes the use of 'e'/'E'
 */
%token <sval> XPATH2_NUMBER                 "<number literal(XPath 2.0)>"

%token ANCESTOR                             "ancestor"
%token ANCESTOR_OR_SELF                     "ancestor-or-self"
%token AND                                  "and"
%token APOS                                 "'"
%token APPLY_TEMPLATE                       "apply-template"
%token AS                                   "as"
%token ASCENDING                            "ascending"
%token ASSIGN                               ":="
%token AT                                   "at"
%token AT_SIGN                              "@"
%token ATTRIBUTE                            "attribute"
%token AVT                                  /* Synthetic token. Signals an attribute value template. */
%token BAR                                  "|"
%token BASEURI                              "base-uri"
%token BEGIN_END_TAG                        "</"
%token BOUNDARY_SPACE                       "boundary-space"
%token BY                                   "by"
%token CALL_TEMPLATE                        "call-template"
%token CASE                                 "case"
%token CASTABLE                             "castable"
%token CAST                                 "cast"
%token CHILD                                "child"
%token COLLATION                            "collation"
%token COLONCOLON                           "::"
%token COMMA                                ","
%token COMMENT                              "comment"
%token COMMENT_START                        "<!--"
%token CONSTRUCTION                         "construction"
%token COPY_NAMESPACES                      "copy-namespaces"
%token CURLY_LBRACE                         "{"
%token CURLY_RBRACE                         "}"
%token DECLARE                              "declare"
%token DEFAULT                              "default"
%token DESCENDANT                           "descendant"
%token DESCENDANT_OR_SELF                   "descendant-or-self"
%token DESCENDING                           "descending"
%token DIV                                  "div"
%token DOCUMENT                             "document"
%token DOCUMENT_NODE                        "document-node"
%token DOLLAR                               "$"
%token DOT                                  "."
%token DOTDOT                               ".."
%token ELEMENT                              "element"
%token ELSE                                 "else"
%token EMPTY                                "empty"
%token EMPTY_SEQUENCE                       "empty-sequence"
%token ENCODING                             "encoding"
%token END_OF_FILE 0                        "end of file"
%token END_SORT                             "end_sort"
%token EQ                                   "eq"
%token ERROR                                "unknown keyword" /* Used by the Tokenizer. We use the phrase "keyword" instead of "token" to be less pointy.  */
%token EVERY                                "every"
%token EXCEPT                               "except"
%token EXTERNAL                             "external"
%token FOLLOWING                            "following"
%token FOLLOWING_SIBLING                    "following-sibling"
%token FOLLOWS                              ">>"
%token FOR_APPLY_TEMPLATE                   "for-apply-template" /* Synthetic token, used in XSL-T. */
%token FOR                                  "for"
%token FUNCTION                             "function"
%token GE                                   "ge"
%token G_EQ                                 "="
%token G_GE                                 ">="
%token G_GT                                 ">"
%token G_LE                                 "<="
%token G_LT                                 "<"
%token G_NE                                 "!="
%token GREATEST                             "greatest"
%token GT                                   "gt"
%token IDIV                                 "idiv"
%token IF                                   "if"
%token IMPORT                               "import"
%token INHERIT                              "inherit"
%token IN                                   "in"
%token INSTANCE                             "instance"
%token INTERSECT                            "intersect"
%token IS                                   "is"
%token ITEM                                 "item"
%token LAX                                  "lax"
%token LBRACKET                             "["
%token LEAST                                "least"
%token LE                                   "le"
%token LET                                  "let"
%token LPAREN                               "("
%token LT                                   "lt"
%token MAP                                  "map" /* Synthetic token, used in XSL-T. */
%token MATCHES                              "matches"
%token MINUS                                "-"
%token MODE                                 "mode" /* Synthetic token, used in XSL-T. */
%token MOD                                  "mod"
%token MODULE                               "module"
%token NAME                                 "name"
%token NAMESPACE                            "namespace"
%token NE                                   "ne"
%token NODE                                 "node"
%token NO_INHERIT                           "no-inherit"
%token NO_PRESERVE                          "no-preserve"
%token OF                                   "of"
%token OPTION                               "option"
%token ORDERED                              "ordered"
%token ORDERING                             "ordering"
%token ORDER                                "order"
%token OR                                   "or"
%token PARENT                               "parent"
%token PI_START                             "<?"
%token PLUS                                 "+"
%token POSITION_SET                         /* Synthetic token. */
%token PRAGMA_END                           "#)"
%token PRAGMA_START                         "(#"
%token PRECEDES                             "<<"
%token PRECEDING                            "preceding"
%token PRECEDING_SIBLING                    "preceding-sibling"
%token PRESERVE                             "preserve"
%token PRIORITY                             "priority"
%token PROCESSING_INSTRUCTION               "processing-instruction"
%token QUESTION                             "?"
%token QUICK_TAG_END                        "/>"
%token QUOTE                                "\""
%token RBRACKET                             "]"
%token RETURN                               "return"
%token RPAREN                               ")"
%token SATISFIES                            "satisfies"
%token SCHEMA_ATTRIBUTE                     "schema-attribute"
%token SCHEMA_ELEMENT                       "schema-element"
%token SCHEMA                               "schema"
%token SELF                                 "self"
%token SEMI_COLON                           ";"
%token SLASH                                "/"
%token SLASHSLASH                           "//"
%token SOME                                 "some"
%token SORT                                 "sort" /* Synthetic token, used in XSL-T. */
%token STABLE                               "stable"
%token STAR                                 "*"
%token STRICT                               "strict"
%token STRIP                                "strip"
%token SUCCESS                              /* Synthetic token, used by the Tokenizer. */
%token <sval> COMMENT_CONTENT
%token <sval> PI_CONTENT
%token <sval> PI_TARGET
%token <sval> XSLT_VERSION                  /* Synthetic token, used in XSL-T. */
%token TEMPLATE                             "template"
%token TEXT                                 "text"
%token THEN                                 "then"
%token TO                                   "to"
%token TREAT                                "treat"
%token TUNNEL                               "tunnel" /* Synthetic token, used in XSL-T. */
%token TYPESWITCH                           "typeswitch"
%token UNION                                "union"
%token UNORDERED                            "unordered"
%token VALIDATE                             "validate"
%token VARIABLE                             "variable"
%token VERSION                              "version"
%token WHERE                                "where"
%token XQUERY                               "xquery"
%token INTERNAL                             "internal" /* Synthetic token, used in XSL-T. */
%token INTERNAL_NAME                        "internal-name" /* Synthetic token, used in XSL-T. */
%token CURRENT                              "current" /* Synthetic token, used in XSL-T. */

/* Alphabetically. */
%type <attributeHolder>             Attribute
%type <attributeHolders>            DirAttributeList
%type <cardinality>                 OccurrenceIndicator
%type <enums.axis>                  Axis AxisToken
%type <enums.boundarySpacePolicy>   BoundarySpacePolicy
%type <enums.combinedNodeOp>        IntersectOperator
%type <enums.constructionMode>      ConstructionMode
%type <enums.mathOperator>          MultiplyOperator AdditiveOperator UnaryOperator
%type <enums.nodeOperator>          NodeOperator
%type <enums.orderingEmptySequence> OrderingEmptySequence EmptynessModifier
%type <enums.sortDirection>         DirectionModifier

%type <enums.orderingMode>          OrderingMode
%type <enums.slot>                  PositionalVar
%type <enums.validationMode>        ValidationMode
%type <enums.valueOperator>         ValueComparisonOperator GeneralComparisonOperator
%type <expr>                        OrExpr AndExpr ComparisonExpr UnionExpr Literal
                                    AdditiveExpr MultiplicativeExpr PrimaryExpr FilterExpr
                                    StepExpr PathExpr RelativePathExpr Expr ExprSingle
                                    VarRef ContextItemExpr IfExpr CastExpr CastableExpr
                                    TreatExpr InstanceOfExpr ValueExpr UnaryExpr NodeComp
                                    IntersectExceptExpr RangeExpr ParenthesizedExpr
                                    ValueComp FunctionCallExpr GeneralComp ForClause
                                    WhereClause FLWORExpr ForTail QuantifiedExpr QueryBody
                                    SomeQuantificationExpr SomeQuantificationTail
                                    EveryQuantificationExpr EveryQuantificationTail
                                    ExtensionExpr EnclosedOptionalExpr VariableValue
                                    EnclosedExpr FunctionBody ValidateExpr NumericLiteral
                                    OrderingExpr TypeswitchExpr LetClause LetTail
                                    Constructor DirectConstructor DirElemConstructor
                                    ComputedConstructor CompDocConstructor CompElemConstructor
                                    CompTextConstructor CompCommentConstructor CompPIConstructor
                                    DirPIConstructor CompAttrConstructor DirElemConstructorTail
                                    AxisStep ForwardStep ReverseStep AbbrevForwardStep
                                    CaseDefault CaseClause CaseTail CompAttributeName
                                    FilteredAxisStep DirCommentConstructor CompPIName
                                    DirAttributeValue AbbrevReverseStep CompNamespaceConstructor
                                    CompElementName CompNameExpr SatisfiesClause Pattern PathPattern
                                    PatternStep RelativePathPattern IdKeyPattern OptionalAssign
                                    OptionalDefaultValue

%type <orderSpec>                   OrderSpec
%type <expressionList>              ExpressionSequence FunctionArguments
                                    DirElemContent AttrValueContent
%type <orderSpecs>                  OrderSpecList OrderByClause MandatoryOrderByClause
%type <functionArgument>            Param
%type <functionArguments>           ParamList
%type <itemType>                    KindTest ItemType AtomicType NodeTest NameTest WildCard NodeTestInAxisStep
                                    ElementTest AttributeTest SchemaElementTest SchemaAttributeTest
                                    TextTest CommentTest PITest DocumentTest AnyKindTest AnyAttributeTest
%type <qName>                       ElementName QName VarName FunctionName PragmaName TypeName NCName
                                    CaseVariable AttributeName OptionalTemplateName
                                    TemplateName Mode OptionalMode
%type <qNameVector>                 Modes OptionalModes
%type <sequenceType>                SequenceType SingleType TypeDeclaration
%type <sval>                        URILiteral StringLiteral LexicalName
%type <enums.Bool>                  IsInternal IsTunnel
%type <enums.Double>                OptionalPriority
%type <enums.pathKind>              MapOrSlash

/* Operator Precendence
 * See: http://www.w3.org/TR/xpath20/#parse-note-occurrence-indicators */
%left STAR DIV
%left PLUS MINUS

%%

/* Here, the grammar starts. In the brackets on the right you
 * find the number of corresponding EBNF rule in the XQuery 1.0 specification. If it
 * contains an X, it means the non-terminal has no counter part in the grammar, but
 * exists for implementation purposes. */
Module: VersionDecl LibraryModule                                                   /* [1] */
| VersionDecl MainModule

VersionDecl: /* empty */                                                            /* [2] */
| XQUERY VERSION StringLiteral Encoding Separator
    {

/* Suppress more compiler warnings about unused defines. */
#if    defined(YYNNTS)              \
    || defined(yyerrok)             \
    || defined(YYNSTATES)           \
    || defined(YYRHSLOC)            \
    || defined(YYRECOVERING)        \
    || defined(YYFAIL)              \
    || defined(YYERROR)             \
    || defined(YYNRULES)            \
    || defined(YYBACKUP)            \
    || defined(YYMAXDEPTH)          \
    || defined(yyclearin)           \
    || defined(YYERRCODE)           \
    || defined(YY_LOCATION_PRINT)   \
    || defined(YYLLOC_DEFAULT)
#endif

        if($3 != QLatin1String("1.0"))
        {
            const ReflectYYLTYPE ryy(@$, parseInfo);

            parseInfo->staticContext->error(QtXmlPatterns::tr("Version %1 is not supported. The supported "
                                               "XQuery version is 1.0.")
                                               .arg(formatData($3)),
                                            ReportContext::XQST0031, &ryy);
        }
    }

Encoding: /* empty */                                                               /* [X] */
| ENCODING StringLiteral
    {
        const QRegExp encNameRegExp(QLatin1String("[A-Za-z][A-Za-z0-9._\\-]*"));

        if(!encNameRegExp.exactMatch($2))
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("The encoding %1 is invalid. "
                                               "It must contain Latin characters only, "
                                               "must not contain whitespace, and must match "
                                               "the regular expression %2.")
                                            .arg(formatKeyword((yyvsp[(2) - (2)].sval)),
                                                 formatExpression(encNameRegExp.pattern())),
                                            ReportContext::XQST0087, fromYYLTYPE(@$, parseInfo));
        }
    }

MainModule: Prolog QueryBody                                                        /* [3] */
    {
        /* In XSL-T, we can have dangling variable references, so resolve them
         * before we proceed with other steps, such as checking circularity. */
        if(parseInfo->isXSLT())
        {
            typedef QHash<QXmlName, Expression::Ptr> Hash;
            const Hash::const_iterator end(parseInfo->unresolvedVariableReferences.constEnd());

            for(Hash::const_iterator it(parseInfo->unresolvedVariableReferences.constBegin()); it != end; ++it)
            {
                const Expression::Ptr body(resolveVariable(it.key(), @$, parseInfo, true)); // TODO source locations vaise
                Q_ASSERT(body);
                it.value()->as<UnresolvedVariableReference>()->bindTo(body);
            }
        }

        /* The UserFunction callsites aren't bound yet, so bind them(if possible!). */
        {
            const UserFunctionCallsite::List::const_iterator cend(parseInfo->userFunctionCallsites.constEnd());
            UserFunctionCallsite::List::const_iterator cit(parseInfo->userFunctionCallsites.constBegin());
            for(; cit != cend; ++cit) /* For each callsite. */
            {
                const UserFunctionCallsite::Ptr callsite(*cit);
                Q_ASSERT(callsite);
                const UserFunction::List::const_iterator end(parseInfo->userFunctions.constEnd());
                UserFunction::List::const_iterator it(parseInfo->userFunctions.constBegin());

                for(; it != end; ++it) /* For each UserFunction. */
                {
                    const FunctionSignature::Ptr sign((*it)->signature());
                    Q_ASSERT(sign);

                    if(callsite->isSignatureValid(sign))
                    {
                        callsite->setSource((*it),
                                            parseInfo->allocateCacheSlots((*it)->argumentDeclarations().count()));
                        break;
                    }
                }
                if(it == end)
                {
                    parseInfo->staticContext->error(QtXmlPatterns::tr("No function with signature %1 is available")
                                                       .arg(formatFunction(callsite)),
                                                    ReportContext::XPST0017, fromYYLTYPE(@$, parseInfo));
                }
            }
        }

        /* Mark callsites in UserFunction bodies as recursive, if they are. */
        {
            const UserFunction::List::const_iterator fend(parseInfo->userFunctions.constEnd());
            UserFunction::List::const_iterator fit(parseInfo->userFunctions.constBegin());
            for(; fit != fend; ++fit)
            {
                CallTargetDescription::List signList;
                signList.append((*fit)->signature());
                CallTargetDescription::checkCallsiteCircularity(signList, (*fit)->body());
            }
        }

        /* Now, check all global variables for circularity.  This is done
         * backwards because global variables are only in scope below them,
         * in XQuery. */
        {
            const VariableDeclaration::List::const_iterator start(parseInfo->declaredVariables.constBegin());
            VariableDeclaration::List::const_iterator it(parseInfo->declaredVariables.constEnd());

            while(it != start)
            {
                --it;
                if((*it)->type != VariableDeclaration::ExpressionVariable && (*it)->type != VariableDeclaration::GlobalVariable)
                    continue; /* We want to ignore 'external' variables. */

                FunctionSignature::List signList;
                checkVariableCircularity(*it, (*it)->expression(), (*it)->type, signList, parseInfo);
                ExpressionFactory::registerLastPath((*it)->expression());
                parseInfo->finalizePushedVariable(1, false); /* Warn if it's unused. */
            }
        }

        /* Generate code for doing initial template name calling. One problem
         * is that we compilation in the initial template name, since we throw away the
         * code if we don't have the requested template. */
        if(parseInfo->languageAccent == QXmlQuery::XSLT20
           && !parseInfo->initialTemplateName.isNull()
           && parseInfo->namedTemplates.contains(parseInfo->initialTemplateName))
        {
            parseInfo->queryBody = create(new CallTemplate(parseInfo->initialTemplateName,
                                                           WithParam::Hash()),
                                          @$, parseInfo);
            parseInfo->templateCalls.append(parseInfo->queryBody);
            /* We just discard the template body that XSLTTokenizer generated. */
        }
        else
            parseInfo->queryBody = $2;
    }

LibraryModule: ModuleDecl Prolog                                                    /* [4] */

ModuleDecl: MODULE NAMESPACE NCNAME G_EQ URILiteral Separator                       /* [5] */
    {
        // TODO add to namespace context
        parseInfo->moduleNamespace = parseInfo->staticContext->namePool()->allocateNamespace($3);
    }

Prolog: /* Empty. */                                                                /* [6] */
/* First part. */
| Prolog DefaultNamespaceDecl
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
        if(parseInfo->hasSecondPrologPart)
            parseInfo->staticContext->error(QtXmlPatterns::tr("A default namespace declaration must occur before function, "
                                               "variable, and option declarations."), ReportContext::XPST0003, fromYYLTYPE(@$, parseInfo));
    }
| Prolog Setter
    {
        if(parseInfo->hasSecondPrologPart)
            parseInfo->staticContext->error(QtXmlPatterns::tr("A default namespace declaration must occur before function, "
                                               "variable, and option declarations."), ReportContext::XPST0003, fromYYLTYPE(@$, parseInfo));
    }
| Prolog NamespaceDecl
    {
        if(parseInfo->hasSecondPrologPart)
            parseInfo->staticContext->error(QtXmlPatterns::tr("Namespace declarations must occur before function, "
                                               "variable, and option declarations."), ReportContext::XPST0003, fromYYLTYPE(@$, parseInfo));
    }
| Prolog Import
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
        if(parseInfo->hasSecondPrologPart)
            parseInfo->staticContext->error(QtXmlPatterns::tr("Module imports must occur before function, "
                                               "variable, and option declarations."), ReportContext::XPST0003, fromYYLTYPE(@$, parseInfo));
    }
| Prolog TemplateDecl

/* Second part. */
| Prolog VarDecl
    {
        parseInfo->hasSecondPrologPart = true;
    }
| Prolog FunctionDecl
    {
        parseInfo->hasSecondPrologPart = true;
    }
| Prolog OptionDecl
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
        parseInfo->hasSecondPrologPart = true;
    }

/*
 * declare template name theName
 * {
 *     "expression"
 * };
 *
 * or
 *
 * declare template name theName matches (pattern) mode modeName priority 123
 * {
 *     "expression"
 * };
 *
 */
TemplateDecl: DECLARE TEMPLATE TemplateName
              OptionalTemplateParameters
              TypeDeclaration
              EnclosedOptionalExpr Separator                                        /* [X] */
    {
        Template::Ptr temp(create(new Template(parseInfo->currentImportPrecedence, $5), @$, parseInfo));

        registerNamedTemplate($3, typeCheckTemplateBody($6, $5, parseInfo),
                              parseInfo, @1, temp);
        temp->templateParameters = parseInfo->templateParameters;
        parseInfo->templateParametersHandled();
    }
| DECLARE TEMPLATE OptionalTemplateName
  MATCHES LPAREN
  {
    parseInfo->isParsingPattern = true;
  }
  Pattern
  {
    parseInfo->isParsingPattern = false;
  }
  RPAREN
  OptionalModes
  OptionalPriority
  OptionalTemplateParameters
  TypeDeclaration
  EnclosedOptionalExpr Separator                                                    /* [X] */
    {
        /* In this grammar branch, we're guaranteed to be a template rule, but
         * may also be a named template. */

        const ImportPrecedence ip = parseInfo->isFirstTemplate() ? 0 : parseInfo->currentImportPrecedence;
        Expression::Ptr pattern($7);
        const TemplatePattern::ID templateID = parseInfo->allocateTemplateID();

        Template::Ptr templ(create(new Template(ip, $13), @$, parseInfo));
        templ->body = typeCheckTemplateBody($14, $13, parseInfo);
        templ->templateParameters = parseInfo->templateParameters;
        parseInfo->templateParametersHandled();

        TemplatePattern::Vector ourPatterns;
        /* We do it as per 6.4 Conflict Resolution for Template Rules:
         *
         * "If the pattern contains multiple alternatives separated by |, then
         * the template rule is treated equivalently to a set of template
         * rules, one for each alternative. However, it is not an error if a
         * node matches more than one of the alternatives." */
        while(pattern->is(Expression::IDCombineNodes))
        {
            const Expression::List operands(pattern->operands());
            pattern = operands.first();

            loadPattern(operands.at(1), ourPatterns, templateID, $11, templ);
        }

        loadPattern(pattern, ourPatterns, templateID, $11, templ);

        if(!$3.isNull())
            registerNamedTemplate($3, $14, parseInfo, @1, templ);

        /* Now, let's add it to all the relevant templates. */
        for(int i = 0; i < $10.count(); ++i) /* For each mode. */
        {
            const QXmlName &modeName = $10.at(i);

            if(modeName == QXmlName(StandardNamespaces::InternalXSLT, StandardLocalNames::all) && $10.count() > 1)
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("The keyword %1 cannot occur with any other mode name.")
                                                                 .arg(formatKeyword(QLatin1String("#all"))),
                                                ReportContext::XTSE0530,
                                                fromYYLTYPE(@$, parseInfo));
            }

            /* For each pattern the template use. */
            const TemplateMode::Ptr mode(parseInfo->modeFor(modeName));
            for(int t = 0; t < ourPatterns.count(); ++t)
                mode->templatePatterns.append(ourPatterns.at(t));
        }
    }

OptionalPriority: /* Empty. */                                                      /* [X] */
    {
        $$ = std::numeric_limits<xsDouble>::quiet_NaN();
    }

| PRIORITY StringLiteral
    {
        const AtomicValue::Ptr val(Decimal::fromLexical($2));
        if(val->hasError())
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("The value of attribute %1 must be of type %2, which %3 isn't.")
                                                             .arg(formatKeyword(QLatin1String("priority")),
                                                                  formatType(parseInfo->staticContext->namePool(), BuiltinTypes::xsDecimal),
                                                                  formatData($2)),
                                            ReportContext::XTSE0530,
                                            fromYYLTYPE(@$, parseInfo));
        }
        else
            $$ = val->as<Numeric>()->toDouble();
    }

OptionalTemplateName: /* Empty. */                                                  /* [X] */
    {
        $$ = QXmlName();
    }
| TemplateName

TemplateName: NAME ElementName
    {
        $$ = $2;
    }

Setter: BoundarySpaceDecl                                                           /* [7] */
| DefaultCollationDecl
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
    }
| BaseURIDecl
| ConstructionDecl
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
    }
| OrderingModeDecl
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
    }
| EmptyOrderDecl
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
    }
| CopyNamespacesDecl

Import: SchemaImport                                                                /* [8] */
| ModuleImport

Separator: SEMI_COLON                                                               /* [9] */

NamespaceDecl: DECLARE NAMESPACE NCNAME G_EQ URILiteral IsInternal Separator        /* [10] */
    {
        if(!$6)
            allowedIn(QXmlQuery::XQuery10, parseInfo, @$);

        if($3 == QLatin1String("xmlns"))
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("It is not possible to redeclare prefix %1.")
                                               .arg(formatKeyword(QLatin1String("xmlns"))),
                                            ReportContext::XQST0070, fromYYLTYPE(@$, parseInfo));
        }
        else if ($5 == CommonNamespaces::XML || $3 == QLatin1String("xml"))
        {
             parseInfo->staticContext->error(QtXmlPatterns::tr(
                                            "The prefix %1 can not be bound. By default, it is already bound "
                                            "to the namespace %2.")
                                             .arg(formatKeyword("xml"))
                                             .arg(formatURI(CommonNamespaces::XML)),
                                             ReportContext::XQST0070,
                                             fromYYLTYPE(@$, parseInfo));
        }
        else if(parseInfo->declaredPrefixes.contains($3))
        {
            /* This includes the case where the user has bound a default prefix(such
             * as 'local') and now tries to do it again. */
            parseInfo->staticContext->error(QtXmlPatterns::tr("Prefix %1 is already declared in the prolog.")
                                               .arg(formatKeyword($3)),
                                            ReportContext::XQST0033, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->declaredPrefixes.append($3);

            if($5.isEmpty())
            {
                parseInfo->staticContext->namespaceBindings()->addBinding(QXmlName(StandardNamespaces::UndeclarePrefix,
                                                                                   StandardLocalNames::empty,
                                                                                   parseInfo->staticContext->namePool()->allocatePrefix($3)));
            }
            else
            {
                parseInfo->staticContext->namespaceBindings()->addBinding(parseInfo->staticContext->namePool()->allocateBinding($3, $5));
            }
        }
    }

BoundarySpaceDecl: DECLARE BOUNDARY_SPACE BoundarySpacePolicy Separator             /* [11] */
    {
        if(parseInfo->hasDeclaration(ParserContext::BoundarySpaceDecl))
        {
            parseInfo->staticContext->error(prologMessage("declare boundary-space"),
                                            ReportContext::XQST0068, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->staticContext->setBoundarySpacePolicy($3);
            parseInfo->registerDeclaration(ParserContext::BoundarySpaceDecl);
        }
    }

BoundarySpacePolicy: STRIP                                                          /* [X] */
    {
        $$ = StaticContext::BSPStrip;
    }

| PRESERVE
    {
        $$ = StaticContext::BSPPreserve;
    }

DefaultNamespaceDecl: DeclareDefaultElementNamespace                                /* [12] */
| DeclareDefaultFunctionNamespace

DeclareDefaultElementNamespace: DECLARE DEFAULT ELEMENT NAMESPACE
                                URILiteral Separator                                /* [X] */
    {
        if(parseInfo->hasDeclaration(ParserContext::DeclareDefaultElementNamespace))
        {
            parseInfo->staticContext->error(prologMessage("declare default element namespace"),
                                            ReportContext::XQST0066, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->staticContext->namespaceBindings()->addBinding(QXmlName(parseInfo->staticContext->namePool()->allocateNamespace($5), StandardLocalNames::empty));
            parseInfo->registerDeclaration(ParserContext::DeclareDefaultElementNamespace);
        }
    }

DeclareDefaultFunctionNamespace: DECLARE DEFAULT FUNCTION NAMESPACE
                                 URILiteral Separator                               /* [X] */
    {
        if(parseInfo->hasDeclaration(ParserContext::DeclareDefaultFunctionNamespace))
        {
            parseInfo->staticContext->error(prologMessage("declare default function namespace"),
                                            ReportContext::XQST0066, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->staticContext->setDefaultFunctionNamespace($5);
            parseInfo->registerDeclaration(ParserContext::DeclareDefaultFunctionNamespace);
        }
    }

OptionDecl: DECLARE OPTION ElementName StringLiteral Separator                     /* [13] */
    {
        if($3.prefix() == StandardPrefixes::empty)
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("The name of an option must have a prefix. "
                                               "There is no default namespace for options."),
                                            ReportContext::XPST0081, fromYYLTYPE(@$, parseInfo));
        }
    }

OrderingModeDecl: DECLARE ORDERING OrderingMode Separator                           /* [14] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
        if(parseInfo->hasDeclaration(ParserContext::OrderingModeDecl))
        {
            parseInfo->staticContext->error(prologMessage("declare ordering"),
                                            ReportContext::XQST0065, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->registerDeclaration(ParserContext::OrderingModeDecl);
            parseInfo->staticContext->setOrderingMode($3);
        }
    }

OrderingMode: ORDERED
    {
        $$ = StaticContext::Ordered;
    }
| UNORDERED
    {
        $$ = StaticContext::Unordered;
    }

EmptyOrderDecl: DECLARE DEFAULT ORDER OrderingEmptySequence Separator               /* [15] */
    {
        if(parseInfo->hasDeclaration(ParserContext::EmptyOrderDecl))
        {
            parseInfo->staticContext->error(prologMessage("declare default order"),
                                            ReportContext::XQST0069, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->registerDeclaration(ParserContext::EmptyOrderDecl);
            parseInfo->staticContext->setOrderingEmptySequence($4);
        }
    }

OrderingEmptySequence: EMPTY LEAST                                                  /* [X] */
    {
        $$ = StaticContext::Least;
    }
| EMPTY GREATEST
    {
        $$ = StaticContext::Greatest;
    }

CopyNamespacesDecl: DECLARE COPY_NAMESPACES PreserveMode COMMA
                    InheritMode Separator                                           /* [16] */
    {
        if(parseInfo->hasDeclaration(ParserContext::CopyNamespacesDecl))
        {
            parseInfo->staticContext->error(prologMessage("declare copy-namespaces"),
                                            ReportContext::XQST0055, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->registerDeclaration(ParserContext::CopyNamespacesDecl);
        }
    }

PreserveMode: PRESERVE                                                              /* [17] */
    {
        parseInfo->preserveNamespacesMode = true;
    }

| NO_PRESERVE
    {
        parseInfo->preserveNamespacesMode = false;
    }

InheritMode: INHERIT                                                                /* [18] */
    {
        parseInfo->inheritNamespacesMode = true;
    }

| NO_INHERIT
    {
        parseInfo->inheritNamespacesMode = false;
    }

DefaultCollationDecl: DECLARE DEFAULT COLLATION StringLiteral Separator             /* [19] */
    {
        if(parseInfo->hasDeclaration(ParserContext::DefaultCollationDecl))
        {
            parseInfo->staticContext->error(prologMessage("declare default collation"),
                                            ReportContext::XQST0038, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            const QUrl coll(resolveAndCheckCollation<ReportContext::XQST0038>($4, parseInfo, @$));

            parseInfo->registerDeclaration(ParserContext::DefaultCollationDecl);
            parseInfo->staticContext->setDefaultCollation(coll);
        }
    }

BaseURIDecl: DECLARE BASEURI IsInternal URILiteral Separator                        /* [20] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XSLT20), parseInfo, @$, $3);
        if(parseInfo->hasDeclaration(ParserContext::BaseURIDecl))
        {
            parseInfo->staticContext->error(prologMessage("declare base-uri"),
                                            ReportContext::XQST0032, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->registerDeclaration(ParserContext::BaseURIDecl);
            const ReflectYYLTYPE ryy(@$, parseInfo);

            QUrl toBeBase(AnyURI::toQUrl<ReportContext::XQST0046>($4, parseInfo->staticContext, &ryy));
            /* Now we're guaranteed that base is a valid lexical representation, but it can still be relative. */

            if(toBeBase.isRelative())
                toBeBase = parseInfo->staticContext->baseURI().resolved(toBeBase);

            parseInfo->staticContext->setBaseURI(toBeBase);
        }
    }

SchemaImport: IMPORT SCHEMA SchemaPrefix URILiteral FileLocations Separator         /* [21] */
    {
        parseInfo->staticContext->error(QtXmlPatterns::tr("The Schema Import feature is not supported, "
                                           "and therefore %1 declarations cannot occur.")
                                           .arg(formatKeyword("import schema")),
                                        ReportContext::XQST0009, fromYYLTYPE(@$, parseInfo));
    }

SchemaPrefix: /* empty */                                                           /* [22] */
| DEFAULT ELEMENT NAMESPACE
| NAMESPACE NCNAME G_EQ

ModuleImport: IMPORT MODULE ModuleNamespaceDecl URILiteral FileLocations Separator  /* [23] */
    {
        if($4.isEmpty())
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("The target namespace of a %1 cannot be empty.")
                                               .arg(formatKeyword("module import")),
                                           ReportContext::XQST0088, fromYYLTYPE(@$, parseInfo));

        }
        else
        {
            /* This is temporary until we have implemented it. */
            parseInfo->staticContext->error(QtXmlPatterns::tr("The module import feature is not supported"),
                                            ReportContext::XQST0016, fromYYLTYPE(@$, parseInfo));
        }
    }

ModuleNamespaceDecl: /* empty */                                                    /* [X] */
| NAMESPACE NCNAME G_EQ

FileLocations: /* empty */                                                          /* [X] */
| AT FileLocation

FileLocation: URILiteral                                                            /* [X] */
| FileLocation COMMA URILiteral

VarDecl: DECLARE VARIABLE IsInternal DOLLAR VarName TypeDeclaration
         VariableValue OptionalDefaultValue Separator                               /* [24] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $3);
        if(variableByName($5, parseInfo))
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("A variable by name %1 has already "
                                                              "been declared.")
                                               .arg(formatKeyword(parseInfo->staticContext->namePool()->toLexical($5))),
                                            parseInfo->isXSLT() ? ReportContext::XTSE0630 : ReportContext::XQST0049,
                                            fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            if($7) /* We got a value assigned. */
            {
                const Expression::Ptr checked
                        (TypeChecker::applyFunctionConversion($7, $6, parseInfo->staticContext,
                                                              $3 ? ReportContext::XTTE0570 : ReportContext::XPTY0004,
                                                              $3 ? TypeChecker::Options(TypeChecker::CheckFocus | TypeChecker::AutomaticallyConvert) : TypeChecker::CheckFocus));

                pushVariable($5, $6, checked, VariableDeclaration::GlobalVariable, @$, parseInfo);
                parseInfo->declaredVariables.append(parseInfo->variables.last());
            }
            else /* We got an 'external' declaration. */
            {
                const SequenceType::Ptr varType(parseInfo->staticContext->
                                                externalVariableLoader()->announceExternalVariable($5, $6));

                if(varType)
                {
                    /* We push the declaration such that we can see name clashes and so on, but we don't use it for tying
                     * any references to it. */
                    pushVariable($5, varType, Expression::Ptr(), VariableDeclaration::ExternalVariable, @$, parseInfo);
                }
                else if($8)
                {
                    /* Ok, the xsl:param got a default value, we make it
                     * available as a regular variable declaration. */
                    // TODO turn into checked
                    pushVariable($5, $6, $8, VariableDeclaration::GlobalVariable, @$, parseInfo);
                    // TODO ensure that duplicates are trapped.
                }
                else
                {
                    parseInfo->staticContext->error(QtXmlPatterns::tr("No value is available for the external "
                                                                      "variable by name %1.")
                                                       .arg(formatKeyword(parseInfo->staticContext->namePool(), $5)),
                                                    parseInfo->isXSLT() ? ReportContext::XTDE0050 : ReportContext::XPDY0002,
                                                    fromYYLTYPE(@$, parseInfo));
                }
            }
        }
    }

VariableValue: EXTERNAL                                                             /* [X] */
    {
        $$.reset();
    }
| ASSIGN ExprSingle
    {
        $$ = $2;
    }

OptionalDefaultValue: /* Empty. */                                                  /* [X] */
    {
        $$.reset();
    }
| ASSIGN ExprSingle
    {
        $$ = $2;
    }

ConstructionDecl: DECLARE CONSTRUCTION ConstructionMode Separator                   /* [25] */
    {
        if(parseInfo->hasDeclaration(ParserContext::ConstructionDecl))
        {
            parseInfo->staticContext->error(prologMessage("declare ordering"),
                                            ReportContext::XQST0067, fromYYLTYPE(@$, parseInfo));
        }
        else
        {
            parseInfo->registerDeclaration(ParserContext::ConstructionDecl);
            parseInfo->staticContext->setConstructionMode($3);
        }
    }

ConstructionMode: STRIP                                                             /* [X] */
    {
        $$ = StaticContext::CMStrip;
    }
| PRESERVE
    {
        $$ = StaticContext::CMPreserve;
    }

FunctionDecl: DECLARE FUNCTION IsInternal FunctionName LPAREN ParamList RPAREN
              {
                $<enums.slot>$ = parseInfo->currentExpressionSlot() - $6.count();
              }
              TypeDeclaration FunctionBody Separator                                /* [26] */
    {
        if(!$3)
            allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $3);

        /* If FunctionBody is null, it is 'external', otherwise the value is the body. */
        const QXmlName::NamespaceCode ns($4.namespaceURI());

        if(parseInfo->isXSLT() && !$4.hasPrefix())
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("A stylesheet function must have a prefixed name."),
                                            ReportContext::XTSE0740,
                                            fromYYLTYPE(@$, parseInfo));
        }

        if($10) /* We got a function body. */
        {
            if(ns == StandardNamespaces::empty)
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("The namespace for a user defined function "
                                                   "cannot be empty (try the predefined "
                                                   "prefix %1 which exists for cases "
                                                   "like this)")
                                                   .arg(formatKeyword("local")),
                                                ReportContext::XQST0060, fromYYLTYPE(@$, parseInfo));
            }
            else if(XPathHelper::isReservedNamespace(ns))
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr(
                                                   "The namespace %1 is reserved; therefore "
                                                   "user defined functions may not use it. "
                                                   "Try the predefined prefix %2, which "
                                                   "exists for these cases.")
                                                .arg(formatURI(parseInfo->staticContext->namePool(), ns), formatKeyword("local")),
                                                parseInfo->isXSLT() ? ReportContext::XTSE0080 : ReportContext::XQST0045,
                                                fromYYLTYPE(@$, parseInfo));
            }
            else if(parseInfo->moduleNamespace != StandardNamespaces::empty &&
                    ns != parseInfo->moduleNamespace)
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr(
                                                   "The namespace of a user defined "
                                                   "function in a library module must be "
                                                   "equivalent to the module namespace. "
                                                   "In other words, it should be %1 instead "
                                                   "of %2")
                                                .arg(formatURI(parseInfo->staticContext->namePool(), parseInfo->moduleNamespace),
                                                     formatURI(parseInfo->staticContext->namePool(), ns)),
                                                ReportContext::XQST0048, fromYYLTYPE(@$, parseInfo));
            }
            else
            {
                /* Apply function conversion such that the body matches the declared
                 * return type. */
                const Expression::Ptr checked(TypeChecker::applyFunctionConversion($10, $9,
                                                                                   parseInfo->staticContext,
                                                                                   ReportContext::XPTY0004,
                                                                                   TypeChecker::Options(TypeChecker::AutomaticallyConvert |
                                                                                                        TypeChecker::CheckFocus |
                                                                                                        TypeChecker::GeneratePromotion)));

                const int argCount = $6.count();
                const FunctionSignature::Ptr sign(new FunctionSignature($4 /* name */,
                                                                        argCount /* minArgs */,
                                                                        argCount /* maxArgs */,
                                                                        $9 /* returnType */));
                sign->setArguments($6);
                const UserFunction::List::const_iterator end(parseInfo->userFunctions.constEnd());
                UserFunction::List::const_iterator it(parseInfo->userFunctions.constBegin());

                for(; it != end; ++it)
                {
                    if(*(*it)->signature() == *sign)
                    {
                        parseInfo->staticContext->error(QtXmlPatterns::tr("A function already exists with "
                                                           "the signature %1.")
                                                           .arg(formatFunction(parseInfo->staticContext->namePool(), sign)),
                                                        parseInfo->isXSLT() ? ReportContext::XTSE0770 : ReportContext::XQST0034, fromYYLTYPE(@$, parseInfo));
                    }
                }

                VariableDeclaration::List argDecls;

                for(int i = 0; i < argCount; ++i)
                    argDecls.append(parseInfo->variables.at(i));

                if($<enums.slot>8 > -1)
                {
                    /* We have allocated slots, so now push them out of scope. */
                    parseInfo->finalizePushedVariable(argCount);
                }

                parseInfo->userFunctions.append(UserFunction::Ptr(new UserFunction(sign, checked, $<enums.slot>8, argDecls)));
            }
        }
        else /* We got an 'external' declaration. */
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("No external functions are supported. "
                                               "All supported functions can be used directly, "
                                               "without first declaring them as external"),
                                            ReportContext::XPST0017, fromYYLTYPE(@$, parseInfo));
        }
    }

ParamList: /* empty */                                                              /* [27] */
    {
        $$ = FunctionArgument::List();
    }
| Param
    {
        FunctionArgument::List l;
        l.append($1);
        $$ = l;
    }
| ParamList COMMA Param
    {
        FunctionArgument::List::const_iterator it($1.constBegin());
        const FunctionArgument::List::const_iterator end($1.constEnd());

        for(; it != end; ++it)
        {
            if((*it)->name() == $3->name())
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("An argument by name %1 has already "
                                                   "been declared. Every argument name "
                                                   "must be unique.")
                                                   .arg(formatKeyword(parseInfo->staticContext->namePool(), $3->name())),
                                                ReportContext::XQST0039, fromYYLTYPE(@$, parseInfo));
            }
        }

        $1.append($3);
        $$ = $1;
    }

Param: DOLLAR VarName TypeDeclaration                                               /* [28] */
    {
        pushVariable($2, $3, Expression::Ptr(), VariableDeclaration::FunctionArgument, @$, parseInfo);
        $$ = FunctionArgument::Ptr(new FunctionArgument($2, $3));
    }

FunctionBody: EXTERNAL                                                              /* [X] */
    {
        $$.reset();
    }
| EnclosedExpr

EnclosedExpr: CURLY_LBRACE Expr CURLY_RBRACE                                        /* [29] */
    {
        $$ = $2;
    }

QueryBody: Expr                                                                     /* [30] */

/**
 * A pattern as found in for instance xsl:template/@match.
 *
 * @note When using this pattern, remember to set ParserContext::isParsingPattern.
 *
 * @see <a href="http://www.w3.org/TR/xslt20/#dt-pattern">XSL Transformations
 * (XSLT) Version 2.0, 5.5.2 Syntax of Patterns</a>
 */
Pattern: PathPattern                                                                /* [XSLT20-1] */
| Pattern BAR PathPattern
    {
        $$ = create(new CombineNodes($1, CombineNodes::Union, $3), @$, parseInfo);
    }

PathPattern: RelativePathPattern                                                    /* [XSLT20-2] */
| SLASH
    {
        /* We write this into a node test. The spec says, 5.5.3 The Meaning of a Pattern:
         * "Similarly, / matches a document node, and only a document node,
         * because the result of the expression root(.)//(/) returns the root
         * node of the tree containing the context node if and only if it is a
         * document node." */
        $$ = create(new AxisStep(QXmlNodeModelIndex::AxisSelf, BuiltinTypes::document), @$, parseInfo);
    }
| SLASH RelativePathPattern
    {
        /* /axis::node-test
         *       =>
         * axis::node-test[parent::document-node()]
         *
         * In practice it looks like this. $2 is:
         *
         *     TruthPredicate
         *          AxisStep    self::element(c)
         *          TruthPredicate
         *              AxisStep    parent::element(b)
         *              AxisStep    parent::element(a)
         *
         * and we want this:
         *
         *      TruthPredicate
         *          AxisStep    self::element(c)
         *          TruthPredicate
         *              AxisStep    self::element(b)
         *              TruthPredicate
         *                  AxisStep    parent::element(a)
         *                  AxisStep    parent::document()
         *
         * So we want to rewrite the predicate deepest down into a
         * another TruthPredicate containing the AxisStep.
         *
         * The simplest case where $2 is only an axis step is special. When $2 is:
         *
         *  AxisStep self::element(a)
         *
         * we want:
         *
         *  TruthPredicate
         *      AxisStep self::element(a)
         *      AxisStep parent::document()
         */

        /* First, find the target. */
        Expression::Ptr target($2);

        while(isPredicate(target->id()))
        {
            const Expression::Ptr candidate(target->operands().at(1));

            if(isPredicate(candidate->id()))
                target = candidate;
            else
                break; /* target is now the last predicate. */
        }

        if(target->is(Expression::IDAxisStep))
        {
            $$ = create(GenericPredicate::create($2, create(new AxisStep(QXmlNodeModelIndex::AxisParent, BuiltinTypes::document), @$, parseInfo),
                                                 parseInfo->staticContext, fromYYLTYPE(@1, parseInfo)), @1, parseInfo);
        }
        else
        {
            const Expression::List targetOperands(target->operands());
            Expression::List newOps;
            newOps.append(targetOperands.at(0));

            newOps.append(create(GenericPredicate::create(targetOperands.at(1),
                                                          create(new AxisStep(QXmlNodeModelIndex::AxisParent, BuiltinTypes::document), @$, parseInfo),
                                                          parseInfo->staticContext, fromYYLTYPE(@1, parseInfo)), @1, parseInfo));

            target->setOperands(newOps);
            $$ = $2;
        }
    }
| SLASHSLASH RelativePathPattern
    {
        /* //axis::node-test
         *        =>
         * axis::node-test[parent::node()]
         *
         * Spec says: "//para matches any para element that has a parent node."
         */
        $$ = create(GenericPredicate::create($2, create(new AxisStep(QXmlNodeModelIndex::AxisParent, BuiltinTypes::node), @$, parseInfo),
                                             parseInfo->staticContext, fromYYLTYPE(@1, parseInfo)), @1, parseInfo);
    }
| IdKeyPattern
| IdKeyPattern SLASH RelativePathPattern
    {
        createIdPatternPath($1, $3, QXmlNodeModelIndex::AxisParent, @2, parseInfo);
    }
| IdKeyPattern SLASHSLASH RelativePathPattern
    {
        createIdPatternPath($1, $3, QXmlNodeModelIndex::AxisAncestor, @2, parseInfo);
    }

IdKeyPattern: FunctionCallExpr
    {
        const Expression::List ands($1->operands());
        const FunctionSignature::Ptr signature($1->as<FunctionCall>()->signature());
        const QXmlName name(signature->name());
        const QXmlName key(StandardNamespaces::fn, StandardLocalNames::key);
        const QXmlName id(StandardNamespaces::fn, StandardLocalNames::id);

        if(name == id)
        {
            const Expression::ID id = ands.first()->id();
            if(!isVariableReference(id) && id != Expression::IDStringValue)
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("When function %1 is used for matching inside a pattern, "
                                                                  "the argument must be a variable reference or a string literal.")
                                                                  .arg(formatFunction(parseInfo->staticContext->namePool(), signature)),
                                                ReportContext::XPST0003,
                                                fromYYLTYPE(@$, parseInfo));
            }
        }
        else if(name == key)
        {
            if(ands.first()->id() != Expression::IDStringValue)
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("In an XSL-T pattern, the first argument to function %1 "
                                                                  "must be a string literal, when used for matching.")
                                                                  .arg(formatFunction(parseInfo->staticContext->namePool(), signature)),
                                                ReportContext::XPST0003,
                                                fromYYLTYPE(@$, parseInfo));
            }

            const Expression::ID id2 = ands.at(1)->id();
            if(!isVariableReference(id2) &&
               id2 != Expression::IDStringValue &&
               id2 != Expression::IDIntegerValue &&
               id2 != Expression::IDBooleanValue &&
               id2 != Expression::IDFloat)
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("In an XSL-T pattern, the first argument to function %1 "
                                                                  "must be a literal or a variable reference, when used for matching.")
                                                                  .arg(formatFunction(parseInfo->staticContext->namePool(), signature)),
                                                ReportContext::XPST0003,
                                                fromYYLTYPE(@$, parseInfo));
            }

            if(ands.count() == 3)
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("In an XSL-T pattern, function %1 cannot have a third argument.")
                                                                  .arg(formatFunction(parseInfo->staticContext->namePool(), signature)),
                                                ReportContext::XPST0003,
                                                fromYYLTYPE(@$, parseInfo));
            }

        }
        else
        {
            const FunctionSignature::Hash signs(parseInfo->staticContext->functionSignatures()->functionSignatures());
            parseInfo->staticContext->error(QtXmlPatterns::tr("In an XSL-T pattern, only function %1 "
                                                              "and %2, not %3, can be used for matching.")
                                                              .arg(formatFunction(parseInfo->staticContext->namePool(), signs.value(id)),
                                                                   formatFunction(parseInfo->staticContext->namePool(), signs.value(key)),
                                                                   formatFunction(parseInfo->staticContext->namePool(), signature)),
                                            ReportContext::XPST0003,
                                            fromYYLTYPE(@$, parseInfo));
        }

        $$ = $1;
    }

RelativePathPattern: PatternStep                                                    /* [XSLT20-3] */
| RelativePathPattern SLASH PatternStep
    {
        $$ = createPatternPath($1, $3, QXmlNodeModelIndex::AxisParent, @2, parseInfo);
    }
| RelativePathPattern SLASHSLASH PatternStep
    {
        $$ = createPatternPath($1, $3, QXmlNodeModelIndex::AxisAncestor, @2, parseInfo);
    }

PatternStep: FilteredAxisStep
    {
        const Expression::Ptr expr(findAxisStep($1));

        const QXmlNodeModelIndex::Axis axis = expr->as<AxisStep>()->axis();
        AxisStep *const axisStep = expr->as<AxisStep>();

        /* Here we constrain the possible axes, and we rewrite the axes as according
         * to 5.5.3 The Meaning of a Pattern.
         *
         * However, we also rewrite axis child and attribute to axis self. The
         * reason for this is that if we don't, we will match the children of
         * the context node, instead of the context node itself. The formal
         * definition of a pattern, root(.)//EE is insensitive to context,
         * while the way we implement pattern, "the other way of seeing it",
         * e.g from right to left, are very much. */

        if(axisStep->nodeTest() == BuiltinTypes::document
           || axis == QXmlNodeModelIndex::AxisChild)
            axisStep->setAxis(QXmlNodeModelIndex::AxisSelf);
        else if(axis == QXmlNodeModelIndex::AxisAttribute)
        {
            axisStep->setAxis(QXmlNodeModelIndex::AxisSelf);
            /* Consider that the user write attribute::node().  This is
             * semantically equivalent to attribute::attribute(), but since we have changed
             * the axis to axis self, we also need to change the node test, such that we
             * have self::attribute(). */
            if(*axisStep->nodeTest() == *BuiltinTypes::node)
                axisStep->setNodeTest(BuiltinTypes::attribute);
        }
        else
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("In an XSL-T pattern, axis %1 cannot be used, "
                                                              "only axis %2 or %3 can.")
                                            .arg(formatKeyword(AxisStep::axisName(axis)),
                                                 formatKeyword(AxisStep::axisName(QXmlNodeModelIndex::AxisChild)),
                                                 formatKeyword(AxisStep::axisName(QXmlNodeModelIndex::AxisAttribute))),
                                            ReportContext::XPST0003,
                                            fromYYLTYPE(@$, parseInfo));
        }

        $$ = $1;
    }

Expr: ExprSingle                                                                    /* [31] */
| ExpressionSequence
    {
        $$ = create(new ExpressionSequence($1), @$, parseInfo);
    }

ExpressionSequence: ExprSingle COMMA ExprSingle                                     /* [X] */
    {
        Expression::List l;
        l.append($1);
        l.append($3);
        $$ = l;
    }
| ExpressionSequence COMMA ExprSingle
    {
        $1.append($3);
        $$ = $1;
    }

ExprSingle: OrExpr                                                                  /* [32] */
| FLWORExpr
| QuantifiedExpr
| TypeswitchExpr
| IfExpr
| AVT LPAREN AttrValueContent RPAREN
    {
        $$ = createDirAttributeValue($3, parseInfo, @$);
    }

OptionalModes: /* Empty. */                                                         /* [X] */
    {
        QVector<QXmlName> result;
        result.append(QXmlName(StandardNamespaces::InternalXSLT, StandardLocalNames::Default));
        $$ = result;
    }
| MODE Modes
    {
        $$ = $2;
    }

OptionalMode: /* Empty. */                                                          /* [X] */
    {
            $$ = QXmlName(StandardNamespaces::InternalXSLT, StandardLocalNames::Default);
    }
| MODE Mode
    {
        $$ = $2;
    }

Modes: Mode
    {
        QVector<QXmlName> result;
        result.append($1);
        $$ = result;
    }
| Modes COMMA Mode
    {
        $1.append($3);
        $$ = $1;
    }

Mode: QName                                                                         /* [X] */
    {
        $$ = $1;
    }
| NCNAME
    {
        if($1 == QLatin1String("#current"))
            $$ = QXmlName(StandardNamespaces::InternalXSLT, StandardLocalNames::current);
        else if($1 == QLatin1String("#default"))
            $$ = QXmlName(StandardNamespaces::InternalXSLT, StandardLocalNames::Default);
        else if($1 == QLatin1String("#all"))
            $$ = QXmlName(StandardNamespaces::InternalXSLT, StandardLocalNames::all);
        else
        {
            const ReflectYYLTYPE ryy(@$, parseInfo);

            if(!QXmlUtils::isNCName($1))
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is an invalid template mode name.")
                                                                  .arg(formatKeyword($1)),
                                                ReportContext::XTSE0550,
                                                fromYYLTYPE(@$, parseInfo));
            }

            $$ = parseInfo->staticContext->namePool()->allocateQName(StandardNamespaces::empty, $1);
        }
    }


FLWORExpr: ForClause                                                                /* [33] */
| LetClause

ForClause: FOR DOLLAR VarName TypeDeclaration
           PositionalVar IN ExprSingle
           {
               /* We're pushing the range variable here, not the positional. */
               $<expr>$ = pushVariable($3, quantificationType($4), $7, VariableDeclaration::RangeVariable, @$, parseInfo);
           }
           {
               /* It is ok this appears after PositionalVar, because currentRangeSlot()
                * uses a different "channel" than currentPositionSlot(), so they can't trash
                * each other. */
               $<enums.slot>$ = parseInfo->staticContext->currentRangeSlot();
           }
           ForTail                                                                  /* [34] */
    {
        Q_ASSERT($7);
        Q_ASSERT($10);

        /* We want the next last pushed variable, since we push the range variable after the
         * positional variable. */
        if($5 != -1 && parseInfo->variables.at(parseInfo->variables.count() -2)->name == $3)
        {
            /* Ok, a positional variable is used since its slot is not -1, and its name is equal
             * to our range variable. This is an error. */
            parseInfo->staticContext->error(QtXmlPatterns::tr("The name of a variable bound in a for-expression must be different "
                                               "from the positional variable. Hence, the two variables named %1 collide.")
                                               .arg(formatKeyword(parseInfo->staticContext->namePool(), $3)),
                                            ReportContext::XQST0089,
                                            fromYYLTYPE(@$, parseInfo));

        }

        const Expression::Ptr retBody(create(new ForClause($<enums.slot>9, $<expr>8, $10, $5), @$, parseInfo));
        ReturnOrderBy *const rob = locateReturnClause($10);

        if(rob)
            $$ = create(new OrderBy(rob->stability(), rob->orderSpecs(), retBody, rob), @$, parseInfo);
        else
            $$ = retBody;

        parseInfo->finalizePushedVariable();

        if($5 != -1) /* We also have a positional variable to remove from the scope. */
            parseInfo->finalizePushedVariable();
    }

ForTail: COMMA DOLLAR VarName TypeDeclaration
         PositionalVar IN ExprSingle
         {
             pushVariable($3, quantificationType($4), $7, VariableDeclaration::RangeVariable, @$, parseInfo);
         }
         {
             /* It is ok this appears after PositionalVar, because currentRangeSlot()
              * uses a different "channel" than currentPositionSlot(), so they can't trash
              * each other. */
             $<enums.slot>$ = parseInfo->staticContext->currentRangeSlot();
         }
         ForTail                                                                    /* [X] */
    {
        $$ = create(new ForClause($<enums.slot>9, $<expr>7, $10, $5), @$, parseInfo);

        parseInfo->finalizePushedVariable();

        if($5 != -1) /* We also have a positional variable to remove from the scope. */
            parseInfo->finalizePushedVariable();
    }

| WhereClause
| ForClause
| LetClause

PositionalVar: /* empty */                                                          /* [35] */
    {
        $$ = -1;
    }

| AT DOLLAR VarName
    {
        pushVariable($3, CommonSequenceTypes::ExactlyOneInteger, Expression::Ptr(),
                     VariableDeclaration::PositionalVariable, @$, parseInfo);
        $$ = parseInfo->currentPositionSlot();
    }

LetClause: LET IsInternal DOLLAR VarName TypeDeclaration ASSIGN ExprSingle
           {
                $<expr>$ = pushVariable($4, quantificationType($5), $7, VariableDeclaration::ExpressionVariable, @$, parseInfo);
           }
           LetTail                                                                  /* [36] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $2);

        Q_ASSERT(parseInfo->variables.top()->name == $4);
        $$ = create(new LetClause($<expr>8, $9, parseInfo->variables.top()), @$, parseInfo);
        parseInfo->finalizePushedVariable();
    }

LetTail: COMMA DOLLAR VarName TypeDeclaration ASSIGN ExprSingle
         { $<expr>$ = pushVariable($3, quantificationType($4), $6, VariableDeclaration::ExpressionVariable, @$, parseInfo);}
         LetTail                                                                    /* [X] */
    {
        Q_ASSERT(parseInfo->variables.top()->name == $3);
        $$ = create(new LetClause($<expr>7, $8, parseInfo->variables.top()), @$, parseInfo);
        parseInfo->finalizePushedVariable();
    }

| WhereClause
| ForClause
| LetClause

WhereClause: OrderByClause RETURN ExprSingle                                        /* [37] */
    {
        if($1.isEmpty())
            $$ = $3;
        else
            $$ = createReturnOrderBy($1, $3, parseInfo->orderStability.pop(), @$, parseInfo);
    }

| WHERE ExprSingle OrderByClause RETURN ExprSingle
    {
        if($3.isEmpty())
            $$ = create(new IfThenClause($2, $5, create(new EmptySequence, @$, parseInfo)), @$, parseInfo);
        else
            $$ = create(new IfThenClause($2, createReturnOrderBy($3, $5, parseInfo->orderStability.pop(), @$, parseInfo),
                                         create(new EmptySequence, @$, parseInfo)),
                        @$, parseInfo);
    }

OrderByClause: /* Empty. */                                                         /* [38] */
    {
        $$ = OrderSpecTransfer::List();
    }
| MandatoryOrderByClause

MandatoryOrderByClause: OrderByInputOrder OrderSpecList
    {
        $$ = $2;
    }

OrderSpecList: OrderSpecList COMMA OrderSpec                                        /* [39] */
    {
        OrderSpecTransfer::List list;
        list += $1;
        list.append($3);
        $$ = list;
    }
| OrderSpec
    {
        OrderSpecTransfer::List list;
        list.append($1);
        $$ = list;
    }

OrderSpec: ExprSingle DirectionModifier EmptynessModifier CollationModifier         /* [40] */
    {
        $$ = OrderSpecTransfer($1, OrderBy::OrderSpec($2, $3));
    }

DirectionModifier: /* Empty. */                                                     /* [X] */
    {
        /* Where does the specification state the default value is ascending?
         *
         * It is implicit, in the first enumerated list in 3.8.3 Order By and Return Clauses:
         *
         * "If T1 and T2 are two tuples in the tuple stream, and V1 and V2 are the first pair
         *  of values encountered when evaluating their orderspecs from left to right for
         *  which one value is greater-than the other (as defined above), then:
         *
         *      1. If V1 is greater-than V2: If the orderspec specifies descending,
         *         then T1 precedes T2 in the tuple stream; otherwise, T2 precedes T1 in the tuple stream.
         *      2. If V2 is greater-than V1: If the orderspec specifies descending,
         *         then T2 precedes T1 in the tuple stream; otherwise, T1 precedes T2 in the tuple stream."
         *
         * which means that if you don't specify anything, or you
         * specify ascending, you get the same result.
         */
        $$ = OrderBy::OrderSpec::Ascending;
    }

| ASCENDING
    {
        $$ = OrderBy::OrderSpec::Ascending;
    }

| DESCENDING
    {
        $$ = OrderBy::OrderSpec::Descending;
    }

EmptynessModifier: /* Empty. */                                                     /* [X] */
    {
        $$ = parseInfo->staticContext->orderingEmptySequence();
    }
| OrderingEmptySequence

CollationModifier: /* Empty. */                                                     /* [X] */
| COLLATION URILiteral
    {
        if(parseInfo->isXSLT())
            resolveAndCheckCollation<ReportContext::XTDE1035>($2, parseInfo, @$);
        else
            resolveAndCheckCollation<ReportContext::XQST0076>($2, parseInfo, @$);
    }
| INTERNAL COLLATION ExprSingle
    {
        /* We do nothing. We don't use collations, and we have this non-terminal
         * in order to accept expressions. */
    }

OrderByInputOrder: STABLE ORDER BY                                                  /* [X] */
    {
        parseInfo->orderStability.push(OrderBy::StableOrder);
    }
| ORDER BY
    {
        parseInfo->orderStability.push(OrderBy::UnstableOrder);
    }

QuantifiedExpr: SomeQuantificationExpr                                              /* [42] */
| EveryQuantificationExpr

SomeQuantificationExpr: SOME DOLLAR VarName TypeDeclaration IN ExprSingle
                        {
                            pushVariable($3, quantificationType($4), $6,
                                         VariableDeclaration::RangeVariable, @$, parseInfo);
                        }
                        {$<enums.slot>$ = parseInfo->staticContext->currentRangeSlot();}
                        SomeQuantificationTail                                      /* [X] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new QuantifiedExpression($<enums.slot>8,
                                             QuantifiedExpression::Some, $<expr>6, $9), @$, parseInfo);
        parseInfo->finalizePushedVariable();
    }

SomeQuantificationTail: COMMA DOLLAR VarName TypeDeclaration IN ExprSingle
                        {
                            $<expr>$ = pushVariable($3, quantificationType($4), $6,
                                                    VariableDeclaration::RangeVariable, @$, parseInfo);
                        }
                        {$<enums.slot>$ = parseInfo->staticContext->currentRangeSlot();}
                        SomeQuantificationTail                                      /* [X] */
    {
        $$ = create(new QuantifiedExpression($<enums.slot>8,
                                             QuantifiedExpression::Some, $<expr>7, $9), @$, parseInfo);
        parseInfo->finalizePushedVariable();
    }

| SatisfiesClause

EveryQuantificationExpr: EVERY DOLLAR VarName TypeDeclaration IN ExprSingle
                         {
                            pushVariable($3, quantificationType($4), $6,
                                         VariableDeclaration::RangeVariable, @$, parseInfo);
                         }
                         {$<enums.slot>$ = parseInfo->staticContext->currentRangeSlot();}
                         EveryQuantificationTail                                    /* [X] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new QuantifiedExpression($<enums.slot>8,
                                             QuantifiedExpression::Every, $<expr>6, $9), @$, parseInfo);
        parseInfo->finalizePushedVariable();
    }

EveryQuantificationTail: COMMA DOLLAR VarName TypeDeclaration IN ExprSingle
                         {
                            $<expr>$ = pushVariable($3, quantificationType($4), $6,
                                                    VariableDeclaration::RangeVariable, @$, parseInfo);
                         }
                         {$<enums.slot>$ = parseInfo->staticContext->currentRangeSlot();}
                         EveryQuantificationTail                                    /* [X] */
    {
        $$ = create(new QuantifiedExpression($<enums.slot>8,
                                             QuantifiedExpression::Every, $<expr>7, $9), @$, parseInfo);
        parseInfo->finalizePushedVariable();
    }

| SatisfiesClause

SatisfiesClause: SATISFIES ExprSingle                                               /* [X] */
    {
        $$ = $2;
    }

/*
 * Typeswitches are re-written to a combination between @c if clauses, <tt>instance of</tt>, and
 * @c let bindings. For example, the query:
 *
 * @code
 * typeswitch(input)
 * case element()             return <!-- a comment -->
 * case $i as attribute(name) return name($i)
 * default                    return "Didn't match"
 * @endcode
 *
 * becomes:
 *
 * @code
 * if(input instance of element())
 * then <!-- a comment -->
 * else if(input instance of attribute(name))
 *      then let $i as attribute(name) := input return name($i)
 *      else "Didn't match"
 * @endcode
 */

TypeswitchExpr: TYPESWITCH LPAREN Expr RPAREN
                {
                    parseInfo->typeswitchSource.push($3);
                }
                CaseClause                                                          /* [43] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
        parseInfo->typeswitchSource.pop();
        $$ = $6;
    }

CaseClause: CASE CaseVariable SequenceType                                          /* [44] */
    {
        if(!$2.isNull())
        {
            pushVariable($2, $3, parseInfo->typeswitchSource.top(),
                         VariableDeclaration::ExpressionVariable, @$, parseInfo, false);
        }
    }
    RETURN ExprSingle
    {
        /* The variable shouldn't be in-scope for other case branches. */
        if(!$2.isNull())
            parseInfo->finalizePushedVariable();
    }
    CaseTail
    {
        const Expression::Ptr instanceOf(create(new InstanceOf(parseInfo->typeswitchSource.top(), $3), @$, parseInfo));
        $$ = create(new IfThenClause(instanceOf, $6, $8), @$, parseInfo);
    }

CaseTail: CaseClause                                                                /* [X] */
| CaseDefault

CaseVariable: /* Empty. */                                                          /* [X] */
    {
        $$ = QXmlName();
    }

| DOLLAR ElementName AS
    {
        $$ = $2;
    }

CaseDefault: DEFAULT RETURN ExprSingle                                              /* [X] */
    {
        $$ = $3;
    }
| DEFAULT DOLLAR ElementName
    {
        if(!$3.isNull())
        {
            pushVariable($3, parseInfo->typeswitchSource.top()->staticType(),
                         parseInfo->typeswitchSource.top(),
                         VariableDeclaration::ExpressionVariable, @$, parseInfo, false);
        }
    }
  RETURN ExprSingle
    {
        if(!$3.isNull())
            parseInfo->finalizePushedVariable();
        $$ = $6;
    }

IfExpr: IF LPAREN Expr RPAREN THEN ExprSingle ELSE ExprSingle                       /* [45] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new IfThenClause($3, $6, $8), @$, parseInfo);
    }

OrExpr: AndExpr                                                                     /* [46] */
| OrExpr OR AndExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new OrExpression($1, $3), @$, parseInfo);
    }

AndExpr: ComparisonExpr                                                             /* [47] */
| AndExpr AND ComparisonExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new AndExpression($1, $3), @$, parseInfo);
    }

ComparisonExpr: RangeExpr                                                           /* [48] */
| ValueComp
| GeneralComp
| NodeComp

RangeExpr: AdditiveExpr                                                             /* [49] */
| AdditiveExpr TO AdditiveExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new RangeExpression($1, $3), @$, parseInfo);
    }

AdditiveExpr: MultiplicativeExpr                                                    /* [50] */
| AdditiveExpr AdditiveOperator MultiplicativeExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new ArithmeticExpression($1, $2, $3), @$, parseInfo);
    }

AdditiveOperator: PLUS  {$$ = AtomicMathematician::Add;}                            /* [X] */
| MINUS                 {$$ = AtomicMathematician::Substract;}

MultiplicativeExpr: UnionExpr                                                       /* [51] */
| MultiplicativeExpr MultiplyOperator UnionExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new ArithmeticExpression($1, $2, $3), @$, parseInfo);
    }

MultiplyOperator: STAR  {$$ = AtomicMathematician::Multiply;}                       /* [X] */
| DIV                   {$$ = AtomicMathematician::Div;}
| IDIV                  {$$ = AtomicMathematician::IDiv;}
| MOD                   {$$ = AtomicMathematician::Mod;}

UnionExpr: IntersectExceptExpr                                                      /* [52] */
| UnionExpr UnionOperator IntersectExceptExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10
                                 | QXmlQuery::XPath20
                                 | QXmlQuery::XmlSchema11IdentityConstraintField
                                 | QXmlQuery::XmlSchema11IdentityConstraintSelector),
                  parseInfo, @$);
        $$ = create(new CombineNodes($1, CombineNodes::Union, $3), @$, parseInfo);
    }

IntersectExceptExpr: InstanceOfExpr                                                 /* [53] */
| IntersectExceptExpr IntersectOperator InstanceOfExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new CombineNodes($1, $2, $3), @$, parseInfo);
    }

UnionOperator: UNION                                                                /* [X] */
| BAR

IntersectOperator: INTERSECT                                                        /* [X] */
    {
        $$ = CombineNodes::Intersect;
    }
| EXCEPT
    {
        $$ = CombineNodes::Except;
    }

InstanceOfExpr: TreatExpr                                                           /* [54] */
| TreatExpr INSTANCE OF SequenceType
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new InstanceOf($1,
                    SequenceType::Ptr($4)), @$, parseInfo);
    }

TreatExpr: CastableExpr                                                             /* [55] */
| CastableExpr TREAT AS SequenceType
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new TreatAs($1, $4), @$, parseInfo);
    }

CastableExpr: CastExpr                                                              /* [56] */
| CastExpr CASTABLE AS SingleType
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new CastableAs($1, $4), @$, parseInfo);
    }

CastExpr: UnaryExpr                                                                 /* [57] */
| UnaryExpr CAST AS SingleType
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new CastAs($1, $4), @$, parseInfo);
    }

UnaryExpr: ValueExpr                                                                /* [58] */
| UnaryOperator UnaryExpr
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new UnaryExpression($1, $2, parseInfo->staticContext), @$, parseInfo);
    }

UnaryOperator: PLUS                                                                 /* [X] */
    {
        $$ = AtomicMathematician::Add;
    }
| MINUS
    {
        $$ = AtomicMathematician::Substract;
    }

ValueExpr: ValidateExpr                                                             /* [59] */
| PathExpr
| ExtensionExpr

GeneralComp: RangeExpr GeneralComparisonOperator RangeExpr                          /* [60] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new GeneralComparison($1, $2, $3, parseInfo->isBackwardsCompat.top()), @$, parseInfo);
    }

GeneralComparisonOperator: G_EQ {$$ = AtomicComparator::OperatorEqual;}             /* [X] */
| G_NE                          {$$ = AtomicComparator::OperatorNotEqual;}
| G_GE                          {$$ = AtomicComparator::OperatorGreaterOrEqual;}
| G_GT                          {$$ = AtomicComparator::OperatorGreaterThan;}
| G_LE                          {$$ = AtomicComparator::OperatorLessOrEqual;}
| G_LT                          {$$ = AtomicComparator::OperatorLessThan;}

ValueComp: RangeExpr ValueComparisonOperator RangeExpr                              /* [61] */
    {
        $$ = create(new ValueComparison($1, $2, $3), @$, parseInfo);
    }

ValueComparisonOperator: EQ {$$ = AtomicComparator::OperatorEqual;}
| NE                        {$$ = AtomicComparator::OperatorNotEqual;}
| GE                        {$$ = AtomicComparator::OperatorGreaterOrEqual;}
| GT                        {$$ = AtomicComparator::OperatorGreaterThan;}
| LE                        {$$ = AtomicComparator::OperatorLessOrEqual;}
| LT                        {$$ = AtomicComparator::OperatorLessThan;}

NodeComp: RangeExpr NodeOperator RangeExpr                                          /* [62] */
    {
        $$ = create(new NodeComparison($1, $2, $3), @$, parseInfo);
    }

NodeOperator: IS    {$$ = QXmlNodeModelIndex::Is;}                                  /* [X] */
| PRECEDES          {$$ = QXmlNodeModelIndex::Precedes;}
| FOLLOWS           {$$ = QXmlNodeModelIndex::Follows;}

ValidateExpr: ValidationMode EnclosedExpr                                           /* [63] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
        parseInfo->staticContext->error(QtXmlPatterns::tr("The Schema Validation Feature is not supported. "
                                                          "Hence, %1-expressions may not be used.")
                                           .arg(formatKeyword("validate")),
                                        ReportContext::XQST0075, fromYYLTYPE(@$, parseInfo));
        /*
        $$ = Validate::create($2, $1, parseInfo->staticContext);
        */
    }

/* "A validate expression may optionally specify a validation mode. The
    default validation mode is strict." */
ValidationMode: VALIDATE    {$$ = Validate::Strict;}                                /* [64] */
| VALIDATE STRICT           {$$ = Validate::Strict;}
| VALIDATE LAX              {$$ = Validate::Lax;}

ExtensionExpr: Pragmas EnclosedOptionalExpr                                         /* [65] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
        /* We don't support any pragmas, so we only do the
         * necessary validation and use the fallback expression. */

        if($2)
            $$ = $2;
        else
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("None of the pragma expressions are supported. "
                                               "Therefore, a fallback expression "
                                               "must be present"),
                                            ReportContext::XQST0079, fromYYLTYPE(@$, parseInfo));
        }
    }

EnclosedOptionalExpr: CURLY_LBRACE /* empty */ CURLY_RBRACE                         /* [X] */
    {
        $$.reset();
    }
| CURLY_LBRACE Expr CURLY_RBRACE
    {
        $$ = $2;
    }

Pragmas: Pragmas Pragma                                                             /* [X] */
| Pragma

Pragma: PRAGMA_START PragmaName PragmaContents PRAGMA_END                           /* [66] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
    }

PragmaContents: /* empty */                                                         /* [67] */
| StringLiteral

PathExpr: SLASH RelativePathExpr                                                    /* [68] */
    {
        /* This is "/step". That is, fn:root(self::node()) treat as document-node()/RelativePathExpr. */
        $$ = create(new Path(createRootExpression(parseInfo, @$), $2), @$, parseInfo);
    }

| SLASHSLASH RelativePathExpr
    {
        $$ = createSlashSlashPath(createRootExpression(parseInfo, @$), $2, @$, parseInfo);
    }
| SLASH
    {
        /* This is "/". That is, fn:root(self::node()) treat as document-node(). */
        $$ = createRootExpression(parseInfo, @$);
    }

| RelativePathExpr
    /* This is "step", simply. We let bison generate "$$ = $1". */

RelativePathExpr: StepExpr                                                          /* [69] */
| RelativePathExpr MapOrSlash StepExpr
    {
        $$ = create(new Path($1, $3, $2), @$, parseInfo);
    }
| RelativePathExpr MapOrSlash SORT MandatoryOrderByClause RETURN StepExpr END_SORT
    {
        const Expression::Ptr orderBy(createReturnOrderBy($4, $6, parseInfo->orderStability.pop(), @$, parseInfo));

        ReturnOrderBy *const rob = orderBy->as<ReturnOrderBy>();
        const Expression::Ptr path(create(new Path($1, orderBy, $2), @$, parseInfo));

        $$ = create(new OrderBy(rob->stability(), rob->orderSpecs(), path, rob), @$, parseInfo);
    }
| RelativePathExpr SLASHSLASH StepExpr
    {
        $$ = createSlashSlashPath($1, $3, @$, parseInfo);
    }

StepExpr: FilteredAxisStep                                                          /* [70] */
    {
        $$ = NodeSortExpression::wrapAround($1, parseInfo->staticContext);
    }
| FilterExpr
| CURRENT EnclosedExpr
    {
        $$ = create(new CurrentItemStore($2), @$, parseInfo);
    }
| XSLT_VERSION
    {
        const xsDouble version = $1.toDouble();

        parseInfo->isBackwardsCompat.push(version != 2);

        $<enums.Double>$ = version;
    }
    EnclosedExpr
    {
        if($<enums.Double>2 < 2)
            $$ = createCompatStore($3, @$, parseInfo);
        else
            $$ = $3;
    }
| BASEURI StringLiteral CURLY_LBRACE Expr CURLY_RBRACE                              /* [X] */
{
    allowedIn(QXmlQuery::XSLT20, parseInfo, @$);
    Q_ASSERT(!$2.isEmpty());
    $$ = create(new StaticBaseURIStore($2, $4), @$, parseInfo);
}

| DECLARE NAMESPACE NCNAME G_EQ STRING_LITERAL CURLY_LBRACE                         /* [X] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XSLT20), parseInfo, @$);
        parseInfo->resolvers.push(parseInfo->staticContext->namespaceBindings());
        const NamespaceResolver::Ptr resolver(new DelegatingNamespaceResolver(parseInfo->staticContext->namespaceBindings()));
        resolver->addBinding(QXmlName(parseInfo->staticContext->namePool()->allocateNamespace($5),
                                      StandardLocalNames::empty,
                                      parseInfo->staticContext->namePool()->allocatePrefix($3)));
        parseInfo->staticContext->setNamespaceBindings(resolver);
    }
    Expr
    CURLY_RBRACE
    {
        parseInfo->staticContext->setNamespaceBindings(parseInfo->resolvers.pop());
        $$ = $8;
    }
| CALL_TEMPLATE ElementName LPAREN TemplateWithParameters RPAREN
    {
        $$ = create(new CallTemplate($2, parseInfo->templateWithParams), @$, parseInfo);
        parseInfo->templateWithParametersHandled();
        parseInfo->templateCalls.append($$);
    }

TemplateWithParameters:
    {
        parseInfo->startParsingWithParam();
    }
    TemplateParameters
    {
        parseInfo->endParsingWithParam();
    }

TemplateParameters: /* Empty. */                                                    /* [X] */
    {
    }
| TemplateParameter
    {
    }
| TemplateParameters COMMA TemplateParameter
    {
    }

OptionalTemplateParameters: /* Empty. */                                            /* [X] */
    {
    }
| LPAREN TemplateParameters RPAREN
    {
    }

TemplateParameter: IsTunnel DOLLAR VarName TypeDeclaration OptionalAssign
    {
        /* Note, this grammar rule is invoked for @c xsl:param @em and @c
         * xsl:with-param. */
        const bool isParsingWithParam = parseInfo->isParsingWithParam();

        /**
         * @c xsl:param doesn't make life easy:
         *
         * If it only has @c name, it's default value is an empty
         * string(hence has type @c xs:string), but the value that
         * (maybe) is supplied can be anything, typically a node.
         *
         * Therefore, for that very common case we can't rely on
         * the Expression's type, but have to force it to item()*.
         *
         * So if we're supplied the type item()*, we pass a null
         * SequenceType. TemplateParameterReference recognizes this
         * and has item()* as its static type, regardless of if the
         * expression has a more specific type.
         */
        SequenceType::Ptr type;

        if(!$4->is(CommonSequenceTypes::ZeroOrMoreItems))
            type = $4;

        Expression::Ptr expr;

        /* The default value is an empty sequence. */
        if(!$5 && ((type && $4->cardinality().allowsEmpty())
                   || isParsingWithParam))
            expr = create(new EmptySequence, @$, parseInfo);
        else
            expr = $5;

        /* We ensure we have some type, so CallTemplate, Template and friends
         * are happy. */
        if(!isParsingWithParam && !type)
            type = CommonSequenceTypes::ZeroOrMoreItems;

        if($1)
            /* TODO, handle tunnel parameters. */;
        else
        {
            if((!isParsingWithParam && VariableDeclaration::contains(parseInfo->templateParameters, $3)) ||
               (isParsingWithParam && parseInfo->templateWithParams.contains($3)))
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("Each name of a template parameter must be unique; %1 is duplicated.")
                                                                 .arg(formatKeyword(parseInfo->staticContext->namePool(), $3)),
                                                isParsingWithParam ? ReportContext::XTSE0670 : ReportContext::XTSE0580, fromYYLTYPE(@$, parseInfo));
            }
            else
            {
                if(isParsingWithParam)
                    parseInfo->templateWithParams[$3] = WithParam::Ptr(new WithParam($3, $4, expr));
                else
                {
                    Q_ASSERT(type);
                    pushVariable($3, type, expr, VariableDeclaration::TemplateParameter, @$, parseInfo);
                    parseInfo->templateParameters.append(parseInfo->variables.top());
                }
            }
        }
    }

IsTunnel: /* Empty. */
    {
        $$ = false;
    }
| TUNNEL
    {
        $$ = true;
    }

OptionalAssign: /* Empty. */                                                        /* [X] */
    {
        $$ = Expression::Ptr();
    }
| ASSIGN ExprSingle
    {
        $$ = $2;
    }

/**
 * Controls whethers a path expression should sort its result. Used for
 * implementing XSL-T's for-each.
 */
MapOrSlash: SLASH                                                                   /* [X] */
    {
        $$ = Path::RegularPath;
    }
| MAP
    {
        $$ = Path::XSLTForEach;
    }
| FOR_APPLY_TEMPLATE
    {
        $$ = Path::ForApplyTemplate;
    }

FilteredAxisStep: AxisStep                                                          /* [X] */
| FilteredAxisStep LBRACKET Expr RBRACKET
    {
        $$ = create(GenericPredicate::create($1, $3, parseInfo->staticContext, fromYYLTYPE(@$, parseInfo)), @$, parseInfo);
    }

AxisStep: ForwardStep                                                               /* [71] */
| ReverseStep

ForwardStep: Axis
             {
                if($1 == QXmlNodeModelIndex::AxisAttribute)
                    parseInfo->nodeTestSource = BuiltinTypes::attribute;
             }
             NodeTestInAxisStep                                                     /* [72] */
    {
        if($3)
        {
            /* A node test was explicitly specified. The un-abbreviated syntax was used. */
            $$ = create(new AxisStep($1, $3), @$, parseInfo);
        }
        else
        {
            /* Quote from 3.2.1.1 Axes
             *
             * [Definition: Every axis has a principal node kind. If an axis
             *  can contain elements, then the principal node kind is element;
             *  otherwise, it is the kind of nodes that the axis can contain.] Thus:
             * - For the attribute axis, the principal node kind is attribute.
             * - For all other axes, the principal node kind is element. */

            if($1 == QXmlNodeModelIndex::AxisAttribute)
                $$ = create(new AxisStep(QXmlNodeModelIndex::AxisAttribute, BuiltinTypes::attribute), @$, parseInfo);
            else
                $$ = create(new AxisStep($1, BuiltinTypes::element), @$, parseInfo);
        }

        parseInfo->restoreNodeTestSource();
    }
| AbbrevForwardStep

NodeTestInAxisStep: NodeTest
| AnyAttributeTest

Axis: AxisToken COLONCOLON                                                          /* [73] */
    {
        if($1 == QXmlNodeModelIndex::AxisNamespace)
        {
            /* We don't raise XPST0010 here because the namespace axis isn't an optional
             * axis. It simply is not part of the XQuery grammar. */
            parseInfo->staticContext->error(QtXmlPatterns::tr("The %1-axis is unsupported in XQuery")
                                               .arg(formatKeyword("namespace")),
                                            ReportContext::XPST0003, fromYYLTYPE(@$, parseInfo));
        }
        else
            $$ = $1;

        switch($1)
        {
            case QXmlNodeModelIndex::AxisAttribute:
            {
                allowedIn(QueryLanguages(  QXmlQuery::XPath20
                                         | QXmlQuery::XQuery10
                                         | QXmlQuery::XmlSchema11IdentityConstraintField
                                         | QXmlQuery::XSLT20),
                          parseInfo, @$);
                break;
            }
            case QXmlNodeModelIndex::AxisChild:
            {
                allowedIn(QueryLanguages(  QXmlQuery::XPath20
                                         | QXmlQuery::XQuery10
                                         | QXmlQuery::XmlSchema11IdentityConstraintField
                                         | QXmlQuery::XmlSchema11IdentityConstraintSelector
                                         | QXmlQuery::XSLT20),
                          parseInfo, @$);
                break;
            }
            default:
            {
                allowedIn(QueryLanguages(  QXmlQuery::XPath20
                                         | QXmlQuery::XQuery10
                                         | QXmlQuery::XSLT20),
                          parseInfo, @$);
            }
        }
    }

AxisToken: ANCESTOR_OR_SELF {$$ = QXmlNodeModelIndex::AxisAncestorOrSelf  ;}
| ANCESTOR                  {$$ = QXmlNodeModelIndex::AxisAncestor        ;}
| ATTRIBUTE                 {$$ = QXmlNodeModelIndex::AxisAttribute       ;}
| CHILD                     {$$ = QXmlNodeModelIndex::AxisChild           ;}
| DESCENDANT_OR_SELF        {$$ = QXmlNodeModelIndex::AxisDescendantOrSelf;}
| DESCENDANT                {$$ = QXmlNodeModelIndex::AxisDescendant      ;}
| FOLLOWING                 {$$ = QXmlNodeModelIndex::AxisFollowing       ;}
| PRECEDING                 {$$ = QXmlNodeModelIndex::AxisPreceding       ;}
| FOLLOWING_SIBLING         {$$ = QXmlNodeModelIndex::AxisFollowingSibling;}
| PRECEDING_SIBLING         {$$ = QXmlNodeModelIndex::AxisPrecedingSibling;}
| PARENT                    {$$ = QXmlNodeModelIndex::AxisParent          ;}
| SELF                      {$$ = QXmlNodeModelIndex::AxisSelf            ;}

AbbrevForwardStep: AT_SIGN
                   {
                        parseInfo->nodeTestSource = BuiltinTypes::attribute;
                   }
                   NodeTest                                                         /* [72] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XSLT20 | QXmlQuery::XmlSchema11IdentityConstraintField), parseInfo, @$);
        $$ = create(new AxisStep(QXmlNodeModelIndex::AxisAttribute, $3), @$, parseInfo);

        parseInfo->restoreNodeTestSource();
    }
| NodeTest
    {
        ItemType::Ptr nodeTest;

        if(parseInfo->isParsingPattern && *$1 == *BuiltinTypes::node)
            nodeTest = BuiltinTypes::xsltNodeTest;
        else
            nodeTest = $1;

        $$ = create(new AxisStep(QXmlNodeModelIndex::AxisChild, nodeTest), @$, parseInfo);
    }
| AnyAttributeTest
    {
        $$ = create(new AxisStep(QXmlNodeModelIndex::AxisAttribute, $1), @$, parseInfo);
    }

ReverseStep: AbbrevReverseStep                                                      /* [75] */

AbbrevReverseStep: DOTDOT                                                           /* [77] */
    {
        $$ = create(new AxisStep(QXmlNodeModelIndex::AxisParent, BuiltinTypes::node), @$, parseInfo);
    }

NodeTest: NameTest                                                                  /* [78] */
| KindTest
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
    }

NameTest: ElementName                                                               /* [79] */
    {
        $$ = QNameTest::create(parseInfo->nodeTestSource, $1);
    }
| WildCard

WildCard: STAR                                                                      /* [80] */
    {
        $$ = parseInfo->nodeTestSource;
    }
| ANY_LOCAL_NAME
    {
        const NamePool::Ptr np(parseInfo->staticContext->namePool());
        const ReflectYYLTYPE ryy(@$, parseInfo);

        const QXmlName::NamespaceCode ns(QNameConstructor::namespaceForPrefix(np->allocatePrefix($1), parseInfo->staticContext, &ryy));

        $$ = NamespaceNameTest::create(parseInfo->nodeTestSource, ns);
    }
| ANY_PREFIX
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        const QXmlName::LocalNameCode c = parseInfo->staticContext->namePool()->allocateLocalName($1);
        $$ = LocalNameTest::create(parseInfo->nodeTestSource, c);
    }

FilterExpr: PrimaryExpr                                                             /* [81] */
| FilterExpr LBRACKET Expr RBRACKET
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(GenericPredicate::create($1, $3, parseInfo->staticContext, fromYYLTYPE(@4, parseInfo)), @$, parseInfo);
    }

PrimaryExpr: Literal                                                                /* [84] */
| VarRef
| ParenthesizedExpr
| ContextItemExpr
| FunctionCallExpr
| OrderingExpr
| Constructor
| APPLY_TEMPLATE OptionalMode LPAREN TemplateWithParameters RPAREN
    {
        $$ = create(new ApplyTemplate(parseInfo->modeFor($2),
                                      parseInfo->templateWithParams,
                                      parseInfo->modeFor(QXmlName(StandardNamespaces::InternalXSLT,
                                                                  StandardLocalNames::Default))),
                    @1, parseInfo);
        parseInfo->templateWithParametersHandled();
    }

Literal: NumericLiteral                                                             /* [85] */
| StringLiteral
    {
        $$ = create(new Literal(AtomicString::fromValue($1)), @$, parseInfo);
    }

NumericLiteral: XPATH2_NUMBER                                                       /* [86] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = createNumericLiteral<Double>($1, @$, parseInfo);
    }
| NUMBER
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = createNumericLiteral<Numeric>($1, @$, parseInfo);
    }

VarRef: DOLLAR VarName                                                              /* [87] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = resolveVariable($2, @$, parseInfo, false);
    }

VarName: NCNAME                                                                     /* [88] */
    {
        /* See: http://www.w3.org/TR/xpath20/#id-variables */
        $$ = parseInfo->staticContext->namePool()->allocateQName(QString(), $1);
    }
| QName
    {
        $$ = $1;
    }

ParenthesizedExpr: LPAREN Expr RPAREN                                               /* [89] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = $2;
    }
| LPAREN RPAREN
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        $$ = create(new EmptySequence, @$, parseInfo);
    }

ContextItemExpr: DOT                                                                /* [90] */
    {
        $$ = create(new ContextItem(), @$, parseInfo);
    }

OrderingExpr: OrderingMode EnclosedExpr                                             /* [X] */
    {
        $$ = $2;
    }

FunctionCallExpr: FunctionName LPAREN FunctionArguments RPAREN                      /* [93] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
        if(XPathHelper::isReservedNamespace($1.namespaceURI()) || $1.namespaceURI() == StandardNamespaces::InternalXSLT)
        { /* We got a call to a builtin function. */
            const ReflectYYLTYPE ryy(@$, parseInfo);

            const Expression::Ptr
                func(parseInfo->staticContext->
                functionSignatures()->createFunctionCall($1, $3, parseInfo->staticContext, &ryy));

            if(func)
                $$ = create(func, @$, parseInfo);
            else
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("No function by name %1 is available.")
                                                   .arg(formatKeyword(parseInfo->staticContext->namePool(), $1)),
                                                ReportContext::XPST0017, fromYYLTYPE(@$, parseInfo));
            }
        }
        else /* It's a call to a function created with 'declare function'.*/
        {
            $$ = create(new UserFunctionCallsite($1, $3.count()), @$, parseInfo);

            $$->setOperands($3);
            parseInfo->userFunctionCallsites.append($$);
        }
    }

FunctionArguments: /* empty */                                                      /* [X] */
    {
        $$ = Expression::List();
    }

| ExprSingle
    {
        Expression::List list;
        list.append($1);
        $$ = list;
    }

| ExpressionSequence

Constructor: DirectConstructor                                                      /* [94] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$);
    }
| ComputedConstructor
/* The reason we cannot call alloweIn() as the action for ComputedConstructor,
 * is that we use the computed constructors for XSL-T, and therefore generate
 * INTERNAL tokens. */

DirectConstructor: DirElemConstructor                                               /* [95] */
| DirCommentConstructor
| DirPIConstructor

/*
 * Direct attribute constructors can contain embedded expressions, and for those namespace bindings
 * on the same element needs to be in scope. For example:
 *
 * @code
 * <element attribute="{prefix:nameTest}" xmlns:prefix="http://example.com/"/>
 * @endcode
 *
 * Patternist is designed to do all name resolution at parse time so the subsequent code only has to
 * deal with expanded QNames(which the QName class represents), and this presents a problem since
 * the parser haven't even encountered the @c xmlns:prefix when resolving @c prefix in the name test.
 *
 * This is solved as follows:
 *
 * <ol>
 *  <li>Just before starting parsing the attributes, we call Tokenizer::commenceScanOnly().
 *      This switches the tokenizer to not tokenize embedded expressions in attributes,
 *      but to return them as strings, token type STRING_LITERAL.</li>
 *  <li>We parse all the attributes, and iterates over them, only caring about
 *      namespace bindings, and validates and adds them to the context.</li>
 *  <li>We call Tokenizer::resumeTokenizationFrom() from the previous position
 *      returned from Tokenizer::commenceScanOnly() and parses the attributes once more,
 *      but this time with tokenization of embedded expressions. Since we this time
 *      have the namespace bindings in place, everything resolves.</li>
 * </ol>
 *
 * Saxon does this in a similar way. Study net.sf.saxon.expr.QueryParser::parseDirectElementConstructor().
 *
 * @see XQueryTokenizer::attributeAsRaw()
 */
DirElemConstructor: G_LT
                    LexicalName
                    {
                        $<enums.tokenizerPosition>$ = parseInfo->tokenizer->commenceScanOnly();
                        parseInfo->scanOnlyStack.push(true);
                    }

                    /* This list contains name/string pairs. No embedded
                     * expressions has been parsed. */
                    DirAttributeList

                    {
                        ++parseInfo->elementConstructorDepth;
                        Expression::List constructors;

                        parseInfo->resolvers.push(parseInfo->staticContext->namespaceBindings());

                        /* Fix up attributes and namespace declarations. */
                        const NamespaceResolver::Ptr resolver(new DelegatingNamespaceResolver(parseInfo->staticContext->namespaceBindings()));
                        const NamePool::Ptr namePool(parseInfo->staticContext->namePool());
                        const int len = $4.size();
                        QSet<QXmlName::PrefixCode> usedDeclarations;

                        /* Whether xmlns="" has been encountered. */
                        bool hasDefaultDeclaration = false;

                        /* For each attribute & namespace declaration, do: */
                        for(int i = 0; i < len; ++i)
                        {
                            QString strLocalName;
                            QString strPrefix;

                            XPathHelper::splitQName($4.at(i).first, strPrefix, strLocalName);
                            const QXmlName::PrefixCode prefix = namePool->allocatePrefix(strPrefix);

                            /* This can seem a bit weird. However, this name is ending up in a QXmlName
                             * which consider its prefix a... prefix. So, a namespace binding name can in some cases
                             * be a local name, but that's just as the initial syntactical construct. */
                            const QXmlName::LocalNameCode localName = namePool->allocatePrefix(strLocalName);

                            /* Not that localName is "foo" in "xmlns:foo" and that prefix is "xmlns". */

                            if(prefix == StandardPrefixes::xmlns ||
                               (prefix == StandardPrefixes::empty && localName == StandardPrefixes::xmlns))
                            {
                                if(localName == StandardPrefixes::xmlns)
                                    hasDefaultDeclaration = true;

                                /* We have a namespace declaration. */

                                const Expression::Ptr nsExpr($4.at(i).second);

                                const QString strNamespace(nsExpr->is(Expression::IDEmptySequence) ? QString() : nsExpr->as<Literal>()->item().stringValue());

                                const QXmlName::NamespaceCode ns = namePool->allocateNamespace(strNamespace);

                                if(ns == StandardNamespaces::empty)
                                {
                                    if(localName != StandardPrefixes::xmlns)
                                    {
                                        parseInfo->staticContext->error(QtXmlPatterns::tr("The namespace URI cannot be the empty string when binding to a prefix, %1.")
                                                                           .arg(formatURI(strPrefix)),
                                                                        ReportContext::XQST0085, fromYYLTYPE(@$, parseInfo));
                                    }
                                }
                                else if(!AnyURI::isValid(strNamespace))
                                {
                                    parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is an invalid namespace URI.").arg(formatURI(strNamespace)),
                                                                    ReportContext::XQST0022, fromYYLTYPE(@$, parseInfo));
                                }

                                if(prefix == StandardPrefixes::xmlns && localName == StandardPrefixes::xmlns)
                                {
                                    parseInfo->staticContext->error(QtXmlPatterns::tr("It is not possible to bind to the prefix %1")
                                                                       .arg(formatKeyword("xmlns")),
                                                                    ReportContext::XQST0070, fromYYLTYPE(@$, parseInfo));
                                }

                                if(ns == StandardNamespaces::xml && localName != StandardPrefixes::xml)
                                {
                                    parseInfo->staticContext->error(QtXmlPatterns::tr("Namespace %1 can only be bound to %2 (and it is, in either case, pre-declared).")
                                                                       .arg(formatURI(namePool->stringForNamespace(StandardNamespaces::xml)))
                                                                       .arg(formatKeyword("xml")),
                                                                    ReportContext::XQST0070, fromYYLTYPE(@$, parseInfo));
                                }

                                if(localName == StandardPrefixes::xml && ns != StandardNamespaces::xml)
                                {
                                    parseInfo->staticContext->error(QtXmlPatterns::tr("Prefix %1 can only be bound to %2 (and it is, in either case, pre-declared).")
                                                                       .arg(formatKeyword("xml"))
                                                                       .arg(formatURI(namePool->stringForNamespace(StandardNamespaces::xml))),
                                                                    ReportContext::XQST0070, fromYYLTYPE(@$, parseInfo));
                                }

                                QXmlName nb;

                                if(localName == StandardPrefixes::xmlns)
                                    nb = QXmlName(ns, StandardLocalNames::empty);
                                else
                                    nb = QXmlName(ns, StandardLocalNames::empty, localName);

                                if(usedDeclarations.contains(nb.prefix()))
                                {
                                    parseInfo->staticContext->error(QtXmlPatterns::tr("Two namespace declaration attributes have the same name: %1.")
                                                                       .arg(formatKeyword(namePool->stringForPrefix(nb.prefix()))),
                                                                    ReportContext::XQST0071, fromYYLTYPE(@$, parseInfo));

                                }
                                else
                                    usedDeclarations.insert(nb.prefix());

                                /* If the user has bound the XML namespace correctly, we in either
                                 * case don't want to output it.
                                 *
                                 * We only have to check the namespace parts since the above checks has ensured
                                 * consistency in the prefix parts. */
                                if(ns != StandardNamespaces::xml)
                                {
                                    /* We don't want default namespace declarations when the
                                     * default namespace already is empty. */
                                    if(!(ns == StandardNamespaces::empty          &&
                                         localName == StandardNamespaces::xmlns   &&
                                         resolver->lookupNamespaceURI(StandardPrefixes::empty) == StandardNamespaces::empty))
                                    {
                                        constructors.append(create(new NamespaceConstructor(nb), @$, parseInfo));
                                        resolver->addBinding(nb);
                                    }
                                }
                            }
                        }

                        if(parseInfo->elementConstructorDepth == 1 && !hasDefaultDeclaration)
                        {
                            /* TODO But mostly this isn't needed, since the default element
                             * namespace is empty? How does this at all work? */
                            const QXmlName def(resolver->lookupNamespaceURI(StandardPrefixes::empty), StandardLocalNames::empty);
                            constructors.append(create(new NamespaceConstructor(def), @$, parseInfo));
                        }

                        parseInfo->staticContext->setNamespaceBindings(resolver);
                        $<expressionList>$ = constructors;

                        /* Resolve the name of the element, now that the namespace attributes are read. */
                        {
                            const ReflectYYLTYPE ryy(@$, parseInfo);

                            const QXmlName ele = QNameConstructor::expandQName<StaticContext::Ptr,
                                                                               ReportContext::XPST0081,
                                                                               ReportContext::XPST0081>($2, parseInfo->staticContext, resolver, &ryy);
                            parseInfo->tagStack.push(ele);
                        }

                        parseInfo->tokenizer->resumeTokenizationFrom($<enums.tokenizerPosition>3);
                    }
                    POSITION_SET
                    DirAttributeList
                    DirElemConstructorTail                         /* [96] */
    {
        /* We add the content constructor after the attribute constructors. This might result
         * in nested ExpressionSequences, but it will be optimized away later on. */

        Expression::List attributes($<expressionList>5);
        const NamePool::Ptr namePool(parseInfo->staticContext->namePool());
        const int len = $7.size();
        QSet<QXmlName> declaredAttributes;
        declaredAttributes.reserve(len);

        /* For each namespace, resolve its name(now that we have resolved the namespace declarations) and
         * turn it into an attribute constructor. */
        for(int i = 0; i < len; ++i)
        {
            QString strLocalName;
            QString strPrefix;

            XPathHelper::splitQName($7.at(i).first, strPrefix, strLocalName);
            const QXmlName::PrefixCode prefix = namePool->allocatePrefix(strPrefix);
            const QXmlName::LocalNameCode localName = namePool->allocateLocalName(strLocalName);

            if(prefix == StandardPrefixes::xmlns ||
               (prefix == StandardPrefixes::empty && localName == StandardLocalNames::xmlns))
            {
                const Expression::ID id = $7.at(i).second->id();

                if(id == Expression::IDStringValue || id == Expression::IDEmptySequence)
                {
                    /* It's a namespace declaration, and we've already handled those above. */
                    continue;
                }
                else
                {
                    parseInfo->staticContext->error(QtXmlPatterns::tr("The namespace URI must be a constant and cannot "
                                                       "use enclosed expressions."),
                                                    ReportContext::XQST0022, fromYYLTYPE(@$, parseInfo));
                }

            }
            else
            {
                const ReflectYYLTYPE ryy(@$, parseInfo);
                const QXmlName att = QNameConstructor::expandQName<StaticContext::Ptr,
                                                                   ReportContext::XPST0081,
                                                                   ReportContext::XPST0081>($7.at(i).first, parseInfo->staticContext,
                                                                                            parseInfo->staticContext->namespaceBindings(),
                                                                                            &ryy, true);
                if(declaredAttributes.contains(att))
                {
                    parseInfo->staticContext->error(QtXmlPatterns::tr("An attribute by name %1 has already appeared on this element.")
                                                      .arg(formatKeyword(parseInfo->staticContext->namePool(), att)),
                                            ReportContext::XQST0040, fromYYLTYPE(@$, parseInfo));

                }
                else
                    declaredAttributes.insert(att);

                /* wrapLiteral() needs the SourceLocationReflection of the AttributeConstructor, but
                 * it's unknown inside the arguments to its constructor. Hence we have to do this workaround of setting
                 * it twice.
                 *
                 * The AttributeConstructor's arguments are just dummies. */
                const Expression::Ptr ctor(create(new AttributeConstructor($7.at(i).second, $7.at(i).second), @$, parseInfo));

                Expression::List ops;
                ops.append(wrapLiteral(toItem(QNameValue::fromValue(namePool, att)), parseInfo->staticContext, ctor.data()));
                ops.append($7.at(i).second);
                ctor->setOperands(ops);

                attributes.append(ctor);
            }
        }

        Expression::Ptr contentOp;

        if(attributes.isEmpty())
            contentOp = $8;
        else
        {
            attributes.append($8);
            contentOp = create(new ExpressionSequence(attributes), @$, parseInfo);
        }

        const Expression::Ptr name(create(new Literal(toItem(QNameValue::fromValue(parseInfo->staticContext->namePool(), parseInfo->tagStack.top()))), @$, parseInfo));
        $$ = create(new ElementConstructor(name, contentOp, parseInfo->isXSLT()), @$, parseInfo);

        /* Restore the old context. We don't want the namespaces
         * to be in-scope for expressions appearing after the
         * element they appeared on. */
        parseInfo->staticContext->setNamespaceBindings(parseInfo->resolvers.pop());
        parseInfo->tagStack.pop();

        --parseInfo->elementConstructorDepth;
    }

DirElemConstructorTail: QUICK_TAG_END
    {
        $$ = create(new EmptySequence(), @$, parseInfo);
    }
| G_GT DirElemContent BEGIN_END_TAG ElementName G_GT
    {
        if(!$4.isLexicallyEqual(parseInfo->tagStack.top()))
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("A direct element constructor is not "
                                               "well-formed. %1 is ended with %2.")
                                               .arg(formatKeyword(parseInfo->staticContext->namePool()->toLexical(parseInfo->tagStack.top())),
                                                    formatKeyword(parseInfo->staticContext->namePool()->toLexical($4))),
                                            ReportContext::XPST0003, fromYYLTYPE(@$, parseInfo));
        }

        if($2.isEmpty())
            $$ = create(new EmptySequence(), @$, parseInfo);
        else if($2.size() == 1)
            $$ = $2.first();
        else
            $$ = create(new ExpressionSequence($2), @$, parseInfo);
    }

DirAttributeList: /* empty */                                                       /* [97] */
    {
        $$ = AttributeHolderVector();
    }
| DirAttributeList Attribute
    {
        $1.append($2);
        $$ = $1;
    }

Attribute: LexicalName G_EQ DirAttributeValue                                       /* [X] */
    {
        $$ = qMakePair($1, $3);
    }

DirAttributeValue: QUOTE AttrValueContent QUOTE                                     /* [98] */
    {
        $$ = createDirAttributeValue($2, parseInfo, @$);
    }

| APOS AttrValueContent APOS
    {
        $$ = createDirAttributeValue($2, parseInfo, @$);
    }

AttrValueContent: /* Empty. */                                                      /* [X] */
    {
        $$ = Expression::List();
    }
| EnclosedExpr AttrValueContent
    {
        Expression::Ptr content($1);

        if(parseInfo->isBackwardsCompat.top())
            content = create(GenericPredicate::createFirstItem(content), @$, parseInfo);

        $2.prepend(createSimpleContent(content, @$, parseInfo));
        $$ = $2;
    }
| StringLiteral AttrValueContent
    {
        $2.prepend(create(new Literal(AtomicString::fromValue($1)), @$, parseInfo));
        $$ = $2;
    }

DirElemContent: /* empty */                                                         /* [101] */
    {
        $$ = Expression::List();
        parseInfo->isPreviousEnclosedExpr = false;
    }
| DirElemContent DirectConstructor
    {
        $1.append($2);
        $$ = $1;
        parseInfo->isPreviousEnclosedExpr = false;
    }
| DirElemContent StringLiteral
    {
        if(parseInfo->staticContext->boundarySpacePolicy() == StaticContext::BSPStrip &&
           XPathHelper::isWhitespaceOnly($2))
        {
            $$ = $1;
        }
        else
        {
            $1.append(create(new TextNodeConstructor(create(new Literal(AtomicString::fromValue($2)), @$, parseInfo)), @$, parseInfo));
            $$ = $1;
            parseInfo->isPreviousEnclosedExpr = false;
        }
    }
| DirElemContent NON_BOUNDARY_WS
    {
        $1.append(create(new TextNodeConstructor(create(new Literal(AtomicString::fromValue($2)), @$, parseInfo)), @$, parseInfo));
        $$ = $1;
        parseInfo->isPreviousEnclosedExpr = false;
    }
| DirElemContent EnclosedExpr
    {
        /* We insert a text node constructor that send an empty text node between
         * the two enclosed expressions, in order to ensure that no space is inserted.
         *
         * However, we only do it when we have no node constructors. */
        if(parseInfo->isPreviousEnclosedExpr &&
           BuiltinTypes::xsAnyAtomicType->xdtTypeMatches($2->staticType()->itemType()) &&
           BuiltinTypes::xsAnyAtomicType->xdtTypeMatches($1.last()->staticType()->itemType()))
            $1.append(create(new TextNodeConstructor(create(new Literal(AtomicString::fromValue(QString())), @$, parseInfo)), @$, parseInfo));
        else
            parseInfo->isPreviousEnclosedExpr = true;

        $1.append(createCopyOf($2, parseInfo, @$));
        $$ = $1;
    }

DirCommentConstructor: COMMENT_START COMMENT_CONTENT                                /* [103] */
    {
        $$ = create(new CommentConstructor(create(new Literal(AtomicString::fromValue($2)), @$, parseInfo)), @$, parseInfo);
    }

DirPIConstructor: PI_START PI_TARGET PI_CONTENT                                     /* [105] */
    {
        const ReflectYYLTYPE ryy(@$, parseInfo);
        NCNameConstructor::validateTargetName<StaticContext::Ptr,
                                              ReportContext::XPST0003,
                                              ReportContext::XPST0003>($2,
                                                                       parseInfo->staticContext, &ryy);

        $$ = create(new ProcessingInstructionConstructor(
                             create(new Literal(AtomicString::fromValue($2)), @$, parseInfo),
                             create(new Literal(AtomicString::fromValue($3)), @$, parseInfo)), @$, parseInfo);
    }

ComputedConstructor: CompDocConstructor                                             /* [109] */
| CompElemConstructor
| CompAttrConstructor
| CompTextConstructor
| CompCommentConstructor
| CompPIConstructor
| CompNamespaceConstructor

CompDocConstructor: DOCUMENT IsInternal EnclosedExpr                                /* [110] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $2);

        $$ = create(new DocumentConstructor($3), @$, parseInfo);
    }

CompElemConstructor: ELEMENT IsInternal CompElementName
                     {
                        /* This value is incremented before the action below is executed. */
                        ++parseInfo->elementConstructorDepth;
                     }
                     EnclosedOptionalExpr                                           /* [111] */
    {
        Q_ASSERT(5);
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $2);

        Expression::Ptr effExpr;

        if($5)
            effExpr = createCopyOf($5, parseInfo, @$);
        else
            effExpr = create(new EmptySequence(), @$, parseInfo);

        const QXmlName::NamespaceCode ns = parseInfo->resolvers.top()->lookupNamespaceURI(StandardPrefixes::empty);

        /* Ensure the default namespace gets counted as an in-scope binding, if such a one exists. If we're
         * a child of another constructor, it has already been done. */
        if(parseInfo->elementConstructorDepth == 1 && ns != StandardNamespaces::empty)
        {
            Expression::List exprList;

            /* We append the namespace constructor before the body, in order to
             * comply with QAbstractXmlPushHandler's contract. */
            const QXmlName def(parseInfo->resolvers.top()->lookupNamespaceURI(StandardPrefixes::empty), StandardLocalNames::empty);
            exprList.append(create(new NamespaceConstructor(def), @$, parseInfo));

            exprList.append(effExpr);

            effExpr = create(new ExpressionSequence(exprList), @$, parseInfo);
        }

        --parseInfo->elementConstructorDepth;
        $$ = create(new ElementConstructor($3, effExpr, parseInfo->isXSLT()), @$, parseInfo);
    }

IsInternal: /* Empty. */                                                          /* [X] */
    {
        $$ = false;
    }
| INTERNAL
    {
        $$ = true;
    }

CompAttrConstructor: ATTRIBUTE
                     IsInternal
                     CompAttributeName
                     EnclosedOptionalExpr                                           /* [113] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $2);

        const Expression::Ptr name(create(new AttributeNameValidator($3), @$, parseInfo));

        if($4)
            $$ = create(new AttributeConstructor(name, createSimpleContent($4, @$, parseInfo)), @$, parseInfo);
        else
            $$ = create(new AttributeConstructor(name, create(new EmptySequence(), @$, parseInfo)), @$, parseInfo);
    }

CompTextConstructor: TEXT IsInternal EnclosedExpr                                 /* [114] */
    {
        $$ = create(new TextNodeConstructor(createSimpleContent($3, @$, parseInfo)), @$, parseInfo);
    }

CompCommentConstructor: COMMENT IsInternal EnclosedExpr                           /* [115] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $2);

        $$ = create(new CommentConstructor(createSimpleContent($3, @$, parseInfo)), @$, parseInfo);
    }

CompPIConstructor: PROCESSING_INSTRUCTION CompPIName EnclosedOptionalExpr           /* [116] */
    {
        allowedIn(QXmlQuery::XQuery10, parseInfo, @$, $2);

        if($3)
        {
            $$ = create(new ProcessingInstructionConstructor($2, createSimpleContent($3, @$, parseInfo)), @$, parseInfo);
        }
        else
            $$ = create(new ProcessingInstructionConstructor($2, create(new EmptySequence(), @$, parseInfo)), @$, parseInfo);
    }

CompAttributeName: {
                        parseInfo->nodeTestSource = BuiltinTypes::attribute;
                   }
                   ElementName
                   {
                        parseInfo->restoreNodeTestSource();
                   }                                                                /* [X] */
    {
        $$ = create(new Literal(toItem(QNameValue::fromValue(parseInfo->staticContext->namePool(), $2))), @$, parseInfo);
    }
| CompNameExpr

CompElementName: ElementName                                                        /* [X] */
    {
        $$ = create(new Literal(toItem(QNameValue::fromValue(parseInfo->staticContext->namePool(), $1))), @$, parseInfo);
    }
| CompNameExpr

CompNameExpr: EnclosedExpr
    {
        if(BuiltinTypes::xsQName->xdtTypeMatches($1->staticType()->itemType()))
            $$ = $1;
        else
        {
            $$ = create(new QNameConstructor($1,
                                             parseInfo->staticContext->namespaceBindings()),
                        @$, parseInfo);
        }
    }

/*
 * We always create an NCNameConstructor here. If will be rewritten away if not needed.
 */
CompPIName: NCNAME
    {
        $$ = create(new NCNameConstructor(create(new Literal(AtomicString::fromValue($1)), @$, parseInfo)), @$, parseInfo);
    }
| EnclosedExpr
    {
        $$ = create(new NCNameConstructor($1), @$, parseInfo);
    }

/*
 * This expression is used for implementing XSL-T 2.0's xsl:namespace
 * instruction.
 */
CompNamespaceConstructor: NAMESPACE EnclosedExpr EnclosedExpr                       /* [X] */
{
    $$ = create(new ComputedNamespaceConstructor($2, $3), @$, parseInfo);
}

SingleType: AtomicType                                                              /* [117] */
    {
        $$ = makeGenericSequenceType($1, Cardinality::exactlyOne());
    }
| AtomicType QUESTION
    {
        $$ = makeGenericSequenceType($1, Cardinality::zeroOrOne());
    }

TypeDeclaration: /* empty */                                                        /* [118] */
    {
        $$ = CommonSequenceTypes::ZeroOrMoreItems;
    }
| AS SequenceType
    {
        $$ = $2;
    }

SequenceType: ItemType OccurrenceIndicator                                          /* [119] */
    {
        $$ = makeGenericSequenceType($1, $2);
    }

| EMPTY_SEQUENCE EmptyParanteses
    {
        $$ = CommonSequenceTypes::Empty;
    }

OccurrenceIndicator: /* empty */    {$$ = Cardinality::exactlyOne();}               /* [120] */
| PLUS                              {$$ = Cardinality::oneOrMore();}
| STAR                              {$$ = Cardinality::zeroOrMore();}
| QUESTION                          {$$ = Cardinality::zeroOrOne();}

ItemType: AtomicType                                                                /* [121] */
| KindTest
| AnyAttributeTest
| ITEM EmptyParanteses
    {
        $$ = BuiltinTypes::item;
    }

AtomicType: ElementName                                                             /* [122] */
    {
        const SchemaType::Ptr t(parseInfo->staticContext->schemaDefinitions()->createSchemaType($1));

        if(!t)
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("The name %1 does not refer to any schema type.")
                                               .arg(formatKeyword(parseInfo->staticContext->namePool(), $1)), ReportContext::XPST0051, fromYYLTYPE(@$, parseInfo));
        }
        else if(BuiltinTypes::xsAnyAtomicType->wxsTypeMatches(t))
            $$ = AtomicType::Ptr(t);
        else
        {
            /* Try to give an intelligent message. */
            if(t->isComplexType())
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is an complex type. Casting to complex "
                                                   "types is not possible. However, casting "
                                                   "to atomic types such as %2 works.")
                                                   .arg(formatType(parseInfo->staticContext->namePool(), t))
                                                   .arg(formatType(parseInfo->staticContext->namePool(), BuiltinTypes::xsInteger)),
                                                ReportContext::XPST0051, fromYYLTYPE(@$, parseInfo));
            }
            else
            {
                parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is not an atomic type. Casting "
                                                   "is only possible to atomic types.")
                                                   .arg(formatType(parseInfo->staticContext->namePool(), t)),
                                                ReportContext::XPST0051, fromYYLTYPE(@$, parseInfo));
            }
        }
    }

/* This non-terminal does not contain SchemaAttributeTest and AttributeTest.
   Those are in the AnyAttributeTest non-terminal. This is in order to get the axis
   right for attribute tests in the abbreviated syntax. */
KindTest: DocumentTest                                                          /* [123] */
| ElementTest
| SchemaElementTest
| PITest
| CommentTest
| TextTest
| AnyKindTest

AnyKindTest: NODE EmptyParanteses                                               /* [124] */
    {
        $$ = BuiltinTypes::node;
    }

DocumentTest: DOCUMENT_NODE EmptyParanteses                                     /* [125] */
    {
        $$ = BuiltinTypes::document;
    }

| DOCUMENT_NODE LPAREN AnyElementTest RPAREN
    {
        // TODO support for document element testing
        $$ = BuiltinTypes::document;
    }

AnyElementTest: ElementTest                                                     /* [X] */
| SchemaElementTest

TextTest: TEXT EmptyParanteses                                                  /* [126] */
    {
        $$ = BuiltinTypes::text;
    }

CommentTest: COMMENT EmptyParanteses                                            /* [127] */
    {
        $$ = BuiltinTypes::comment;
    }

PITest: PROCESSING_INSTRUCTION EmptyParanteses                                  /* [128] */
    {
        $$ = BuiltinTypes::pi;
    }

| PROCESSING_INSTRUCTION LPAREN NCNAME RPAREN
    {
        $$ = LocalNameTest::create(BuiltinTypes::pi, parseInfo->staticContext->namePool()->allocateLocalName($3));
    }

| PROCESSING_INSTRUCTION LPAREN StringLiteral RPAREN
    {
        if(QXmlUtils::isNCName($3))
        {
            $$ = LocalNameTest::create(BuiltinTypes::pi, parseInfo->staticContext->namePool()->allocateLocalName($3));
        }
        else
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is not a valid name for a "
                                                              "processing-instruction.")
                                                 .arg(formatKeyword($3)),
                                            ReportContext::XPTY0004,
                                            fromYYLTYPE(@$, parseInfo));
        }
    }

AnyAttributeTest: AttributeTest
| SchemaAttributeTest

AttributeTest: ATTRIBUTE EmptyParanteses                                            /* [129] */
    {
        $$ = BuiltinTypes::attribute;
    }

| ATTRIBUTE LPAREN STAR RPAREN
    {
        $$ = BuiltinTypes::attribute;
    }

| ATTRIBUTE LPAREN AttributeName RPAREN
    {
        $$ = QNameTest::create(BuiltinTypes::attribute, $3);
    }
| ATTRIBUTE LPAREN AttributeName COMMA TypeName RPAREN
    {
        const SchemaType::Ptr t(parseInfo->staticContext->schemaDefinitions()->createSchemaType($5));

        if(t)
            $$ = BuiltinTypes::attribute;
        else
        {
            parseInfo->staticContext->error(unknownType().arg(formatKeyword(parseInfo->staticContext->namePool(), $5)),
                                            ReportContext::XPST0008, fromYYLTYPE(@$, parseInfo));
        }
    }
| ATTRIBUTE LPAREN STAR COMMA TypeName RPAREN
    {
        const SchemaType::Ptr t(parseInfo->staticContext->schemaDefinitions()->createSchemaType($5));

        if(t)
            $$ = BuiltinTypes::attribute;
        else
        {
            parseInfo->staticContext->error(unknownType().arg(formatKeyword(parseInfo->staticContext->namePool(), $5)),
                                            ReportContext::XPST0008, fromYYLTYPE(@$, parseInfo));
        }
    }

SchemaAttributeTest: SCHEMA_ATTRIBUTE LPAREN ElementName RPAREN                     /* [131] */
    {
        parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is not in the in-scope attribute "
                                           "declarations. Note that the schema import "
                                           "feature is not supported.")
                                           .arg(formatKeyword(parseInfo->staticContext->namePool(), $3)),
                                        ReportContext::XPST0008, fromYYLTYPE(@$, parseInfo));
        $$.reset();
    }

ElementTest: ELEMENT EmptyParanteses                                                /* [133] */
    {
        $$ = BuiltinTypes::element;
    }

| ELEMENT LPAREN STAR RPAREN
    {
        $$ = BuiltinTypes::element;
    }

| ELEMENT LPAREN ElementName RPAREN
    {
        $$ = QNameTest::create(BuiltinTypes::element, $3);
    }

| ELEMENT LPAREN ElementName COMMA TypeName OptionalQuestionMark RPAREN
    {
        const SchemaType::Ptr t(parseInfo->staticContext->schemaDefinitions()->createSchemaType($5));

        if(t)
            $$ = BuiltinTypes::element;
        else
        {
            parseInfo->staticContext->error(unknownType()
                                               .arg(formatKeyword(parseInfo->staticContext->namePool(), $5)),
                                            ReportContext::XPST0008, fromYYLTYPE(@$, parseInfo));
        }
    }

| ELEMENT LPAREN STAR COMMA TypeName OptionalQuestionMark RPAREN
    {
        const SchemaType::Ptr t(parseInfo->staticContext->schemaDefinitions()->createSchemaType($5));

        if(t)
            $$ = BuiltinTypes::element;
        else
        {
            parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is an unknown schema type.")
                                               .arg(formatKeyword(parseInfo->staticContext->namePool(), $5)),
                                            ReportContext::XPST0008, fromYYLTYPE(@$, parseInfo));
        }
    }

OptionalQuestionMark: /* Empty. */
| QUESTION

SchemaElementTest: SCHEMA_ELEMENT LPAREN ElementName RPAREN                         /* [135] */
    {
        parseInfo->staticContext->error(QtXmlPatterns::tr("%1 is not in the in-scope attribute "
                                           "declarations. Note that the schema import "
                                           "feature is not supported.")
                                           .arg(formatKeyword(parseInfo->staticContext->namePool(), $3)),
                                        ReportContext::XPST0008, fromYYLTYPE(@$, parseInfo));
        $$.reset();
    }

EmptyParanteses: LPAREN RPAREN                                                      /* [X] */

AttributeName: NCNAME                                                               /* [137] */
    {
        $$ = parseInfo->staticContext->namePool()->allocateQName(StandardNamespaces::empty, $1);
    }

| QName

/*
 * When a QName appear with no prefix, it uses a certain default namespace
 * depending on where the QName occurs. These two rules, invoked in the appropriate
 * contexts, performs this distinction.
 */
ElementName: NCNAME                                                                 /* [138] */
    {
        if(parseInfo->nodeTestSource == BuiltinTypes::element)
            $$ = parseInfo->staticContext->namePool()->allocateQName(parseInfo->staticContext->namespaceBindings()->lookupNamespaceURI(StandardPrefixes::empty), $1);
        else
            $$ = parseInfo->staticContext->namePool()->allocateQName(StandardNamespaces::empty, $1);
    }
| QName

TypeName: ElementName                                                               /* [139] */

FunctionName: NCName                                                                /* [X] */
| QName

NCName: NCNAME
    {
        $$ = parseInfo->staticContext->namePool()->allocateQName(parseInfo->staticContext->defaultFunctionNamespace(), $1);
    }
| INTERNAL_NAME NCNAME
    {
        $$ = parseInfo->staticContext->namePool()->allocateQName(StandardNamespaces::InternalXSLT, $2);
    }

LexicalName: NCNAME
| QNAME

PragmaName: NCNAME                                                                  /* [X] */
    {
        parseInfo->staticContext->error(QtXmlPatterns::tr("The name of an extension expression must be in "
                                                          "a namespace."),
                                        ReportContext::XPST0081, fromYYLTYPE(@$, parseInfo));
    }
| QName

URILiteral: StringLiteral                                                           /* [140] */

StringLiteral: STRING_LITERAL                                                       /* [144] */
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
    }
| XPATH2_STRING_LITERAL
    {
        allowedIn(QueryLanguages(QXmlQuery::XQuery10 | QXmlQuery::XPath20), parseInfo, @$);
    }

QName: QNAME                                                      /* [154] */
    {

        const ReflectYYLTYPE ryy(@$, parseInfo);

        $$ = QNameConstructor::
             expandQName<StaticContext::Ptr,
                         ReportContext::XPST0081,
                         ReportContext::XPST0081>($1, parseInfo->staticContext,
                                                  parseInfo->staticContext->namespaceBindings(), &ryy);

    }
| CLARK_NAME
    {
        $$ = parseInfo->staticContext->namePool()->fromClarkName($1);
    }

%%

QString Tokenizer::tokenToString(const Token &token)
{
    switch(token.type)
    {
        case NCNAME:
        /* Fallthrough. */
        case QNAME:
        /* Fallthrough. */
        case NUMBER:
        /* Fallthrough. */
        case XPATH2_NUMBER:
            return token.value;
        case STRING_LITERAL:
            return QLatin1Char('"') + token.value + QLatin1Char('"');
        default:
        {
            const QString raw(QString::fromLatin1(yytname[YYTRANSLATE(token.type)]));

            /* Remove the quotes. */
            if(raw.at(0) == QLatin1Char('"') && raw.length() > 1)
                return raw.mid(1, raw.length() - 2);
            else
                return raw;
        }
    }
}

} /* namespace Patternist */

QT_END_NAMESPACE

// vim: et:ts=4:sw=4:sts=4:syntax=yacc