File: xpath.ry

package info (click to toggle)
ruby-xmlparser 0.7.3-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 896 kB
  • sloc: ruby: 9,323; ansic: 2,016; makefile: 11
file content (2352 lines) | stat: -rw-r--r-- 51,366 bytes parent folder | download | duplicates (8)
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
#
# xpath.ry
#
#   Copyright (C) Ueno Katsuhiro 2000
#
# $Id: xpath.ry,v 1.2 2003/03/12 06:38:21 yoshidam Exp $
#

class Compiler

prechigh
  left '|'
  right NEG
  left MUL 'div' 'mod'
  left '+' '-'
  left '<' '>' '<=' '>='
  left '=' '!='
  left 'and'
  left 'or'
preclow

options no_result_var


rule

  xPath:          # none #
                      { [] }
                  | expr
                      {
                        expr = val[0].expr('.to_ruby')
                        expr.collect! { |i| i or @context }
                        expr
                      }
                  | PATTERN pattern     # for XSLT
                      {
                        expr = val[0].expr('.to_ruby')
                        expr.collect! { |i| i or @context }
                        expr
                      }

  pattern:        locationPath
                  | pattern '|' locationPath
                      { val[0] ** val[2] }

  expr:           expr 'or' expr
                      { val[0].logical_or val[2] }
                  | expr 'and' expr
                      { val[0].logical_and val[2] }
                  | expr '=' expr
                      { val[0].eq val[2] }
                  | expr '!=' expr
                      { val[0].neq val[2] }
                  | expr '<' expr
                      { val[0].lt val[2] }
                  | expr '>' expr
                      { val[0].gt val[2] }
                  | expr '<=' expr
                      { val[0].le val[2] }
                  | expr '>=' expr
                      { val[0].ge val[2] }
                  | expr '+' expr
                      { val[0] + val[2] }
                  | expr '-' expr
                      { val[0] - val[2] }
                  | '-' expr =NEG
                      { -val[1] }
                  | expr MUL expr
                      { val[0] * val[2] }
                  | expr 'div' expr
                      { val[0] / val[2] }
                  | expr 'mod' expr
                      { val[0] % val[2] }
                  | expr '|' expr
                      {
                        # Why `**' is used for unionizing node-sets is that its
                        # precedence is higher than any other binary operators
                        # in Ruby.
                        val[0] ** val[2]
                      }
                  | locationPath
                  | filterExpr
                  | filterExpr '/' relPath
                      { val[0] << val[2] }
                  | filterExpr '//' relPath
                      { val[0].add_step('descendant-or-self') << val[2] }

  filterExpr:     Variable
                      {
                        Expression.new [ nil,'.get_variable(',val[0].dump,')' ]
                      }
                  | '(' expr ')'
                      { val[1].unarize }
                  | Literal
                      { Expression.new StringConstant.new(val[0]) }
                  | Number
                      { Expression.new NumberConstant.new(val[0]) }
                  | functionCall
                      { Expression.new val[0] }
                  | filterExpr predicate
                      { val[0].add_predicate val[1] }

  functionCall:   FuncName '(' arguments ')'
                      {
                        val[2][0,0] = [ nil, ".funcall(#{val[0].dump}" ]
                        val[2].push(')')
                      }

  arguments:      # none #
                      { [] }
                  | expr
                      { val[0].expr.unshift ', ' }
                  | arguments ',' expr
                      { val[0].push(', ').concat(val[2].expr) }

  predicate:      '['
                      {
                        c = @context
                        @context = c.succ
                        c
                      }
                  expr
                      {
                        c = @context
                        @context = _values[-2]
                        c
                      }
                  ']'
                      {
                        expr = val[2]
                        valuetype = expr.value_type
                        value = expr.value
                        if valuetype == :number then
                          if value then
                            f = value.to_f
                            if f > 0 and f.truncate == f then
                              [ ".at(#{f.to_i})" ]
                            else
                              [ '.at(0)' ]   # clear
                            end
                          else
                            expr.expr('.to_f').
                              unshift('.at(').push(')')
                          end
                        elsif value then
                          if value.true? then
                            []
                          else
                            [ '.at(0)' ]   # clear
                          end
                        else
                          c = val[3]
                          if valuetype == :ruby_boolean then
                            conv = '.true?'
                          else
                            conv = '.to_predicate'
                          end
                          a = expr.expr(conv)
                          a.collect! { |i| i or c }
                          a.unshift(".predicate { |#{c}| ").push(' }')
                        end
                      }

  locationPath:   '/'
                      { LocationPath.new.absolute! }
                  | '/' relPath
                      { val[1].absolute! }
                  | '//' relPath
                      {
                        path = LocationPath.new
                        path.absolute!
                        path.add_step('descendant-or-self') << val[1]
                      }
                  | relPath

  relPath:        step
                      { LocationPath.new.add_step(*val[0]) }
                  | relPath '/' step
                      { val[0].add_step(*val[2]) }
                  | relPath '//' step
                      {
                        val[0].add_step('descendant-or-self').add_step(*val[2])
                      }
                  # XPath does not permit functions here, but XPointer does.
                  | relPath '/' FuncName '('
                      {
                        c = @context
                        @context = c.succ
                        c
                      }
                    arguments
                      {
                        c = @context
                        @context = _values[-2]
                        c
                      }
                  ')'
                      {
                        on_error unless is_xpointer?
                        args = val[5]
                        c = val[6]
                        args.collect! { |i| i or c }
                        args[0] = ".funcall(#{val[2].dump}) { |#{c}| ["
                        args.push '] }'
                        val[0].add_predicate args
                      }

  step:           '.'
                      { [ 'self', false, false, false, nil ] }
                  | '..'
                      { [ 'parent', false, false, false, nil ] }
                  | axisSpec nodeTest predicates
                      {
                        nodetest = val[1]
                        unless nodetest[0] then
                          axis = val[0]
                          if axis != 'attribute' and axis != 'namespace' then
                            nodetest[0] = 'element'
                          end
                        end
                        nodetest[0] = false if nodetest[0] == 'node'
                        nodetest.unshift(val[0]).push(val[2])
                      }

  predicates:     # none #
                  | predicates predicate
                      { (val[0] || []).concat val[1] }

  nodeTest:       '*'
                      { [ false, false, false ] }
                  | Name
                      {
                        if /:/ =~ val[0] then
                          [ false, $', $` ]   #' <= for racc
                        else
                          [ false, val[0], nil ]
                        end
                      }
                  | Name ':' '*'
                      {
                        on_error if /:/ =~ val[0]
                        [ false, false, val[0] ]
                      }
                  | NodeType '(' nodeTestArg ')'
                      {
                        nodetype = val[0]
                        arg = val[2]
                        if arg and nodetype != 'processing-instruction' then
                          raise CompileError,
                            "nodetest #{nodetype}() requires no argument"
                        end
                        [ nodetype, arg || false, false ]
                      }

  nodeTestArg:    # none #
                  | Literal

  axisSpec:       # none #
                      { 'child' }
                  | '@'
                      { 'attribute' }
                  | AxisName '::'

end


---- inner ----

  module CompilePhaseObject

    def invoke_conv(expr, conv_method)
      return unless conv_method
      if conv_method == '.to_number' or
          conv_method == '.to_string' or
          conv_method == '.to_boolean' then
        expr.push conv_method, '(', nil, ')'
      else
        expr.push conv_method
      end
    end
    private :invoke_conv

  end


  module ConstantObject

    include CompilePhaseObject

    def to_string
      StringConstant.new to_str
    end

    def to_number
      NumberConstant.new self
    end

    def to_boolean
      if true? then
        ConstantTrue
      else
        ConstantFalse
      end
    end

  end


  module BooleanConstant

    include ConstantObject

    def value_type
      :boolean
    end

    def expr(conv_method = nil)
      if conv_method == '.to_ruby' or conv_method == '.true?' then
        [ true?.to_s ]
      else
        ret = [ nil, '.make_boolean(', true?.to_s, ')' ]
        invoke_conv ret, conv_method unless conv_method == '.to_boolean'
        ret
      end
    end

  end

  class ConstantTrueClass < XPathTrueClass
    include BooleanConstant
    @instance = new
  end

  class ConstantFalseClass < XPathFalseClass
    include BooleanConstant
    @instance = new
  end

  ConstantTrue = ConstantTrueClass.instance
  ConstantFalse = ConstantFalseClass.instance



  class NumberConstant < XPathNumber

    include ConstantObject

    def value_type
      :number
    end

    def initialize(src)
      f = src.to_f
      if src.is_a? ConstantObject and s = dump_float(f) then
        src = s
      end
      @src = [ src ]
      @precedence = 1
      super f
    end

    attr_reader :precedence
    protected :precedence

    def to_number
      self
    end


    def expr(conv_method = nil)
      @src.collect! { |i|
        if i.is_a? ConstantObject then
          i.expr '.to_f'
        else
          i
        end
      }
      expr = @src
      expr.flatten!
      @src = :draff  # for debug
      unless conv_method == '.to_ruby' or conv_method == '.to_f' then
        expr[0, 0] = [ nil, '.make_number(' ]
        expr.push(')')
        invoke_conv expr, conv_method unless conv_method == '.to_number'
      end
      expr
    end


    private

    def dump_float(f)
      if f.finite? and f == eval(s = f.to_s) then
        s
      elsif f.infinite? then
        if f > 0 then
          '(1.0 / 0.0)'
        else
          '(-1.0 / 0.0)'
        end
      elsif f.nan? then
        '(0.0 / 0.0)'
      else
        nil
      end
    end


    def concat(op, other, prec)
      @src.unshift('(').push(')') if @precedence < prec
      if other.precedence < prec then
        @src.push(op).push('(').concat(other.expr('.to_f')).push(')')
      else
        @src.push(op).concat(other.expr('.to_f'))
      end
      @precedence = prec
    end


    public

    def self.def_arithmetic_operator(op, precedence)
      module_eval <<_, __FILE__, __LINE__ + 1
      def #{op}(other)
        super other
        if s = dump_float(@value) then
          @src.clear
          @src.push s
        else
          concat ' #{op} ', other, #{precedence}
        end
        self
      end
_
    end

    def_arithmetic_operator '+', 0
    def_arithmetic_operator '-', 0
    def_arithmetic_operator '*', 1
    def_arithmetic_operator '/', 1

    class << self
      undef def_arithmetic_operator
    end

    def %(other)
      orig = @value
      super other
      if s = dump_float(@value) then
        @src.clear
        @src.push s
      else
        f = other.to_f
        other = -other if orig % f == -@value
        concat ' % ', other, 1
      end
      self
    end

    def -@
      super
      if s = dump_float(@value) then
        @src.clear
        @src.push s
      else
        if @src.size == 1 then
          @src.unshift '-'
        else
          @src.unshift('-(').push(')')
        end
        @precedence = 1
      end
      self
    end

  end



  class StringConstant < XPathString

    include ConstantObject

    def value_type
      :string
    end

    def to_string
      self
    end

    def expr(conv_method = nil)
      if conv_method == '.to_ruby' or conv_method == '.to_str' then
        [ @value.dump ]
      else
        ret = [ nil, '.make_string(', @value.dump, ')' ]
        invoke_conv ret, conv_method unless conv_method == '.to_string'
        ret
      end
    end

  end



  class Expression

    include CompilePhaseObject

    def initialize(expr)
      if expr.is_a? ConstantObject then
        @value = expr
      else
        raise "BUG" unless expr.is_a? Array
        @value = nil
        @valuetype = nil
        @expr = expr
      end
      @unary = true
    end

    attr_reader :value


    def value_type
      if @value then
        @value.value_type
      else
        @valuetype
      end
    end


    def unarize
      unless @unary then
        @expr.unshift('(').push(')')
        @unary = true
      end
      self
    end


    def self.def_comparison_operator(name, op)
      module_eval <<_, __FILE__, __LINE__ + 1
      def #{name}(other)
        if @value and other.value then
          if @value #{op} other.value then
            @value = ConstantTrue
          else
            @value = ConstantFalse
          end
          @unary = true
        else
          @expr = expr.push(' #{op} ').concat(other.expr)
          @valuetype = :ruby_boolean
          @unary = false
        end
        self
      end
_
    end

    def self.def_arithmetic_operator(*ops)
      ops.each { |op|
        module_eval <<_, __FILE__, __LINE__ + 1
        def #{op}(other)
          if @value and other.value then
            @value = @value.to_number #{op} other.value.to_number
          else
            @expr = expr('.to_number').push(' #{op} ')
            # not 'to_number', for a little speed up :-)
            @expr.concat other.expr('.to_f')
            @valuetype = :number
            @unary = false
          end
          self
        end
_
      }
    end

    def_comparison_operator 'eq',  '=='
    def_comparison_operator 'neq', '!='
    def_comparison_operator 'lt',  '<'
    def_comparison_operator 'gt',  '>'
    def_comparison_operator 'le',  '<='
    def_comparison_operator 'ge',  '>='
    def_arithmetic_operator '+', '-', '*', '/', '%'

    class << self
      undef def_comparison_operator
      undef def_arithmetic_operator
    end

    def -@
      if @value then
        @value = -@value.to_number
      else
        unarize
        @expr = expr('.to_number').unshift('-')
      end
      self
    end

    def logical_or(other)
      if @value and @value.true? then
        @value = ConstantTrue
        @unary = true
        @expr = @valuetype = nil
      else
        @expr = expr('.true?').push(' || ').concat(other.expr('.true?'))
        @valuetype = :ruby_boolean
        @unary = false
      end
      self
    end

    def logical_and(other)
      if @value and not @value.true? then
        @value = ConstantFalse
        @unary = true
        @expr = @valuetype = nil
      else
        @expr = expr('.true?').push(' && ').concat(other.expr('.true?'))
        @valuetype = :ruby_boolean
        @unary = false
      end
      self
    end

    def **(other)
      @expr = expr.push(' ** ').concat(other.expr)
      @valuetype = nil
      @unary = false
      self
    end


    def add_predicate(pred)
      unarize
      @expr = expr.concat(pred)
      @valuetype = nil
      self
    end

    def <<(other)
      path = other.expr
      path.shift  # nil
      path.shift  # .to_nodeset
      add_predicate path
    end

    def add_step(axis)
      add_predicate [ ".step(:#{axis.tr('-','_')})" ]
    end


    def expr(conv_method = nil)
      if @value then
        ret = @value.expr(conv_method)
        @value = nil
      elsif @valuetype == :ruby_boolean then
        ret = @expr
        unless conv_method == '.to_ruby' or conv_method == '.true?' then
          ret[0, 0] = [ nil, '.make_boolean(' ]
          ret.push ')'
          invoke_conv ret, conv_method unless conv_method == '.to_boolean'
        end
      elsif @valuetype == :number and conv_method == '.to_number' then
        ret = @expr
      elsif @valuetype == :string and conv_method == '.to_string' then
        ret = @expr
      elsif @valuetype == :boolean and conv_method == '.to_boolean' then
        ret = @expr
      else
        if conv_method then
          unarize
          invoke_conv @expr, conv_method
        end
        ret = @expr
      end
      @expr = :draff   # for debug
      ret
    end

  end



  class LocationPath

    include CompilePhaseObject

    def initialize
      @root = false
      @steps = []    # [ axis, [ tests ], predicates ]
    end

    attr_reader :root, :steps
    protected :root, :steps

    def absolute!
      @root = true
      self
    end


    def add_step(axis, nodetype = false, localpart = false,
                 namespace = false, predicate = nil)
      if nodetype == false and localpart == false and namespace == false then
        append_step axis, [], predicate
      else
        append_step axis, [ [ nodetype, localpart, namespace ] ], predicate
      end
      self
    end


    def <<(other)
      raise "BUG" if other.root
      other = other.steps
      other.each { |step|
        if step[0] then
          append_step(*step)
        else
          add_predicate(step[2])
        end
      }
      self
    end


    def add_predicate(pred)
      @steps.push [ nil, nil, pred ]
      self
    end


    def **(other)
      unless other.is_a? LocationPath then
        ret = nil
      else
        othersteps = other.steps
        size = @steps.size
        unless size == othersteps.size then
          othersize = othersteps.size
          if size >= othersize then
            ret = (@steps[0, othersize] == othersize and self)
          else
            ret = (othersteps[0, size] == @steps and other)
          end
        else
          last = @steps.pop
          otherlast = othersteps.pop
          if @steps == othersteps and mix_step(last, otherlast) then
            ret = self
          else
            ret = nil
          end
          @steps.push last
          othersteps.push otherlast
        end
      end
      ret or Expression.new(expr) ** other
    end


    private

    UnifiableAxes = {
      'descendant' => {
        'descendant-or-self' => 'descendant',
      },
      'descendant-or-self' => {
        'child'              => 'descendant',
        'descendant'         => 'descendant',
        'descendant-or-self' => 'descendant-or-self',
      },
      'ancestor' => {
        'ancestor-or-self'   => 'ancestor',
      },
      'ancestor-or-self' => {
        'parent'             => 'ancestor',
        'ancestor'           => 'ancestor',
        'ancestor-or-self'   => 'ancestor-or-self',
      },
      'following-sibling' => {
        'following-sibling'  => 'following-sibling',
      },
      'preceding-sibling' => {
        'preceding-sibling'  => 'preceding-sibling',
      },
      'following' => {
        'following'          => 'following',
        'following-sibling'  => 'following',
      },
      'preceding' => {
        'preceding'          => 'preceding',
        'preceding-sibling'  => 'preceding',
      },
      'child' => {
        'following-sibling'  => 'child',
        'preceding-sibling'  => 'child',
      },
    }
    UnifiableAxes.default = {}


    def append_step(axis, test, predicate)
      lastaxis, lasttest, lastpred = laststep = @steps.last
      if axis == 'self' and test.empty? then
        @steps.push [ nil, nil, predicate ] if predicate
      elsif lastaxis and lasttest.empty? and
          not lastpred and not predicate and
          w = UnifiableAxes[lastaxis][axis] then
        laststep[0] = w
        laststep[1] = test
      else
        @steps.push [ axis, test, predicate ]
      end
    end


    def mix_step(step, other)
      if step[0] and step[0] == other[0] and step[2] == other[2] then
        step[1].concat other[1]
        step
      else
        nil
      end
    end


    public

    def expr(conv_method = nil)
      if @root then
        expr = [ nil, '.root_nodeset' ]
      else
        expr = [ nil, '.to_nodeset' ]
      end
      @steps.each { |axis,test,predicate|
        if axis.nil? then   # predicate only
          expr.concat predicate
        elsif test.empty? and not predicate then
          expr.push ".select_all(:#{axis.tr('-','_')})"
        else
          expr.push ".step(:#{axis.tr('-','_')})"
          if test.empty? then
            expr.push ' { |n| n.select_all'
          else
            expr.push ' { |n| n.select { |i| '
            test.each { |nodetype,localpart,namespace|
              if nodetype then
                expr.push "i.node_type == :#{nodetype.tr('-','_')}", ' && '
              end
              if localpart then
                expr.push "i.name_localpart == #{localpart.dump}", ' && '
              end
              if namespace.nil? then
                expr.push 'i.namespace_uri.nil?', ' && '
              elsif namespace then
                namespace = namespace.dump
                expr.push('i.namespace_uri == ', nil,
                          ".get_namespace(#{namespace})", ' && ')
              end
              expr[-1] = ' or '
            }
            expr[-1] = ' }'
          end
          expr.concat predicate if predicate
          expr.push ' }'
        end
      }
      @steps = :draff   # for debug
      invoke_conv expr, conv_method
      expr
    end


    def value_type
      nil
    end

    def value
      nil
    end

    def unarize
      self
    end

    def self.redirect_to_expr(*ops)
      ops.each { |op|
        name = op
        name = op[1..-1] if op[0] == ?.
        module_eval <<_, __FILE__, __LINE__ + 1
        def #{name}(arg) ; Expression.new(expr) #{op} arg ; end
_
      }
    end

    redirect_to_expr('.eq', '.neq', '.lt', '.gt', '.le', '.ge',
                     '+', '-', '*', '/', '%', '.logical_or', '.logical_and')

    class << self
      undef redirect_to_expr
    end

    def -@
      -Expression.new(expr)
    end

  end




  Delim = '\\s\\(\\)\\[\\]\\.@,\\/\\|\\*\\+"\'=!<>:'
  Name = "[^-#{Delim}][^#{Delim}]*"

  Operator = {
    '@' => true, '::' => true, '(' => true, '[' => true,
    :MUL => true, 'and' => true, 'or' => true, 'mod' => true, 'div' => true,
    '/'  => true, '//' => true, '|'  => true, '+' => true,
    '-'  => true, '='  => true, '!=' => true, '<' => true,
    '<=' => true, '>'  => true, '>=' => true,
    ':' => false
    # ':' '*'    => '*' must not be a MultiplyOperator
    # ':' 'and'  => 'and' must be a OperatorName
  }

  NodeType = {
    'comment' => true,
    'text' => true,
    'processing-instruction' => true,
    'node' => true,
  }


  private

  def axis?(s)
    /\A[-a-zA-Z]+\z/ =~ s
  end

  def nodetype?(s)
    NodeType.key? s
  end

  def tokenize(src)
    token = []
    src.scan(/(\.\.?|\/\/?|::?|!=|[<>]=?|[-()\[\].@,|+=*])|
              ("[^"]*"|'[^']*')|(\d+\.?\d*)|
              (\$?#{Name}(?::#{Name})?)|
              \s+|./ox) { |delim,literal,number,name|  #/
      if delim then
        if delim == '*' then
          delim = :MUL if (prev = token[-1]) and not Operator.key? prev[0]
        elsif delim == '::' then
          prev = token[-1]
          if prev and prev[0] == :Name and axis? prev[1] then
            prev[0] = :AxisName
          end
        elsif delim == '(' then
          if (prev = token[-1]) and prev[0] == :Name then
            if nodetype? prev[1] then
              prev[0] = :NodeType
            else
              prev[0] = :FuncName
            end
          end
        end
        token.push [ delim, delim ]
      elsif name then
        prev = token[-1]
        if name[0] == ?$ then
          name[0,1] = ''
          token.push [ :Variable, name ]
        elsif Operator.key? name and
            (prev = token[-1]) and not Operator[prev[0]] then
          token.push [ name, name ]
        else
          token.push [ :Name, name ]
        end
      elsif number then
        number << '.0' unless number.include? ?.
        token.push [ :Number, number ]
      elsif literal then
        literal.chop!
        literal[0,1] = ''
        token.push [ :Literal, literal ]
      else
        s = $&.strip
        token.push [ s, s ] unless s.empty?
      end
    }
    token
  end


  public

  def compile(src, pattern = false)
    @token = tokenize(src)
    @token.push [ false, :end ]
    @token.each { |i| p i } if @yydebug
    @token.reverse!
    @token.push [ :PATTERN, nil ] if pattern
    @context = 'context0'
    ret = do_parse
    ret = ret.unshift("proc { |context0| ").push(" }").join
    print ">>>>\n", ret, "\n<<<<\n" if @yydebug
    XPathProc.new eval(ret), src
  end


  def initialize(debug = false)
    super()
    @yydebug = debug
  end


  private

  def next_token
    @token.pop
  end


  def is_xpointer?
    false
  end


  def on_error(*args) # tok, val, values
    raise CompileError, 'parse error'
  end


---- header ----
#
# xpath.rb : generated by racc
#

module XPath

  class Error < StandardError ; end
  class CompileError < Error ; end
  class TypeError < Error ; end
  class NameError < Error ; end
  class ArgumentError < Error ; end
  class InvalidOperation < Error ; end


  class XPathProc

    def initialize(proc, source)
      @proc = proc
      @source = source
    end

    attr_reader :source

    def call(context)
      @proc.call context
    end

  end


  def self.compile(src, pattern = false)
    @compiler = Compiler.new unless defined? @compiler
    @compiler.compile src, pattern
  end



  module XPathObject

    def _type
      type.name.sub(/\A.*::(?:XPath)?(?=[^:]+\z)/, '')
    end
    private :_type

    def type_error(into)
      raise XPath::TypeError, "failed to convert #{_type} into #{into}"
    end
    private :type_error


    def to_str         # => to Ruby String
      type_error 'String'
    end

    def to_f           # => to Ruby Float
      type_error 'Float'
    end

    def true?          # => to Ruby Boolean
      type_error 'Boolean'
    end

    def to_ruby        # => to Ruby Object
      self
    end

    def to_predicate   # => to Ruby Float, true or false. shouldn't override.
      true?
    end


    def to_string(context)   # => to XPath String. shouldn't override.
      context.make_string to_str
    end

    def to_number(context)   # => to XPath Number. shouldn't override.
      context.make_number to_f
    end

    def to_boolean(context)  # => to XPath Boolean. shouldn't override.
      context.make_boolean true?
    end


    public

    # called from compiled XPath expression

    def ==(other)
      if other.is_a? XPathNodeSet or
          other.is_a? XPathBoolean or other.is_a? XPathNumber then
        other == self
      else
        to_str == other.to_str
      end
    end

    def <(other)
      if other.is_a? XPathNodeSet then
        other > self
      else
        to_f < other.to_f
      end
    end

    def >(other)
      if other.is_a? XPathNodeSet then
        other < self
      else
        to_f > other.to_f
      end
    end

    def <=(other)
      if other.is_a? XPathNodeSet then
        other >= self
      else
        to_f <= other.to_f
      end
    end

    def >=(other)
      if other.is_a? XPathNodeSet then
        other <= self
      else
        to_f >= other.to_f
      end
    end

    def **(other)
      type_error 'NodeSet'
    end

    def predicate(&block)
      type_error 'NodeSet'
    end

    def at(pos)
      type_error 'NodeSet'
    end

    def funcall(name)   # for XPointer
      raise XPath::NameError, "undefined function `#{name}' for #{_type}"
    end

  end




  class XPathBoolean

    include XPathObject

    class << self
      attr_reader :instance
      private :new
    end

    def to_str
      true?.to_s
    end

    # def to_f
    # def true?

    def to_ruby
      true?
    end

    def to_boolean(context)
      self
    end

    def ==(other)
      true? == other.true?
    end

  end


  class XPathTrueClass < XPathBoolean

    @instance = new

    def to_f
      1.0
    end

    def true?
      true
    end

  end


  class XPathFalseClass < XPathBoolean

    @instance = new

    def to_f
      0.0
    end

    def true?
      false
    end

  end


  XPathTrue = XPathTrueClass.instance
  XPathFalse = XPathFalseClass.instance




  class XPathNumber

    include XPathObject

    def initialize(num)
      raise ::TypeError, "must be a Float" unless num.is_a? Float
      @value = num
    end

    def to_str
      if @value.nan? then
        'NaN'
      elsif @value.infinite? then
        if @value < 0 then
          '-Infinity'
        else
          'Infinity'
        end
      else
        sprintf("%.100f", @value).gsub(/\.?0+\z/, '')    # enough?
      end
    end

    def to_f
      @value
    end

    def true?
      @value != 0.0 and not @value.nan?
    end

    def to_ruby
      to_f
    end

    def to_predicate
      to_f
    end

    def to_number(context)
      self
    end


    def ==(other)
      if other.is_a? XPathNodeSet or other.is_a? XPathBoolean then
        other == self
      else
        @value == other.to_f
      end
    end

    def +(other)
      @value += other.to_f
      self
    end

    def -(other)
      @value -= other.to_f
      self
    end

    def *(other)
      @value *= other.to_f
      self
    end

    def /(other)
      @value /= other.to_f
      self
    end

    def %(other)
      n = other.to_f
      f = @value % n
      f = -f if @value < 0
      f = -f if n < 0
      @value = f
      self
    end

    def -@
      @value = -@value
      self
    end

    def floor
      @value = @value.floor.to_f
      self
    end

    def ceil
      @value = @value.ceil.to_f
      self
    end

    def round
      f = @value
      unless f.nan? or f.infinite? then
        if f >= 0.0 then
          @value = f.round.to_f
        elsif f - f.truncate >= -0.5 then
          @value = f.ceil.to_f
        else
          @value = f.floor.to_f
        end
      end
      self
    end

  end




  class XPathString

    include XPathObject

    def initialize(str)
      raise ::TypeError, "must be a String" unless str.is_a? String
      @value = str
    end

    def to_str
      @value
    end

    def to_f
      if /\A\s*(-?\d+\.?\d*)(?:\s|\z)/ =~ @value then
        $1.to_f
      else
        0.0 / 0.0  # NaN
      end
    end

    def true?
      not @value.empty?
    end

    def to_ruby
      to_str
    end

    def to_string(context)
      self
    end


    def concat(s)
      @value = @value + s
      self
    end

    def start_with?(s)
      /\A#{Regexp.quote(s)}/ =~ @value
    end

    def contain?(s)
      /#{Regexp.quote(s)}/ =~ @value
    end

    def substring_before(s)
      if /#{Regexp.quote(s)}/ =~ @value then
        @value = $`
      else
        @value = ''
      end
      self
    end

    def substring_after(s)
      if /#{Regexp.quote(s)}/ =~ @value then
        @value = $'
      else
        @value = ''
      end
      self
    end

    def substring(start, len)
      start = start.round.to_f
      if start.infinite? or start.nan? then
        @value = ''
      elsif len then
        len = len.round.to_f
        maxlen = start + len
        len = maxlen - 1.0 if len >= maxlen
        if start <= 1.0 then
          start = 0
        else
          start = start.to_i - 1
        end
        if len.nan? or len < 1.0 then
          @value = ''
        elsif len.infinite? then
          # @value = @value[start..-1]
          /\A[\W\w]{0,#{start}}/ =~ @value
          @value = $'
        else
          # @value = @value[start, len.to_i]
          /\A[\W\w]{0,#{start}}([\W\w]{0,#{len.to_i}})/ =~ @value
          @value = $1
        end
      elsif start > 1.0 then
        # @value = @value[(start-1)..-1]
        /\A[\W\w]{0,#{start.to_i-1}}/ =~ @value
        @value = $'
      end
      raise "BUG" unless @value
      self
    end

    def size
      @value.gsub(/[^\Wa-zA-Z_\d]/, ' ').size
    end

    def normalize_space
      @value = @value.strip
      @value.gsub!(/\s+/, ' ')
      self
    end

    def translate(from, to)
      to = to.split(//)
      h = {}
      from.split(//).each_with_index { |i,n|
        h[i] = to[n] unless h.key? i
      }
      @value = @value.gsub(/[#{Regexp.quote(h.keys.join)}]/) { |s| h[s] }
      self
    end

    def replace(str)
      @value = str
      self
    end

  end




---- footer ----

  #
  #   Client            NodeVisitor        a NodeAdapter        a Node
  #     |                    |                   |                 |
  #    |=|                   |                   |                 |
  #    | |--{visit(node)}-->|=|                  |                 |
  #    | |                  | |---{accept(self)}----------------->|=|
  #    | |                  |=|                  |                | |
  #    | |                   |                   |                | |
  #    | |                  |=|<------------------{on_**(self)}---|=|
  #    | |                  | |                  |                 |
  #    | |                  | |--{wrap(node)}-->|=|                |
  #    | |                  | |                 | |                |
  #    | |                  | |                 |=|                |
  #    | |<--[NodeAdapter]--|=|                  |                 |
  #    | |                   |                   |                 |
  #    | |-----{request}----------------------->|=|                |
  #    | |                   |                  | |--{request}--->|=|
  #    | |                   |                  | |               | |
  #    | |                   |                  | |<-----[Data]---|=|
  #    | |<--------------------------[Data]-----|=|                |
  #    | |                   |                   |                 |
  #    |=|                   |                   |                 |
  #     |                    |                   |                 |
  #


  class TransparentNodeVisitor

    def visit(node)
      node
    end

  end


  class NullNodeAdapter

    def node
      self
    end

    def root
      nil
    end

    def parent
      nil
    end

    def children
      []
    end

    def each_following_siblings
    end

    def each_preceding_siblings
    end

    def attributes
      []
    end

    def namespaces
      []
    end

    def index
      0
    end

    def node_type
      nil
    end

    def name_localpart
      nil
    end

    def qualified_name
      name_localpart
    end

    def namespace_uri
      nil
    end

    def string_value
      ''
    end

    def lang
      nil
    end

    def select_id(*ids)
      raise XPath::Error, "selection by ID is not supported"
    end

  end




  class AxisIterator

    def reverse_order?
      false
    end

  end


  class ReverseAxisIterator < AxisIterator

    def reverse_order?
      true
    end

  end


  class SelfIterator < AxisIterator

    def each(node, visitor)
      yield visitor.visit(node)
    end

  end


  class ChildIterator < AxisIterator

    def each(node, visitor, &block)
      visitor.visit(node).children.each { |i| yield visitor.visit(i) }
    end

  end


  class ParentIterator < AxisIterator

    def each(node, visitor)
      parent = visitor.visit(node).parent
      yield visitor.visit(parent) if parent
    end

  end


  class AncestorIterator < ReverseAxisIterator

    def each(node, visitor)
      node = visitor.visit(node).parent
      while node
        i = visitor.visit(node)
        parent = i.parent
        yield i
        node = parent
      end
    end

  end


  class AncestorOrSelfIterator < AncestorIterator

    def each(node, visitor)
      yield visitor.visit(node)
      super
    end

  end


  class DescendantIterator < AxisIterator

    def each(node, visitor)
      stack = visitor.visit(node).children.reverse
      while node = stack.pop
        i = visitor.visit(node)
        stack.concat i.children.reverse
        yield i
      end
    end

  end


  class DescendantOrSelfIterator < DescendantIterator

    def each(node, visitor)
      yield visitor.visit(node)
      super
    end

  end


  class FollowingSiblingIterator < AxisIterator

    def each(node, visitor)
      visitor.visit(node).each_following_siblings { |i|
        yield visitor.visit(i)
      }
    end

  end


  class PrecedingSiblingIterator < ReverseAxisIterator

    def each(node, visitor)
      visitor.visit(node).each_preceding_siblings { |i|
        yield visitor.visit(i)
      }
    end

  end


  class FollowingIterator < DescendantOrSelfIterator

    def each(node, visitor)
      while parent = (a = visitor.visit(node)).parent
        a.each_following_siblings { |i| super i, visitor }
        node = parent
      end
    end

  end


  class PrecedingIterator < ReverseAxisIterator

    def each(node, visitor)
      while parent = (adaptor = visitor.visit(node)).parent
        adaptor.each_preceding_siblings { |i|
          stack = visitor.visit(i).children.dup
          while node = stack.pop
            a = visitor.visit(node)
            stack.concat a.children
            yield a
          end
          yield visitor.visit(i)
        }
        node = parent
      end
    end

  end


  class AttributeIterator < AxisIterator

    def each(node, visitor)
      visitor.visit(node).attributes.each { |i| yield visitor.visit(i) }
    end

  end


  class NamespaceIterator < AxisIterator

    def each(node, visitor)
      visitor.visit(node).namespaces.each { |i| yield visitor.visit(i) }
    end

  end




  class XPathNodeSet

    class LocationStep < XPathNodeSet

      def initialize(context)
        @context = context
        @visitor = context.visitor
        @nodes = []
      end

      def set_iterator(iterator)
        @iterator = iterator
      end

      def reuse(node)
        @node = node
        @nodes.clear
      end

      def select
        @iterator.each(@node, @visitor) { |i|
          node = i.node
          @nodes.push node if yield(i)
        }
        self
      end

      def select_all
        @iterator.each(@node, @visitor) { |i| @nodes.push i.node }
        self
      end

    end


    include XPathObject

    def initialize(context, *nodes)
      @context = context.dup
      @visitor = context.visitor
      nodes.sort! { |a,b| compare_position a, b }
      @nodes = nodes
    end

    attr_reader :nodes
    protected :nodes


    def to_str
      if @nodes.empty? then
        ''
      else
        @visitor.visit(@nodes[0]).string_value
      end
    end

    def to_f
      to_string(@context).to_f
    end

    def true?
      not @nodes.empty?
    end

    def to_ruby
      @nodes
    end


    def self.def_comparison_operator(*ops)
      ops.each { |op|
        module_eval <<_, __FILE__, __LINE__ + 1
        def #{op}(other)
          if other.is_a? XPathBoolean then
            other #{op} self.to_boolean
          else
            visitor = @visitor
            str = @context.make_string('')
            ret = false
            @nodes.each { |node|
              str.replace visitor.visit(node).string_value
              break if ret = (other #{op} str)
            }
            ret
          end
        end
_
      }
    end

    def_comparison_operator '==', '<', '>', '<=', '>='

    class << self
      undef def_comparison_operator
    end

    def **(other)
      super unless other.is_a? XPathNodeSet
      merge other.nodes
      self
    end


    def count
      @nodes.size
    end

    def first
      @nodes[0]
    end

    def each(&block)
      @nodes.each(&block)
    end


    def funcall(name)   # for XPointer
      raise "BUG" unless block_given?
      func = ('f_' + name.tr('-', '_')).intern
      super unless respond_to? func, true
      size = @nodes.size
      pos = 1
      c = @context.dup
      begin
        @nodes.collect! { |node|
          c.reuse node, pos, size
          pos += 1
          args = yield(c)
          send(func, node, *args)
        }
      rescue Object::ArgumentError
        if $@[1] == "#{__FILE__}:#{__LINE__-3}:in `send'" then
          raise XPath::ArgumentError, "#{$!} for `#{name}'"
        end
        raise
      end
      self
    end


    private

    def compare_position(node1, node2)
      visitor = @visitor
      ancestors1 = []
      ancestors2 = []
      p1 = visitor.visit(node1).parent
      while p1
        ancestors1.push node1
        p1 = visitor.visit(node1 = p1).parent
      end
      p2 = visitor.visit(node2).parent
      while p2
        ancestors2.push node2
        p2 = visitor.visit(node2 = p2).parent
      end
      unless node1 == node2 then
        raise XPath::Error, "can't compare the positions of given two nodes"
      end
      n = -1
      ancestors1.reverse_each { |node1|
        node2 = ancestors2[n]
        unless node1 == node2 then
          break unless node2
          return visitor.visit(node1).index - visitor.visit(node2).index
        end
        n -= 1
      }
      ancestors1.size - ancestors2.size
    end


    def merge(other)
      if @nodes.empty? or other.empty? then
        @nodes.concat other
      elsif (n = compare_position(@nodes.last, other.first)) <= 0 then
        @nodes.pop if n == 0
        @nodes.concat other
      elsif (n = compare_position(other.last, @nodes.first)) <= 0 then
        other.pop if n == 0
        @nodes = other.concat(@nodes)
      else
        newnodes = []
        nodes = @nodes
        until nodes.empty? or other.empty?
          n = compare_position(nodes.last, other.last)
          if n > 0 then
            newnodes.push nodes.pop
          elsif n < 0 then
            newnodes.push other.pop
          else
            newnodes.push nodes.pop
            other.pop
          end
        end
        newnodes.reverse!
        @nodes.concat(other).concat(newnodes)
      end
    end


    IteratorForAxis = {
      :self               => SelfIterator.new,
      :child              => ChildIterator.new,
      :parent             => ParentIterator.new,
      :ancestor           => AncestorIterator.new,
      :ancestor_or_self   => AncestorOrSelfIterator.new,
      :descendant         => DescendantIterator.new,
      :descendant_or_self => DescendantOrSelfIterator.new,
      :following          => FollowingIterator.new,
      :preceding          => PrecedingIterator.new,
      :following_sibling  => FollowingSiblingIterator.new,
      :preceding_sibling  => PrecedingSiblingIterator.new,
      :attribute          => AttributeIterator.new,
      :namespace          => NamespaceIterator.new,
    }

    def get_iterator(axis)
      ret = IteratorForAxis[axis]
      unless ret then
        raise XPath::NameError, "invalid axis `#{axis.id2name.tr('_','-')}'"
      end
      ret
    end

    def make_location_step
      if defined? @__lstep__ then
        @__lstep__
      else
        @__lstep__ = LocationStep.new(@context)
      end
    end


    public

    def step(axis)
      iterator = get_iterator(axis)
      lstep = make_location_step
      lstep.set_iterator iterator
      oldnodes = @nodes
      @nodes = []
      oldnodes.each { |node|
        lstep.reuse node
        nodes = yield(lstep).nodes
        nodes.reverse! if iterator.reverse_order?
        merge nodes
      }
      self
    end


    def select_all(axis)
      iterator = get_iterator(axis)
      visitor = @visitor
      oldnodes = @nodes
      @nodes = []
      oldnodes.each { |start|
        nodes = []
        iterator.each(start, visitor) { |i| nodes.push i.node }
        nodes.reverse! if iterator.reverse_order?
        merge nodes
      }
      self
    end


    def predicate
      context = @context
      size = @nodes.size
      pos = 1
      result = nil
      newnodes = @nodes.reject { |node|
        context.reuse node, pos, size
        pos += 1
        result = yield(context)
        break if result.is_a? Numeric
        not result
      }
      if result.is_a? Numeric then
        at result
      else
        @nodes = newnodes
      end
      self
    end


    def at(pos)
      n = pos.to_i
      if n != pos or n <= 0 then
        node = nil
      else
        node = @nodes[n - 1]
      end
      @nodes.clear
      @nodes.push node if node
      self
    end

  end



  class Context

    def initialize(node, namespace = nil, variable = nil, visitor = nil)
      visitor = TransparentNodeVisitor.new unless visitor
      @visitor = visitor
      @node = node
      @context_position = 1
      @context_size = 1
      @variables = variable
      @namespaces = namespace || {}
    end

    attr_reader :visitor, :node, :context_position, :context_size

    def reuse(node, pos = 1, size = 1)
      @variables = nil
      @node, @context_position, @context_size = node, pos, size
    end


    def get_variable(name)
      value = @variables && @variables[name]  # value should be a XPathObjcect.
      raise XPath::NameError, "undefined variable `#{name}'" unless value
      value
    end


    PredefinedNamespace = {
      'xml' => 'http://www.w3.org/XML/1998/namespace',
    }

    def get_namespace(prefix)
      ret = @namespaces[prefix] || PredefinedNamespace[prefix]
      raise XPath::Error, "undeclared namespace `#{prefix}'" unless ret
      ret
    end


    def make_string(str)
      XPathString.new str
    end

    def make_number(num)
      XPathNumber.new num
    end

    def make_boolean(f)
      if f then
        XPathTrue
      else
        XPathFalse
      end
    end

    def make_nodeset(*nodes)
      XPathNodeSet.new(self, *nodes)
    end


    def to_nodeset
      make_nodeset @node
    end

    def root_nodeset
      make_nodeset @visitor.visit(@node).root
    end


    def funcall(name, *args)
      begin
        send('f_' + name.tr('-', '_'), *args)
      rescue Object::NameError
        if $@[0] == "#{__FILE__}:#{__LINE__-2}:in `send'" then
          raise XPath::NameError, "undefined function `#{name}'"
        end
        raise
      rescue Object::ArgumentError
        if $@[1] == "#{__FILE__}:#{__LINE__-7}:in `send'" then
          raise XPath::ArgumentError, "#{$!} for `#{name}'"
        end
        raise
      end
    end


    private

    def must(type, *args)
      args.each { |i|
        unless i.is_a? type then
          s = type.name.sub(/\A.*::(?:XPath)?(?=[^:]+\z)/, '')
          raise XPath::TypeError, "argument must be #{s}"
        end
      }
    end

    def must_be_nodeset(*args)
      must XPathNodeSet, *args
    end


    def f_last
      make_number @context_size.to_f
    end

    def f_position
      make_number @context_position.to_f
    end

    def f_count(nodeset)
      must_be_nodeset nodeset
      make_number nodeset.count.to_f
    end

    def f_id(obj)
      unless obj.is_a? XPathNodeSet then
        ids = obj.to_str.strip.split(/\s+/)
      else
        ids = []
        obj.each { |node| ids.push @visitor.visit(node).string_value }
      end
      root = @visitor.visit(@node).root
      make_nodeset(*@visitor.visit(root).select_id(*ids))
    end

    def f_local_name(nodeset = nil)
      unless nodeset then
        n = @node
      else
        must_be_nodeset nodeset
        n = nodeset.first
      end
      n = @visitor.visit(n) if n
      n = n.name_localpart if n
      n = '' unless n
      make_string n
    end

    def f_namespace_uri(nodeset = nil)
      unless nodeset then
        n = @node
      else
        must_be_nodeset nodeset
        n = nodeset.first
      end
      n = @visitor.visit(n) if n
      n = n.namespace_uri if n
      n = '' unless n
      make_string n
    end

    def f_name(nodeset = nil)
      unless nodeset then
        n = @node
      else
        must_be_nodeset nodeset
        n = nodeset.first
      end
      n = @visitor.visit(n) if n
      n = n.qualified_name if n
      n = '' unless n
      make_string n
    end


    def f_string(obj = nil)
      obj = to_nodeset unless obj
      obj.to_string self
    end

    def f_concat(str, str2, *strs)
      s = str2.to_str.dup
      strs.each { |i| s << i.to_str }
      str.to_string(self).concat(s)
    end

    def f_starts_with(str, sub)
      make_boolean str.to_string(self).start_with?(sub.to_str)
    end

    def f_contains(str, sub)
      make_boolean str.to_string(self).contain?(sub.to_str)
    end

    def f_substring_before(str, sub)
      str.to_string(self).substring_before sub.to_str
    end

    def f_substring_after(str, sub)
      str.to_string(self).substring_after sub.to_str
    end

    def f_substring(str, start, len = nil)
      len = len.to_number(self) if len
      str.to_string(self).substring start.to_number(self), len
    end

    def f_string_length(str = nil)
      if str then
        str = str.to_string(self)
      else
        str = make_string(@node.string_value)
      end
      make_number str.size.to_f
    end

    def f_normalize_space(str = nil)
      if str then
        str = str.to_string(self)
      else
        str = make_string(@node.string_value)
      end
      str.normalize_space
    end

    def f_translate(str, from, to)
      str.to_string(self).translate from.to_str, to.to_str
    end


    def f_boolean(obj)
      obj.to_boolean self
    end

    def f_not(bool)
      make_boolean(!bool.true?)
    end

    def f_true
      make_boolean true
    end

    def f_false
      make_boolean false
    end

    def f_lang(str)
      lang = @visitor.visit(@node).lang
      make_boolean(lang && /\A#{Regexp.quote(str.to_str)}(?:-|\z)/i =~ lang)
    end


    def f_number(obj = nil)
      obj = to_nodeset unless obj
      obj.to_number self
    end

    def f_sum(nodeset)
      must_be_nodeset nodeset
      sum = 0.0
      nodeset.each { |node|
        sum += make_string(@visitor.visit(node).string_value).to_f
      }
      make_number sum
    end

    def f_floor(num)
      num.to_number(self).floor
    end

    def f_ceiling(num)
      num.to_number(self).ceil
    end

    def f_round(num)
      num.to_number(self).round
    end

  end


end