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
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
45711
45712
45713
45714
45715
45716
45717
45718
45719
45720
45721
45722
45723
45724
45725
45726
45727
45728
45729
45730
45731
45732
45733
45734
45735
45736
45737
45738
45739
45740
45741
45742
45743
45744
45745
45746
45747
45748
45749
45750
45751
45752
45753
45754
45755
45756
45757
45758
45759
45760
45761
45762
45763
45764
45765
45766
45767
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
45805
45806
45807
45808
45809
45810
45811
45812
45813
45814
45815
45816
45817
45818
45819
45820
45821
45822
45823
45824
45825
45826
45827
45828
45829
45830
45831
45832
45833
45834
45835
45836
45837
45838
45839
45840
45841
45842
45843
45844
45845
45846
45847
45848
45849
45850
45851
45852
45853
45854
45855
45856
45857
45858
45859
45860
45861
45862
45863
45864
45865
45866
45867
45868
45869
45870
45871
45872
45873
45874
45875
45876
45877
45878
45879
45880
45881
45882
45883
45884
45885
45886
45887
45888
45889
45890
45891
45892
45893
45894
45895
45896
45897
45898
45899
45900
45901
45902
45903
45904
45905
45906
45907
45908
45909
45910
45911
45912
45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933
45934
45935
45936
45937
45938
45939
45940
45941
45942
45943
45944
45945
45946
45947
45948
45949
45950
45951
45952
45953
45954
45955
45956
45957
45958
45959
45960
45961
45962
45963
45964
45965
45966
45967
45968
45969
45970
45971
45972
45973
45974
45975
45976
45977
45978
45979
45980
45981
45982
45983
45984
45985
45986
45987
45988
45989
45990
45991
45992
45993
45994
45995
45996
45997
45998
45999
46000
46001
46002
46003
46004
46005
46006
46007
46008
46009
46010
46011
46012
46013
46014
46015
46016
46017
46018
46019
46020
46021
46022
46023
46024
46025
46026
46027
46028
46029
46030
46031
46032
46033
46034
46035
46036
46037
46038
46039
46040
46041
46042
46043
46044
46045
46046
46047
46048
46049
46050
46051
46052
46053
46054
46055
46056
46057
46058
46059
46060
46061
46062
46063
46064
46065
46066
46067
46068
46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082
46083
46084
46085
46086
46087
46088
46089
46090
46091
46092
46093
46094
46095
46096
46097
46098
46099
46100
46101
46102
46103
46104
46105
46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126
46127
46128
46129
46130
46131
46132
46133
46134
46135
46136
46137
46138
46139
46140
46141
46142
46143
46144
46145
46146
46147
46148
46149
46150
46151
46152
46153
46154
46155
46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173
46174
46175
46176
46177
46178
46179
46180
46181
46182
46183
46184
46185
46186
46187
46188
46189
46190
46191
46192
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203
46204
46205
46206
46207
46208
46209
46210
46211
46212
46213
46214
46215
46216
46217
46218
46219
46220
46221
46222
46223
46224
46225
46226
46227
46228
46229
46230
46231
46232
46233
46234
46235
46236
46237
46238
46239
46240
46241
46242
46243
46244
46245
46246
46247
46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260
46261
46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275
46276
46277
46278
46279
46280
46281
46282
46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299
46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317
46318
46319
46320
46321
46322
46323
46324
46325
46326
46327
46328
46329
46330
46331
46332
46333
46334
46335
46336
46337
46338
46339
46340
46341
46342
46343
46344
46345
46346
46347
46348
46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366
46367
46368
46369
46370
46371
46372
46373
46374
46375
46376
46377
46378
46379
46380
46381
46382
46383
46384
46385
46386
46387
46388
46389
46390
46391
46392
46393
46394
46395
46396
46397
46398
46399
46400
46401
46402
46403
46404
46405
46406
46407
46408
46409
46410
46411
46412
46413
46414
46415
46416
46417
46418
46419
46420
46421
46422
46423
46424
46425
46426
46427
46428
46429
46430
46431
46432
46433
46434
46435
46436
46437
46438
46439
46440
46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453
46454
46455
46456
46457
46458
46459
46460
46461
46462
46463
46464
46465
46466
46467
46468
46469
46470
46471
46472
46473
46474
46475
46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492
46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510
46511
46512
46513
46514
46515
46516
46517
46518
46519
46520
46521
46522
46523
46524
46525
46526
46527
46528
46529
46530
46531
46532
46533
46534
46535
46536
46537
46538
46539
46540
46541
46542
46543
46544
46545
46546
46547
46548
46549
46550
46551
46552
46553
46554
46555
46556
46557
46558
46559
46560
46561
46562
46563
46564
46565
46566
46567
46568
46569
46570
46571
46572
46573
46574
46575
46576
46577
46578
46579
46580
46581
46582
46583
46584
46585
46586
46587
46588
46589
46590
46591
46592
46593
46594
46595
46596
46597
46598
46599
46600
46601
46602
46603
46604
46605
46606
46607
46608
46609
46610
46611
46612
46613
46614
46615
46616
46617
46618
46619
46620
46621
46622
46623
46624
46625
46626
46627
46628
46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
46666
46667
46668
46669
46670
46671
46672
46673
46674
46675
46676
46677
46678
46679
46680
46681
46682
46683
46684
46685
46686
46687
46688
46689
46690
46691
46692
46693
46694
46695
46696
46697
46698
46699
46700
46701
46702
46703
46704
46705
46706
46707
46708
46709
46710
46711
46712
46713
46714
46715
46716
46717
46718
46719
46720
46721
46722
46723
46724
46725
46726
46727
46728
46729
46730
46731
46732
46733
46734
46735
46736
46737
46738
46739
46740
46741
46742
46743
46744
46745
46746
46747
46748
46749
46750
46751
46752
46753
46754
46755
46756
46757
46758
46759
46760
46761
46762
46763
46764
46765
46766
46767
46768
46769
46770
46771
46772
46773
46774
46775
46776
46777
46778
46779
46780
46781
46782
46783
46784
46785
46786
46787
46788
46789
46790
46791
46792
46793
46794
46795
46796
46797
46798
46799
46800
46801
46802
46803
46804
46805
46806
46807
46808
46809
46810
46811
46812
46813
46814
46815
46816
46817
46818
46819
46820
46821
46822
46823
46824
46825
46826
46827
46828
46829
46830
46831
46832
46833
46834
46835
46836
46837
46838
46839
46840
46841
46842
46843
46844
46845
46846
46847
46848
46849
46850
46851
46852
46853
46854
46855
46856
46857
46858
46859
46860
46861
46862
46863
46864
46865
46866
46867
46868
46869
46870
46871
46872
46873
46874
46875
46876
46877
46878
46879
46880
46881
46882
46883
46884
46885
46886
46887
46888
46889
46890
46891
46892
46893
46894
46895
46896
46897
46898
46899
46900
46901
46902
46903
46904
46905
46906
46907
46908
46909
46910
46911
46912
46913
46914
46915
46916
46917
46918
46919
46920
46921
46922
46923
46924
46925
46926
46927
46928
46929
46930
46931
46932
46933
46934
46935
46936
46937
46938
46939
46940
46941
46942
46943
46944
46945
46946
46947
46948
46949
46950
46951
46952
46953
46954
46955
46956
46957
46958
46959
46960
46961
46962
46963
46964
46965
46966
46967
46968
46969
46970
46971
46972
46973
46974
46975
46976
46977
46978
46979
46980
46981
46982
46983
46984
46985
46986
46987
46988
46989
46990
46991
46992
46993
46994
46995
46996
46997
46998
46999
47000
47001
47002
47003
47004
47005
47006
47007
47008
47009
47010
47011
47012
47013
47014
47015
47016
47017
47018
47019
47020
47021
47022
47023
47024
47025
47026
47027
47028
47029
47030
47031
47032
47033
47034
47035
47036
47037
47038
47039
47040
47041
47042
47043
47044
47045
47046
47047
47048
47049
47050
47051
47052
47053
47054
47055
47056
47057
47058
47059
47060
47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
47072
47073
47074
47075
47076
47077
47078
47079
47080
47081
47082
47083
47084
47085
47086
47087
47088
47089
47090
47091
47092
47093
47094
47095
47096
47097
47098
47099
47100
47101
47102
47103
47104
47105
47106
47107
47108
47109
47110
47111
47112
47113
47114
47115
47116
47117
47118
47119
47120
47121
47122
47123
47124
47125
47126
47127
47128
47129
47130
47131
47132
47133
47134
47135
47136
47137
47138
47139
47140
47141
47142
47143
47144
47145
47146
47147
47148
47149
47150
47151
47152
47153
47154
47155
47156
47157
47158
47159
47160
47161
47162
47163
47164
47165
47166
47167
47168
47169
47170
47171
47172
47173
47174
47175
47176
47177
47178
47179
47180
47181
47182
47183
47184
47185
47186
47187
47188
47189
47190
47191
47192
47193
47194
47195
47196
47197
47198
47199
47200
47201
47202
47203
47204
47205
47206
47207
47208
47209
47210
47211
47212
47213
47214
47215
47216
47217
47218
47219
47220
47221
47222
47223
47224
47225
47226
47227
47228
47229
47230
47231
47232
47233
47234
47235
47236
47237
47238
47239
47240
47241
47242
47243
47244
47245
47246
47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266
47267
47268
47269
47270
47271
47272
47273
47274
47275
47276
47277
47278
47279
47280
47281
47282
47283
47284
47285
47286
47287
47288
47289
47290
47291
47292
47293
47294
47295
47296
47297
47298
47299
47300
47301
47302
47303
47304
47305
47306
47307
47308
47309
47310
47311
47312
47313
47314
47315
47316
47317
47318
47319
47320
47321
47322
47323
47324
47325
47326
47327
47328
47329
47330
47331
47332
47333
47334
47335
47336
47337
47338
47339
47340
47341
47342
47343
47344
47345
47346
47347
47348
47349
47350
47351
47352
47353
47354
47355
47356
47357
47358
47359
47360
47361
47362
47363
47364
47365
47366
47367
47368
47369
47370
47371
47372
47373
47374
47375
47376
47377
47378
47379
47380
47381
47382
47383
47384
47385
47386
47387
47388
47389
47390
47391
47392
47393
47394
47395
47396
47397
47398
47399
47400
47401
47402
47403
47404
47405
47406
47407
47408
47409
47410
47411
47412
47413
47414
47415
47416
47417
47418
47419
47420
47421
47422
47423
47424
47425
47426
47427
47428
47429
47430
47431
47432
47433
47434
47435
47436
47437
47438
47439
47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459
47460
47461
47462
47463
47464
47465
47466
47467
47468
47469
47470
47471
47472
47473
47474
47475
47476
47477
47478
47479
47480
47481
47482
47483
47484
47485
47486
47487
47488
47489
47490
47491
47492
47493
47494
47495
47496
47497
47498
47499
47500
47501
47502
47503
47504
47505
47506
47507
47508
47509
47510
47511
47512
47513
47514
47515
47516
47517
47518
47519
47520
47521
47522
47523
47524
47525
47526
47527
47528
47529
47530
47531
47532
47533
47534
47535
47536
47537
47538
47539
47540
47541
47542
47543
47544
47545
47546
47547
47548
47549
47550
47551
47552
47553
47554
47555
47556
47557
47558
47559
47560
47561
47562
47563
47564
47565
47566
47567
47568
47569
47570
47571
47572
47573
47574
47575
47576
47577
47578
47579
47580
47581
47582
47583
47584
47585
47586
47587
47588
47589
47590
47591
47592
47593
47594
47595
47596
47597
47598
47599
47600
47601
47602
47603
47604
47605
47606
47607
47608
47609
47610
47611
47612
47613
47614
47615
47616
47617
47618
47619
47620
47621
47622
47623
47624
47625
47626
47627
47628
47629
47630
47631
47632
47633
47634
47635
47636
47637
47638
47639
47640
47641
47642
47643
47644
47645
47646
47647
47648
47649
47650
47651
47652
47653
47654
47655
47656
47657
47658
47659
47660
47661
47662
47663
47664
47665
47666
47667
47668
47669
47670
47671
47672
47673
47674
47675
47676
47677
47678
47679
47680
47681
47682
47683
47684
47685
47686
47687
47688
47689
47690
47691
47692
47693
47694
47695
47696
47697
47698
47699
47700
47701
47702
47703
47704
47705
47706
47707
47708
47709
47710
47711
47712
47713
47714
47715
47716
47717
47718
47719
47720
47721
47722
47723
47724
47725
47726
47727
47728
47729
47730
47731
47732
47733
47734
47735
47736
47737
47738
47739
47740
47741
47742
47743
47744
47745
47746
47747
47748
47749
47750
47751
47752
47753
47754
47755
47756
47757
47758
47759
47760
47761
47762
47763
47764
47765
47766
47767
47768
47769
47770
47771
47772
47773
47774
47775
47776
47777
47778
47779
47780
47781
47782
47783
47784
47785
47786
47787
47788
47789
47790
47791
47792
47793
47794
47795
47796
47797
47798
47799
47800
47801
47802
47803
47804
47805
47806
47807
47808
47809
47810
47811
47812
47813
47814
47815
47816
47817
47818
47819
47820
47821
47822
47823
47824
47825
47826
47827
47828
47829
47830
47831
47832
47833
47834
47835
47836
47837
47838
47839
47840
47841
47842
47843
47844
47845
47846
47847
47848
47849
47850
47851
47852
47853
47854
47855
47856
47857
47858
47859
47860
47861
47862
47863
47864
47865
47866
47867
47868
47869
47870
47871
47872
47873
47874
47875
47876
47877
47878
47879
47880
47881
47882
47883
47884
47885
47886
47887
47888
47889
47890
47891
47892
47893
47894
47895
47896
47897
47898
47899
47900
47901
47902
47903
47904
47905
47906
47907
47908
47909
47910
47911
47912
47913
47914
47915
47916
47917
47918
47919
47920
47921
47922
47923
47924
47925
47926
47927
47928
47929
47930
47931
47932
47933
47934
47935
47936
47937
47938
47939
47940
47941
47942
47943
47944
47945
47946
47947
47948
47949
47950
47951
47952
47953
47954
47955
47956
47957
47958
47959
47960
47961
47962
47963
47964
47965
47966
47967
47968
47969
47970
47971
47972
47973
47974
47975
47976
47977
47978
47979
47980
47981
47982
47983
47984
47985
47986
47987
47988
47989
47990
47991
47992
47993
47994
47995
47996
47997
47998
47999
48000
48001
48002
48003
48004
48005
48006
48007
48008
48009
48010
48011
48012
48013
48014
48015
48016
48017
48018
48019
48020
48021
48022
48023
48024
48025
48026
48027
48028
48029
48030
48031
48032
48033
48034
48035
48036
48037
48038
48039
48040
48041
48042
48043
48044
48045
48046
48047
48048
48049
48050
48051
48052
48053
48054
48055
48056
48057
48058
48059
48060
48061
48062
48063
48064
48065
48066
48067
48068
48069
48070
48071
48072
48073
48074
48075
48076
48077
48078
48079
48080
48081
48082
48083
48084
48085
48086
48087
48088
48089
48090
48091
48092
48093
48094
48095
48096
48097
48098
48099
48100
48101
48102
48103
48104
48105
48106
48107
48108
48109
48110
48111
48112
48113
48114
48115
48116
48117
48118
48119
48120
48121
48122
48123
48124
48125
48126
48127
48128
48129
48130
48131
48132
48133
48134
48135
48136
48137
48138
48139
48140
48141
48142
48143
48144
48145
48146
48147
48148
48149
48150
48151
48152
48153
48154
48155
48156
48157
48158
48159
48160
48161
48162
48163
48164
48165
48166
48167
48168
48169
48170
48171
48172
48173
48174
48175
48176
48177
48178
48179
48180
48181
48182
48183
48184
48185
48186
48187
48188
48189
48190
48191
48192
48193
48194
48195
48196
48197
48198
48199
48200
48201
48202
48203
48204
48205
48206
48207
48208
48209
48210
48211
48212
48213
48214
48215
48216
48217
48218
48219
48220
48221
48222
48223
48224
48225
48226
48227
48228
48229
48230
48231
48232
48233
48234
48235
48236
48237
48238
48239
48240
48241
48242
48243
48244
48245
48246
48247
48248
48249
48250
48251
48252
48253
48254
48255
48256
48257
48258
48259
48260
48261
48262
48263
48264
48265
48266
48267
48268
48269
48270
48271
48272
48273
48274
48275
48276
48277
48278
48279
48280
48281
48282
48283
48284
48285
48286
48287
48288
48289
48290
48291
48292
48293
48294
48295
48296
48297
48298
48299
48300
48301
48302
48303
48304
48305
48306
48307
48308
48309
48310
48311
48312
48313
48314
48315
48316
48317
48318
48319
48320
48321
48322
48323
48324
48325
48326
48327
48328
48329
48330
48331
48332
48333
48334
48335
48336
48337
48338
48339
48340
48341
48342
48343
48344
48345
48346
48347
48348
48349
48350
48351
48352
48353
48354
48355
48356
48357
48358
48359
48360
48361
48362
48363
48364
48365
48366
48367
48368
48369
48370
48371
48372
48373
48374
48375
48376
48377
48378
48379
48380
48381
48382
48383
48384
48385
48386
48387
48388
48389
48390
48391
48392
48393
48394
48395
48396
48397
48398
48399
48400
48401
48402
48403
48404
48405
48406
48407
48408
48409
48410
48411
48412
48413
48414
48415
48416
48417
48418
48419
48420
48421
48422
48423
48424
48425
48426
48427
48428
48429
48430
48431
48432
48433
48434
48435
48436
48437
48438
48439
48440
48441
48442
48443
48444
48445
48446
48447
48448
48449
48450
48451
48452
48453
48454
48455
48456
48457
48458
48459
48460
48461
48462
48463
48464
48465
48466
48467
48468
48469
48470
48471
48472
48473
48474
48475
48476
48477
48478
48479
48480
48481
48482
48483
48484
48485
48486
48487
48488
48489
48490
48491
48492
48493
48494
48495
48496
48497
48498
48499
48500
48501
48502
48503
48504
48505
48506
48507
48508
48509
48510
48511
48512
48513
48514
48515
48516
48517
48518
48519
48520
48521
48522
48523
48524
48525
48526
48527
48528
48529
48530
48531
48532
48533
48534
48535
48536
48537
48538
48539
48540
48541
48542
48543
48544
48545
48546
48547
48548
48549
48550
48551
48552
48553
48554
48555
48556
48557
48558
48559
48560
48561
48562
48563
48564
48565
48566
48567
48568
48569
48570
48571
48572
48573
48574
48575
48576
48577
48578
48579
48580
48581
48582
48583
48584
48585
48586
48587
48588
48589
48590
48591
48592
48593
48594
48595
48596
48597
48598
48599
48600
48601
48602
48603
48604
48605
48606
48607
48608
48609
48610
48611
48612
48613
48614
48615
48616
48617
48618
48619
48620
48621
48622
48623
48624
48625
48626
48627
48628
48629
48630
48631
48632
48633
48634
48635
48636
48637
48638
48639
48640
48641
48642
48643
48644
48645
48646
48647
48648
48649
48650
48651
48652
48653
48654
48655
48656
48657
48658
48659
48660
48661
48662
48663
48664
48665
48666
48667
48668
48669
48670
48671
48672
48673
48674
48675
48676
48677
48678
48679
48680
48681
48682
48683
48684
48685
48686
48687
48688
48689
48690
48691
48692
48693
48694
48695
48696
48697
48698
48699
48700
48701
48702
48703
48704
48705
48706
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
48722
48723
48724
48725
48726
48727
48728
48729
48730
48731
48732
48733
48734
48735
48736
48737
48738
48739
48740
48741
48742
48743
48744
48745
48746
48747
48748
48749
48750
48751
48752
48753
48754
48755
48756
48757
48758
48759
48760
48761
48762
48763
48764
48765
48766
48767
48768
48769
48770
48771
48772
48773
48774
48775
48776
48777
48778
48779
48780
48781
48782
48783
48784
48785
48786
48787
48788
48789
48790
48791
48792
48793
48794
48795
48796
48797
48798
48799
48800
48801
48802
48803
48804
48805
48806
48807
48808
48809
48810
48811
48812
48813
48814
48815
48816
48817
48818
48819
48820
48821
48822
48823
48824
48825
48826
48827
48828
48829
48830
48831
48832
48833
48834
48835
48836
48837
48838
48839
48840
48841
48842
48843
48844
48845
48846
48847
48848
48849
48850
48851
48852
48853
48854
48855
48856
48857
48858
48859
48860
48861
48862
48863
48864
48865
48866
48867
48868
48869
48870
48871
48872
48873
48874
48875
48876
48877
48878
48879
48880
48881
48882
48883
48884
48885
48886
48887
48888
48889
48890
48891
48892
48893
48894
48895
48896
48897
48898
48899
48900
48901
48902
48903
48904
48905
48906
48907
48908
48909
48910
48911
48912
48913
48914
48915
48916
48917
48918
48919
48920
48921
48922
48923
48924
48925
48926
48927
48928
48929
48930
48931
48932
48933
48934
48935
48936
48937
48938
48939
48940
48941
48942
48943
48944
48945
48946
48947
48948
48949
48950
48951
48952
48953
48954
48955
48956
48957
48958
48959
48960
48961
48962
48963
48964
48965
48966
48967
48968
48969
48970
48971
48972
48973
48974
48975
48976
48977
48978
48979
48980
48981
48982
48983
48984
48985
48986
48987
48988
48989
48990
48991
48992
48993
48994
48995
48996
48997
48998
48999
49000
49001
49002
49003
49004
49005
49006
49007
49008
49009
49010
49011
49012
49013
49014
49015
49016
49017
49018
49019
49020
49021
49022
49023
49024
49025
49026
49027
49028
49029
49030
49031
49032
49033
49034
49035
49036
49037
49038
49039
49040
49041
49042
49043
49044
49045
49046
49047
49048
49049
49050
49051
49052
49053
49054
49055
49056
49057
49058
49059
49060
49061
49062
49063
49064
49065
49066
49067
49068
49069
49070
49071
49072
49073
49074
49075
49076
49077
49078
49079
49080
49081
49082
49083
49084
49085
49086
49087
49088
49089
49090
49091
49092
49093
49094
49095
49096
49097
49098
49099
49100
49101
49102
49103
49104
49105
49106
49107
49108
49109
49110
49111
49112
49113
49114
49115
49116
49117
49118
49119
49120
49121
49122
49123
49124
49125
49126
49127
49128
49129
49130
49131
49132
49133
49134
49135
49136
49137
49138
49139
49140
49141
49142
49143
49144
49145
49146
49147
49148
49149
49150
49151
49152
49153
49154
49155
49156
49157
49158
49159
49160
49161
49162
49163
49164
49165
49166
49167
49168
49169
49170
49171
49172
49173
49174
49175
49176
49177
49178
49179
49180
49181
49182
49183
49184
49185
49186
49187
49188
49189
49190
49191
49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207
49208
49209
49210
49211
49212
49213
49214
49215
49216
49217
49218
49219
49220
49221
49222
49223
49224
49225
49226
49227
49228
49229
49230
49231
49232
49233
49234
49235
49236
49237
49238
49239
49240
49241
49242
49243
49244
49245
49246
49247
49248
49249
49250
49251
49252
49253
49254
49255
49256
49257
49258
49259
49260
49261
49262
49263
49264
49265
49266
49267
49268
49269
49270
49271
49272
49273
49274
49275
49276
49277
49278
49279
49280
49281
49282
49283
49284
49285
49286
49287
49288
49289
49290
49291
49292
49293
49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306
49307
49308
49309
49310
49311
49312
49313
49314
49315
49316
49317
49318
49319
49320
49321
49322
49323
49324
49325
49326
49327
49328
49329
49330
49331
49332
49333
49334
49335
49336
49337
49338
49339
49340
49341
49342
49343
49344
49345
49346
49347
49348
49349
49350
49351
49352
49353
49354
49355
49356
49357
49358
49359
49360
49361
49362
49363
49364
49365
49366
49367
49368
49369
49370
49371
49372
49373
49374
49375
49376
49377
49378
49379
49380
49381
49382
49383
49384
49385
49386
49387
49388
49389
49390
49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406
49407
49408
49409
49410
49411
49412
49413
49414
49415
49416
49417
49418
49419
49420
49421
49422
49423
49424
49425
49426
49427
49428
49429
49430
49431
49432
49433
49434
49435
49436
49437
49438
49439
49440
49441
49442
49443
49444
49445
49446
49447
49448
49449
49450
49451
49452
49453
49454
49455
49456
49457
49458
49459
49460
49461
49462
49463
49464
49465
49466
49467
49468
49469
49470
49471
49472
49473
49474
49475
49476
49477
49478
49479
49480
49481
49482
49483
49484
49485
49486
49487
49488
49489
49490
49491
49492
49493
49494
49495
49496
49497
49498
49499
49500
49501
49502
49503
49504
49505
49506
49507
49508
49509
49510
49511
49512
49513
49514
49515
49516
49517
49518
49519
49520
49521
49522
49523
49524
49525
49526
49527
49528
49529
49530
49531
49532
49533
49534
49535
49536
49537
49538
49539
49540
49541
49542
49543
49544
49545
49546
49547
49548
49549
49550
49551
49552
49553
49554
49555
49556
49557
49558
49559
49560
49561
49562
49563
49564
49565
49566
49567
49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
49583
49584
49585
49586
49587
49588
49589
49590
49591
49592
49593
49594
49595
49596
49597
49598
49599
49600
49601
49602
49603
49604
49605
49606
49607
49608
49609
49610
49611
49612
49613
49614
49615
49616
49617
49618
49619
49620
49621
49622
49623
49624
49625
49626
49627
49628
49629
49630
49631
49632
49633
49634
49635
49636
49637
49638
49639
49640
49641
49642
49643
49644
49645
49646
49647
49648
49649
49650
49651
49652
49653
49654
49655
49656
49657
49658
49659
49660
49661
49662
49663
49664
49665
49666
49667
49668
49669
49670
49671
49672
49673
49674
49675
49676
49677
49678
49679
49680
49681
49682
49683
49684
49685
49686
49687
49688
49689
49690
49691
49692
49693
49694
49695
49696
49697
49698
49699
49700
49701
49702
49703
49704
49705
49706
49707
49708
49709
49710
49711
49712
49713
49714
49715
49716
49717
49718
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734
49735
49736
49737
49738
49739
49740
49741
49742
49743
49744
49745
49746
49747
49748
49749
49750
49751
49752
49753
49754
49755
49756
49757
49758
49759
49760
49761
49762
49763
49764
49765
49766
49767
49768
49769
49770
49771
49772
49773
49774
49775
49776
49777
49778
49779
49780
49781
49782
49783
49784
49785
49786
49787
49788
49789
49790
49791
49792
49793
49794
49795
49796
49797
49798
49799
49800
49801
49802
49803
49804
49805
49806
49807
49808
49809
49810
49811
49812
49813
49814
49815
49816
49817
49818
49819
49820
49821
49822
49823
49824
49825
49826
49827
49828
49829
49830
49831
49832
49833
49834
49835
49836
49837
49838
49839
49840
49841
49842
49843
49844
49845
49846
49847
49848
49849
49850
49851
49852
49853
49854
49855
49856
49857
49858
49859
49860
49861
49862
49863
49864
49865
49866
49867
49868
49869
49870
49871
49872
49873
49874
49875
49876
49877
49878
49879
49880
49881
49882
49883
49884
49885
49886
49887
49888
49889
49890
49891
49892
49893
49894
49895
49896
49897
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909
49910
49911
49912
49913
49914
49915
49916
49917
49918
49919
49920
49921
49922
49923
49924
49925
49926
49927
49928
49929
49930
49931
49932
49933
49934
49935
49936
49937
49938
49939
49940
49941
49942
49943
49944
49945
49946
49947
49948
49949
49950
49951
49952
49953
49954
49955
49956
49957
49958
49959
49960
49961
49962
49963
49964
49965
49966
49967
49968
49969
49970
49971
49972
49973
49974
49975
49976
49977
49978
49979
49980
49981
49982
49983
49984
49985
49986
49987
49988
49989
49990
49991
49992
49993
49994
49995
49996
49997
49998
49999
50000
50001
50002
50003
50004
50005
50006
50007
50008
50009
50010
50011
50012
50013
50014
50015
50016
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035
50036
50037
50038
50039
50040
50041
50042
50043
50044
50045
50046
50047
50048
50049
50050
50051
50052
50053
50054
50055
50056
50057
50058
50059
50060
50061
50062
50063
50064
50065
50066
50067
50068
50069
50070
50071
50072
50073
50074
50075
50076
50077
50078
50079
50080
50081
50082
50083
50084
50085
50086
50087
50088
50089
50090
50091
50092
50093
50094
50095
50096
50097
50098
50099
50100
50101
50102
50103
50104
50105
50106
50107
50108
50109
50110
50111
50112
50113
50114
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134
50135
50136
50137
50138
50139
50140
50141
50142
50143
50144
50145
50146
50147
50148
50149
50150
50151
50152
50153
50154
50155
50156
50157
50158
50159
50160
50161
50162
50163
50164
50165
50166
50167
50168
50169
50170
50171
50172
50173
50174
50175
50176
50177
50178
50179
50180
50181
50182
50183
50184
50185
50186
50187
50188
50189
50190
50191
50192
50193
50194
50195
50196
50197
50198
50199
50200
50201
50202
50203
50204
50205
50206
50207
50208
50209
50210
50211
50212
50213
50214
50215
50216
50217
50218
50219
50220
50221
50222
50223
50224
50225
50226
50227
50228
50229
50230
50231
50232
50233
50234
50235
50236
50237
50238
50239
50240
50241
50242
50243
50244
50245
50246
50247
50248
50249
50250
50251
50252
50253
50254
50255
50256
50257
50258
50259
50260
50261
50262
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
50315
50316
50317
50318
50319
50320
50321
50322
50323
50324
50325
50326
50327
50328
50329
50330
50331
50332
50333
50334
50335
50336
50337
50338
50339
50340
50341
50342
50343
50344
50345
50346
50347
50348
50349
50350
50351
50352
50353
50354
50355
50356
50357
50358
50359
50360
50361
50362
50363
50364
50365
50366
50367
50368
50369
50370
50371
50372
50373
50374
50375
50376
50377
50378
50379
50380
50381
50382
50383
50384
50385
50386
50387
50388
50389
50390
50391
50392
50393
50394
50395
50396
50397
50398
50399
50400
50401
50402
50403
50404
50405
50406
50407
50408
50409
50410
50411
50412
50413
50414
50415
50416
50417
50418
50419
50420
50421
50422
50423
50424
50425
50426
50427
50428
50429
50430
50431
50432
50433
50434
50435
50436
50437
50438
50439
50440
50441
50442
50443
50444
50445
50446
50447
50448
50449
50450
50451
50452
50453
50454
50455
50456
50457
50458
50459
50460
50461
50462
50463
50464
50465
50466
50467
50468
50469
50470
50471
50472
50473
50474
50475
50476
50477
50478
50479
50480
50481
50482
50483
50484
50485
50486
50487
50488
50489
50490
50491
50492
50493
50494
50495
50496
50497
50498
50499
50500
50501
50502
50503
50504
50505
50506
50507
50508
50509
50510
50511
50512
50513
50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
50566
50567
50568
50569
50570
50571
50572
50573
50574
50575
50576
50577
50578
50579
50580
50581
50582
50583
50584
50585
50586
50587
50588
50589
50590
50591
50592
50593
50594
50595
50596
50597
50598
50599
50600
50601
50602
50603
50604
50605
50606
50607
50608
50609
50610
50611
50612
50613
50614
50615
50616
50617
50618
50619
50620
50621
50622
50623
50624
50625
50626
50627
50628
50629
50630
50631
50632
50633
50634
50635
50636
50637
50638
50639
50640
50641
50642
50643
50644
50645
50646
50647
50648
50649
50650
50651
50652
50653
50654
50655
50656
50657
50658
50659
50660
50661
50662
50663
50664
50665
50666
50667
50668
50669
50670
50671
50672
50673
50674
50675
50676
50677
50678
50679
50680
50681
50682
50683
50684
50685
50686
50687
50688
50689
50690
50691
50692
50693
50694
50695
50696
50697
50698
50699
50700
50701
50702
50703
50704
50705
50706
50707
50708
50709
50710
50711
50712
50713
50714
50715
50716
50717
50718
50719
50720
50721
50722
50723
50724
50725
50726
50727
50728
50729
50730
50731
50732
50733
50734
50735
50736
50737
50738
50739
50740
50741
50742
50743
50744
50745
50746
50747
50748
50749
50750
50751
50752
50753
50754
50755
50756
50757
50758
50759
50760
50761
50762
50763
50764
50765
50766
50767
50768
50769
50770
50771
50772
50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794
50795
50796
50797
50798
50799
50800
50801
50802
50803
50804
50805
50806
50807
50808
50809
50810
50811
50812
50813
50814
50815
50816
50817
50818
50819
50820
50821
50822
50823
50824
50825
50826
50827
50828
50829
50830
50831
50832
50833
50834
50835
50836
50837
50838
50839
50840
50841
50842
50843
50844
50845
50846
50847
50848
50849
50850
50851
50852
50853
50854
50855
50856
50857
50858
50859
50860
50861
50862
50863
50864
50865
50866
50867
50868
50869
50870
50871
50872
50873
50874
50875
50876
50877
50878
50879
50880
50881
50882
50883
50884
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
50896
50897
50898
50899
50900
50901
50902
50903
50904
50905
50906
50907
50908
50909
50910
50911
50912
50913
50914
50915
50916
50917
50918
50919
50920
50921
50922
50923
50924
50925
50926
50927
50928
50929
50930
50931
50932
50933
50934
50935
50936
50937
50938
50939
50940
50941
50942
50943
50944
50945
50946
50947
50948
50949
50950
50951
50952
50953
50954
50955
50956
50957
50958
50959
50960
50961
50962
50963
50964
50965
50966
50967
50968
50969
50970
50971
50972
50973
50974
50975
50976
50977
50978
50979
50980
50981
50982
50983
50984
50985
50986
50987
50988
50989
50990
50991
50992
50993
50994
50995
50996
50997
50998
50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012
51013
51014
51015
51016
51017
51018
51019
51020
51021
51022
51023
51024
51025
51026
51027
51028
51029
51030
51031
51032
51033
51034
51035
51036
51037
51038
51039
51040
51041
51042
51043
51044
51045
51046
51047
51048
51049
51050
51051
51052
51053
51054
51055
51056
51057
51058
51059
51060
51061
51062
51063
51064
51065
51066
51067
51068
51069
51070
51071
51072
51073
51074
51075
51076
51077
51078
51079
51080
51081
51082
51083
51084
51085
51086
51087
51088
51089
51090
51091
51092
51093
51094
51095
51096
51097
51098
51099
51100
51101
51102
51103
51104
51105
51106
51107
51108
51109
51110
51111
51112
51113
51114
51115
51116
51117
51118
51119
51120
51121
51122
51123
51124
51125
51126
51127
51128
51129
51130
51131
51132
51133
51134
51135
51136
51137
51138
51139
51140
51141
51142
51143
51144
51145
51146
51147
51148
51149
51150
51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173
51174
51175
51176
51177
51178
51179
51180
51181
51182
51183
51184
51185
51186
51187
51188
51189
51190
51191
51192
51193
|
package org.jruby;
public enum CompatVersion {
RUBY1_8, RUBY1_9, BOTH;
public static CompatVersion getVersionFromString(String compatString) {
if (compatString.equalsIgnoreCase("RUBY1_8")) {
return CompatVersion.RUBY1_8;
} else if (compatString.equalsIgnoreCase("RUBY1_9")) {
return CompatVersion.RUBY1_9;
} else {
return null;
}
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Damian Steer <pldms@mac.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
/**
* An almost entirely useless interface for those objects that we _really_ want
* to finalise.
*
* @author pldms
*
*/
public interface Finalizable {
public void finalize();
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
/**
* Error numbers.
* @fixme
* this interface is a big hack defining a bunch of arbitrary valor as system call error numbers
* this is actually because I need them but will probably need to be changed to something smarter
* sooner or later.
* The purpose of this class it to help implement the Errno module which in turn in needed by rubicon.
* @author Benoit Cerrina
**/
public interface IErrno
{
int EPERM = 1;
int ENOENT = 2;
int ESRCH = 3;
int EINTR = 4;
int EIO = 5;
int ENXIO = 6;
int E2BIG = 7;
int ENOEXEC = 8;
int EBADF = 9;
int ECHILD = 10;
int EDEADLK = 11;
int ENOMEM = 12;
int EACCES = 13;
int EFAULT = 14;
int ENOTBLK = 15;
int EBUSY = 16;
int EEXIST = 17;
int EXDEV = 18;
int ENODEV = 19;
int ENOTDIR = 20;
int EISDIR = 21;
int EINVAL = 22;
int ENFILE = 23;
int EMFILE = 24;
int ENOTTY = 25;
int ETXTBSY = 26;
int EFBIG = 27;
int ENOSPC = 28;
int ESPIPE = 29;
int EROFS = 30;
int EMLINK = 31;
int EPIPE = 32;
int EDOM = 33;
int ERANGE = 34;
int EWOULDBLOCK = 35;
int EAGAIN = 35;
int EINPROGRESS = 36;
int EALREADY = 37;
int ENOTSOCK = 38;
int EDESTADDRREQ = 39;
int EMSGSIZE = 40;
int EPROTOTYPE = 41;
int ENOPROTOOPT = 42;
int EPROTONOSUPPORT = 43;
int ESOCKTNOSUPPORT = 44;
int EOPNOTSUPP = 45;
int EPFNOSUPPORT = 46;
int EAFNOSUPPORT = 47;
int EADDRINUSE = 48;
int EADDRNOTAVAIL = 49;
int ENETDOWN = 50;
int ENETUNREACH = 51;
int ENETRESET = 52;
int ECONNABORTED = 53;
int ECONNRESET = 54;
int ENOBUFS = 55;
int EISCONN = 56;
int ENOTCONN = 57;
int ESHUTDOWN = 58;
int ETOOMANYREFS = 59;
int ETIMEDOUT = 60;
int ECONNREFUSED = 61;
int ELOOP = 62;
int ENAMETOOLONG = 63;
int EHOSTDOWN = 64;
int EHOSTUNREACH = 65;
int ENOTEMPTY = 66;
int EUSERS = 68;
int EDQUOT = 69;
int ESTALE = 70;
int EREMOTE = 71;
int ENOLCK = 77;
int ENOSYS = 78;
int EOVERFLOW = 84;
int EIDRM = 90;
int ENOMSG = 91;
int EILSEQ = 92;
int EBADMSG = 94;
int EMULTIHOP = 95;
int ENODATA = 96;
int ENOLINK = 97;
int ENOSR = 98;
int ENOSTR = 99;
int EPROTO = 100;
int ETIME = 101;
int EOPNOTSUPP_DARWIN = 102;
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 William N Dortch <bill.dortch@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.List;
import java.util.Map;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
/**
* This class is used to provide an intermediate superclass for modules and classes that include
* other modules. It inserts itself as the immediate superClass of the includer, but defers all
* module methods to the actual superclass. Multiple of these intermediate superclasses can be
* added for multiple included modules.
*
* This allows the normal superclass-based searches (searchMethod, getConstant, etc) to traverse
* the superclass ancestors as normal while the included modules do not actually show up in
* direct inheritance traversal.
*
* @see org.jruby.RubyModule
*/
public final class IncludedModuleWrapper extends RubyClass {
private final RubyModule delegate;
public IncludedModuleWrapper(Ruby runtime, RubyClass superClass, RubyModule delegate) {
super(runtime, superClass, false);
this.delegate = delegate;
this.metaClass = delegate.metaClass;
}
/**
* Overridden newIncludeClass implementation to allow attaching future includes to the correct module
* (i.e. the one to which this is attached)
*
* @see org.jruby.RubyModule#newIncludeClass(RubyClass)
*/
@Override
public IncludedModuleWrapper newIncludeClass(RubyClass superClass) {
IncludedModuleWrapper includedModule = new IncludedModuleWrapper(getRuntime(), superClass, getNonIncludedClass());
// include its parent (and in turn that module's parents)
if (getSuperClass() != null) {
includedModule.includeModule(getSuperClass());
}
return includedModule;
}
@Override
public boolean isModule() {
return false;
}
@Override
public boolean isClass() {
return false;
}
@Override
public boolean isIncluded() {
return true;
}
@Override
public boolean isImmediate() {
return true;
}
@Override
public void setMetaClass(RubyClass newRubyClass) {
throw new UnsupportedOperationException("An included class is only a wrapper for a module");
}
@Override
public Map<String, DynamicMethod> getMethods() {
return delegate.getMethods();
}
@Override
public void addMethod(String name, DynamicMethod method) {
throw new UnsupportedOperationException("An included class is only a wrapper for a module");
}
public void setMethods(Map newMethods) {
throw new UnsupportedOperationException("An included class is only a wrapper for a module");
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public RubyModule getNonIncludedClass() {
return delegate;
}
@Override
public RubyClass getRealClass() {
return getSuperClass().getRealClass();
}
@Override
protected boolean isSame(RubyModule module) {
return delegate.isSame(module);
}
/**
* We don't want to reveal ourselves to Ruby code, so delegate this
* operation.
*/
@Override
public IRubyObject id() {
return delegate.id();
}
//
// VARIABLE TABLE METHODS - pass to delegate
//
@Override
protected boolean variableTableContains(String name) {
return delegate.variableTableContains(name);
}
@Override
protected boolean variableTableFastContains(String internedName) {
return delegate.variableTableFastContains(internedName);
}
@Override
protected IRubyObject variableTableFetch(String name) {
return delegate.variableTableFetch(name);
}
@Override
protected IRubyObject variableTableFastFetch(String internedName) {
return delegate.variableTableFastFetch(internedName);
}
@Override
protected IRubyObject variableTableStore(String name, IRubyObject value) {
return delegate.variableTableStore(name, value);
}
@Override
protected IRubyObject variableTableFastStore(String internedName, IRubyObject value) {
return delegate.variableTableFastStore(internedName, value);
}
@Override
protected IRubyObject variableTableRemove(String name) {
return delegate.variableTableRemove(name);
}
@Override
protected VariableTableEntry[] variableTableGetTable() {
return delegate.variableTableGetTable();
}
@Override
protected int variableTableGetSize() {
return delegate.variableTableGetSize();
}
@Override
protected void variableTableSync(List<Variable<IRubyObject>> vars) {
delegate.variableTableSync(vars);
}
@Override
protected IRubyObject variableTableReadLocked(VariableTableEntry entry) {
return delegate.variableTableReadLocked(entry);
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
@Override
@Deprecated // born deprecated
protected Map variableTableGetMap() {
return delegate.variableTableGetMap();
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
@Override
@Deprecated // born deprecated
protected Map variableTableGetMap(Map map) {
return delegate.variableTableGetMap(map);
}
//
// CONSTANT TABLE METHODS - pass to delegate
//
@Override
protected boolean constantTableContains(String name) {
return delegate.constantTableContains(name);
}
@Override
protected boolean constantTableFastContains(String internedName) {
return delegate.constantTableFastContains(internedName);
}
@Override
protected IRubyObject constantTableFetch(String name) {
return delegate.constantTableFetch(name);
}
@Override
protected IRubyObject constantTableFastFetch(String internedName) {
return delegate.constantTableFastFetch(internedName);
}
@Override
protected IRubyObject constantTableStore(String name, IRubyObject value) {
// FIXME: legal here? may want UnsupportedOperationException
return delegate.constantTableStore(name, value);
}
@Override
protected IRubyObject constantTableFastStore(String internedName, IRubyObject value) {
// FIXME: legal here? may want UnsupportedOperationException
return delegate.constantTableFastStore(internedName, value);
}
@Override
protected IRubyObject constantTableRemove(String name) {
// this _is_ legal (when removing an undef)
return delegate.constantTableRemove(name);
}
@Override
protected ConstantTableEntry[] constantTableGetTable() {
return delegate.constantTableGetTable();
}
@Override
protected int constantTableGetSize() {
return delegate.constantTableGetSize();
}
@Override
protected void constantTableSync(List<Variable<IRubyObject>> vars) {
// FIXME: legal here? may want UnsupportedOperationException
delegate.constantTableSync(vars);
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
@Override
@Deprecated // born deprecated
protected Map constantTableGetMap() {
return delegate.constantTableGetMap();
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
@Override
@Deprecated // born deprecated
protected Map constantTableGetMap(Map map) {
return delegate.constantTableGetMap(map);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Charles Nutter <charles.o.nutter@sun.com>
* Copyright (C) 2008 MenTaLguY <mental@rydia.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.image.VolatileImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.Arrays;
import java.lang.reflect.InvocationTargetException;
import org.jruby.anno.JRubyMethod;
import org.jruby.demo.TextAreaReadline;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
/**
* @author <a href="mailto:mental@rydia.net">MenTaLguY</a>
*
* The JRubyApplet class provides a simple way to write Java applets using
* JRuby without needing to create a custom Java applet class. At applet
* initialization time, JRubyApplet starts up a JRuby runtime, then evaluates
* the scriptlet given as the "eval" applet parameter.
*
* The Java applet instance is available to the Ruby script as
* JRUBY_APPLET; the script can define callbacks for applet start, stop,
* and destroy by passing blocks to JRUBY_APPLET.on_start,
* JRUBY_APPLET.on_stop, and JRUBY_APPLET.on_destroy, respectively.
*
* Ruby code can install a custom paint callback using JRUBY_APPLET.on_paint
* (the Graphics2D object is passed as an argument to the callback). By
* default, JRubyApplet painting is double-buffered, but you can select
* single-buffered painting via JRUBY_APPLET.double_buffered = false.
*
* The applet's background color can be set via JRUBY_APPLET.background_color=.
* You may want to set it to nil if you're not using double-buffering, so that
* no background color will be drawn (your own paint code is then responsible
* for filling the area).
*
* Beyond these things, you should be able to use JRuby's Java integration
* to do whatever you would do in Java with the applet instance.
*
*/
public class JRubyApplet extends Applet {
private Ruby runtime;
private boolean doubleBuffered = true;
private Color backgroundColor = Color.WHITE;
private RubyProc startProc;
private RubyProc stopProc;
private RubyProc destroyProc;
private RubyProc paintProc;
private Graphics priorGraphics;
private IRubyObject wrappedGraphics;
private VolatileImage backBuffer;
private Graphics backBufferGraphics;
private Facade facade;
private interface Facade {
public InputStream getInputStream();
public PrintStream getOutputStream();
public PrintStream getErrorStream();
public void attach(Ruby runtime, Applet applet);
public void destroy();
}
private static RubyProc blockToProc(Ruby runtime, Block block) {
if (block.isGiven()) {
RubyProc proc = block.getProcObject();
if (proc == null) {
proc = RubyProc.newProc(runtime, block, block.type);
}
return proc;
} else {
return null;
}
}
private boolean getBooleanParameter(String name, boolean defaultValue) {
String value = getParameter(name);
if ( value != null ) {
return value.equals("true");
} else {
return defaultValue;
}
}
private InputStream getCodeResourceAsStream(String name) {
if (name == null) {
return null;
}
try {
final URL directURL = new URL(getCodeBase(), name);
return directURL.openStream();
} catch (IOException e) {
}
return JRubyApplet.class.getClassLoader().getResourceAsStream(name);
}
private static void safeInvokeAndWait(Runnable runnable) throws InvocationTargetException, InterruptedException {
if (EventQueue.isDispatchThread()) {
try {
runnable.run();
} catch (Exception e) {
throw new InvocationTargetException(e);
}
} else {
EventQueue.invokeAndWait(runnable);
}
}
public static class RubyMethods {
@JRubyMethod
public static IRubyObject on_start(IRubyObject recv, Block block) {
JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
synchronized (applet) {
applet.startProc = blockToProc(applet.runtime, block);
}
return recv;
}
@JRubyMethod
public static IRubyObject on_stop(IRubyObject recv, Block block) {
JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
synchronized (applet) {
applet.stopProc = blockToProc(applet.runtime, block);
}
return recv;
}
@JRubyMethod
public static IRubyObject on_destroy(IRubyObject recv, Block block) {
JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
synchronized (applet) {
applet.destroyProc = blockToProc(applet.runtime, block);
}
return recv;
}
@JRubyMethod
public static IRubyObject on_paint(IRubyObject recv, Block block) {
JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
synchronized (applet) {
applet.paintProc = blockToProc(applet.runtime, block);
applet.repaint();
}
return recv;
}
}
@Override
public void init() {
super.init();
if (getBooleanParameter("jruby.console", false)) {
facade = new ConsoleFacade(getParameter("jruby.banner"));
} else {
facade = new TrivialFacade();
}
synchronized (this) {
if (runtime != null) {
return;
}
final RubyInstanceConfig config = new RubyInstanceConfig() {{
setInput(facade.getInputStream());
setOutput(facade.getOutputStream());
setError(facade.getErrorStream());
setObjectSpaceEnabled(getBooleanParameter("jruby.objectspace", false));
}};
Ruby.setSecurityRestricted(true);
runtime = Ruby.newInstance(config);
}
final String scriptName = getParameter("jruby.script");
final InputStream scriptStream = getCodeResourceAsStream(scriptName);
final String evalString = getParameter("jruby.eval");
try {
final JRubyApplet applet = this;
safeInvokeAndWait(new Runnable() {
public void run() {
applet.setLayout(new BorderLayout());
applet.facade.attach(applet.runtime, applet);
if (scriptStream != null) {
applet.runtime.runFromMain(scriptStream, scriptName);
}
if (evalString != null) {
applet.runtime.evalScriptlet(evalString);
}
}
});
} catch (InterruptedException e) {
} catch (InvocationTargetException e) {
throw new RuntimeException("Error running script", e.getCause());
}
}
private void invokeCallback(final RubyProc proc, final IRubyObject[] args) {
if (proc == null) {
return;
}
final Ruby runtime = this.runtime;
try {
safeInvokeAndWait(new Runnable() {
public void run() {
ThreadContext context = runtime.getCurrentContext();
proc.call(context, args);
}
});
} catch (InterruptedException e) {
} catch (InvocationTargetException e) {
throw new RuntimeException("Ruby callback failed", e.getCause());
}
}
public synchronized void setBackgroundColor(Color color) {
backgroundColor = color;
repaint();
}
public synchronized Color getBackgroundColor() {
return backgroundColor;
}
public synchronized boolean isDoubleBuffered() {
return doubleBuffered;
}
public synchronized void setDoubleBuffered(boolean shouldBuffer) {
doubleBuffered = shouldBuffer;
repaint();
}
@Override
public synchronized void start() {
super.start();
invokeCallback(startProc, new IRubyObject[] {});
}
@Override
public synchronized void stop() {
invokeCallback(stopProc, new IRubyObject[] {});
super.stop();
}
@Override
public synchronized void destroy() {
try {
invokeCallback(destroyProc, new IRubyObject[] {});
} finally {
facade.destroy();
final Ruby runtime = this.runtime;
this.runtime = null;
startProc = null;
stopProc = null;
destroyProc = null;
paintProc = null;
priorGraphics = null;
wrappedGraphics = null;
runtime.tearDown();
super.destroy();
}
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public synchronized void paint(Graphics g) {
if (doubleBuffered) {
paintBuffered(g);
} else {
paintUnbuffered(g);
}
}
private synchronized void paintBuffered(Graphics g) {
do {
GraphicsConfiguration config = getGraphicsConfiguration();
int width = getWidth();
int height = getHeight();
if (backBuffer == null || width != backBuffer.getWidth() || height != backBuffer.getHeight() || backBuffer.validate(config) == VolatileImage.IMAGE_INCOMPATIBLE) {
if (backBuffer != null) {
backBufferGraphics.dispose();
backBufferGraphics = null;
backBuffer.flush();
backBuffer = null;
}
backBuffer = config.createCompatibleVolatileImage(width, height);
backBufferGraphics = backBuffer.createGraphics();
}
backBufferGraphics.setClip(g.getClip());
paintUnbuffered(backBufferGraphics);
g.drawImage(backBuffer, 0, 0, this);
} while (backBuffer.contentsLost());
}
private synchronized void paintUnbuffered(Graphics g) {
if (backgroundColor != null) {
g.setColor(backgroundColor);
g.fillRect(0, 0, getWidth(), getHeight());
}
if (paintProc != null) {
if (priorGraphics != g) {
wrappedGraphics = JavaUtil.convertJavaToUsableRubyObject(runtime, g);
priorGraphics = g;
}
ThreadContext context = runtime.getCurrentContext();
paintProc.call(context, new IRubyObject[] {wrappedGraphics});
}
super.paint(g);
}
private static class TrivialFacade implements Facade {
public TrivialFacade() {}
public InputStream getInputStream() { return System.in; }
public PrintStream getOutputStream() { return System.out; }
public PrintStream getErrorStream() { return System.err; }
public void attach(Ruby runtime, Applet applet) {
final IRubyObject wrappedApplet = JavaUtil.convertJavaToUsableRubyObject(runtime, applet);
wrappedApplet.dataWrapStruct(applet);
runtime.defineGlobalConstant("JRUBY_APPLET", wrappedApplet);
wrappedApplet.getMetaClass().defineAnnotatedMethods(RubyMethods.class);
}
public void destroy() {}
}
private static class ConsoleFacade implements Facade {
private JTextPane textPane;
private JScrollPane scrollPane;
private TextAreaReadline adaptor;
private InputStream inputStream;
private PrintStream outputStream;
private PrintStream errorStream;
public ConsoleFacade(String bannerText) {
textPane = new JTextPane();
textPane.setMargin(new Insets(4, 4, 0, 4));
textPane.setCaretColor(new Color(0xa4, 0x00, 0x00));
textPane.setBackground(new Color(0xf2, 0xf2, 0xf2));
textPane.setForeground(new Color(0xa4, 0x00, 0x00));
Font font = findFont("Monospaced", Font.PLAIN, 14,
new String[] {"Monaco", "Andale Mono"});
textPane.setFont(font);
scrollPane = new JScrollPane(textPane);
scrollPane.setDoubleBuffered(true);
if ( bannerText != null ) {
bannerText = " " + bannerText + " \n\n";
}
adaptor = new TextAreaReadline(textPane, bannerText);
inputStream = adaptor.getInputStream();
outputStream = new PrintStream(adaptor.getOutputStream());
errorStream = new PrintStream(adaptor.getOutputStream());
}
public InputStream getInputStream() { return inputStream; }
public PrintStream getOutputStream() { return outputStream; }
public PrintStream getErrorStream() { return errorStream; }
public void attach(Ruby runtime, Applet applet) {
adaptor.hookIntoRuntime(runtime);
applet.add(scrollPane);
applet.validate();
}
public void destroy() {
Container parent = scrollPane.getParent();
adaptor.shutdown();
if (parent != null) {
parent.remove(scrollPane);
}
}
private Font findFont(String otherwise, int style, int size, String[] families) {
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
Arrays.sort(fonts);
for (int i = 0; i < families.length; i++) {
if (Arrays.binarySearch(fonts, families[i]) >= 0) {
return new Font(families[i], style, size);
}
}
return new Font(otherwise, style, size);
}
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public class JRubyClient extends JRubyService {
public JRubyClient(String[] args) throws Exception {
Configuration conf = new Configuration(args[0]);
if(conf.isDebug()) {
System.err.println("Starting client with port " + conf.getPort() + ", key " + conf.getKey() + " and command " + conf.getCommand());
}
Socket socket = new Socket(InetAddress.getLocalHost(), conf.getPort());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(conf.terminate()) {
writer.write(CMD_TERM + " " + conf.getKey() + "\n");
} else if(conf.noMore()) {
writer.write(CMD_NO_MORE + " " + conf.getKey() + "\n");
} else {
writer.write(CMD_START + " " + conf.getKey() + " " + conf.getCommand() + "\n");
}
writer.flush();
writer.close();
socket.close();
}
public static void main(String[] args) throws Exception {
new JRubyClient(args);
}
}// JRubyClient
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.ArrayList;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public class JRubyServer extends JRubyService {
private Configuration conf;
private boolean stillStarting = true;
private JRubyServer(String[] args) throws Exception {
conf = new Configuration(args[0]);
if(conf.isDebug()) {
System.err.println("Starting server with port " + conf.getPort() + " and key " + conf.getKey());
}
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress(InetAddress.getLocalHost(),conf.getPort()));
while(true) {
Thread t1 = new Thread(new Handler(server.accept()));
t1.setDaemon(true);
t1.start();
}
}
private class Handler implements Runnable {
private Socket socket;
public Handler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader rr = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
String command = rr.readLine();
rr.close();
this.socket.close();
this.socket = null;
if(conf.isDebug()) {
System.err.println("Got command: " + command);
}
String[] cmds = command.split(" ", 3);
if(cmds[1].equals(conf.getKey())) {
if(cmds[0].equals(CMD_TERM)) {
if(conf.isDebug()) {
System.err.println("Terminating hard");
}
System.exit(0);
} else if(cmds[0].equals(CMD_NO_MORE)) {
if(conf.isDebug()) {
System.err.println("Accepting no more START");
}
stillStarting = false;
} else if(cmds[0].equals(CMD_START)) {
if(stillStarting) {
if(conf.isDebug()) {
System.err.println("Doing START on command " + cmds[2]);
}
new Main().run(intoCommandArguments(cmds[2].trim()));
} else {
if(conf.isDebug()) {
System.err.println("Not doing START anymore, invalid command");
}
}
} else {
if(conf.isDebug()) {
System.err.println("Unrecognized command");
}
}
} else {
if(conf.isDebug()) {
System.err.println("Invalid key");
}
}
} catch(Exception e) {}
}
}
protected static String[] intoCommandArguments(String str) {
List<String> args = new ArrayList<String>();
boolean inSingle = false;
int contentStart = -1;
for(int i=0,j=str.length();i<j;i++) {
if(str.charAt(i) == ' ' && !inSingle && contentStart != -1) {
args.add(str.substring(contentStart,i));
contentStart = -1;
continue;
}
if(str.charAt(i) == ' ') {
continue;
}
if(str.charAt(i) == '\'' && !inSingle) {
inSingle = true;
contentStart = i+1;
continue;
}
if(str.charAt(i) == '\'') {
inSingle = false;
args.add(str.substring(contentStart,i));
contentStart = -1;
continue;
}
if(contentStart == -1) {
contentStart = i;
}
}
if(contentStart != -1) {
args.add(str.substring(contentStart));
}
return (String[])args.toArray(new String[0]);
}
public static void main(String[] args) throws Exception {
new JRubyServer(args);
}
}// JRubyServer
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public abstract class JRubyService {
protected static class Configuration {
private final static int DEFAULT_PORT = 19222;
private String key;
private int port = DEFAULT_PORT;
private boolean terminate;
private boolean noMore;
private boolean debug;
private String command;
public Configuration(String args) {
int i=0;
int stop;
loop: for(int j=args.length();i<j;i++) {
if(args.charAt(i) == '-' && i+1 < j) {
switch(args.charAt(++i)) {
case 'k':
stop = args.indexOf(" ", (++i) + 1);
if(stop == -1) {
stop = args.length();
}
key = args.substring(i, stop).trim();
i = stop;
break;
case 'p':
stop = args.indexOf(" ", (++i) + 1);
if(stop == -1) {
stop = args.length();
}
port = Integer.parseInt(args.substring(i, stop).trim());
i = stop;
break;
case 't':
terminate = true;
i++;
break;
case 'n':
noMore = true;
i++;
break;
case 'd':
debug = true;
i++;
break;
case '-': // handle everything after -- as arguments to the jruby process
i++;
break loop;
default:
i--;
break loop;
}
} else if(args.charAt(i) != ' ') {
break loop;
}
}
if(i<args.length()) {
command = args.substring(i).trim();
}
}
public String getKey() {
return key;
}
public int getPort() {
return port;
}
public boolean terminate() {
return terminate;
}
public boolean noMore() {
return noMore;
}
public boolean isDebug() {
return debug;
}
public String getCommand() {
return command;
}
}
public static final String CMD_START = "START";
public static final String CMD_NO_MORE = "NO_MORE";
public static final String CMD_TERM = "TERM";
}// JRubyService
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2006 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Kiel Hodges <jruby-devel@selfsosoft.com>
* Copyright (C) 2005 Jason Voegele <jason@jvoegele.com>
* Copyright (C) 2005 Tim Azzopardi <tim@tigerfive.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.InputStream;
import java.io.PrintStream;
import org.jruby.exceptions.MainExitException;
import org.jruby.exceptions.RaiseException;
import org.jruby.exceptions.ThreadKill;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.SafePropertyAccessor;
import org.jruby.util.SimpleSampler;
/**
* Class used to launch the interpreter.
* This is the main class as defined in the jruby.mf manifest.
* It is very basic and does not support yet the same array of switches
* as the C interpreter.
* Usage: java -jar jruby.jar [switches] [rubyfile.rb] [arguments]
* -e 'command' one line of script. Several -e's allowed. Omit [programfile]
* @author jpetersen
*/
public class Main {
private boolean hasPrintedUsage = false;
private final RubyInstanceConfig config;
public Main(RubyInstanceConfig config) {
this.config = config;
}
public Main(final InputStream in, final PrintStream out, final PrintStream err) {
this(new RubyInstanceConfig(){{
setInput(in);
setOutput(out);
setError(err);
}});
}
public Main() {
this(new RubyInstanceConfig());
}
public static void main(String[] args) {
Main main = new Main();
try {
int status = main.run(args);
if (status != 0) {
System.exit(status);
}
} catch (RaiseException re) {
throw re;
} catch (Throwable t) {
// print out as a nice Ruby backtrace
System.err.println(ThreadContext.createRawBacktraceStringFromThrowable(t));
System.exit(1);
}
}
public int run(String[] args) {
try {
config.processArguments(args);
return run();
} catch (MainExitException mee) {
if (!mee.isAborted()) {
config.getOutput().println(mee.getMessage());
if (mee.isUsageError()) {
printUsage();
}
}
return mee.getStatus();
} catch (OutOfMemoryError oome) {
// produce a nicer error since Rubyists aren't used to seeing this
System.gc();
String memoryMax = SafePropertyAccessor.getProperty("jruby.memory.max");
String message = "";
if (memoryMax != null) {
message = " of " + memoryMax;
}
System.err.println("Error: Your application used more memory than the safety cap" + message + ".");
System.err.println("Specify -J-Xmx####m to increase it (#### = cap size in MB).");
if (config.getVerbose()) {
System.err.println("Exception trace follows:");
oome.printStackTrace();
} else {
System.err.println("Specify -w for full OutOfMemoryError stack trace");
}
return 1;
} catch (StackOverflowError soe) {
// produce a nicer error since Rubyists aren't used to seeing this
System.gc();
String stackMax = SafePropertyAccessor.getProperty("jruby.stack.max");
String message = "";
if (stackMax != null) {
message = " of " + stackMax;
}
System.err.println("Error: Your application used more stack memory than the safety cap" + message + ".");
System.err.println("Specify -J-Xss####k to increase it (#### = cap size in KB).");
if (config.getVerbose()) {
System.err.println("Exception trace follows:");
soe.printStackTrace();
} else {
System.err.println("Specify -w for full StackOverflowError stack trace");
}
return 1;
} catch (UnsupportedClassVersionError ucve) {
System.err.println("Error: Some library (perhaps JRuby) was built with a later JVM version.");
System.err.println("Please use libraries built with the version you intend to use or an earlier one.");
if (config.getVerbose()) {
System.err.println("Exception trace follows:");
ucve.printStackTrace();
} else {
System.err.println("Specify -w for full UnsupportedClassVersionError stack trace");
}
return 1;
} catch (ThreadKill kill) {
return 0;
}
}
public int run() {
if (config.isShowVersion()) {
showVersion();
}
if (config.isShowCopyright()) {
showCopyright();
}
if (!config.shouldRunInterpreter() ) {
if (config.shouldPrintUsage()) {
printUsage();
}
if (config.shouldPrintProperties()) {
printProperties();
}
return 0;
}
InputStream in = config.getScriptSource();
String filename = config.displayedFileName();
Ruby runtime = Ruby.newInstance(config);
// set thread context JRuby classloader here, for the main thread
try {
Thread.currentThread().setContextClassLoader(runtime.getJRubyClassLoader());
} catch (SecurityException se) {
// can't set TC classloader
if (runtime.getInstanceConfig().isVerbose()) {
System.err.println("WARNING: Security restrictions disallowed setting context classloader for main thread.");
}
}
if (in == null) {
// no script to run, return success below
} else if (config.isShouldCheckSyntax()) {
runtime.parseFromMain(in, filename);
config.getOutput().println("Syntax OK");
} else {
long now = -1;
try {
if (config.isBenchmarking()) {
now = System.currentTimeMillis();
}
if (config.isSamplingEnabled()) {
SimpleSampler.startSampleThread();
}
try {
runtime.runFromMain(in, filename);
} finally {
runtime.tearDown();
if (config.isBenchmarking()) {
config.getOutput().println("Runtime: " + (System.currentTimeMillis() - now) + " ms");
}
if (config.isSamplingEnabled()) {
org.jruby.util.SimpleSampler.report();
}
}
} catch (RaiseException rj) {
RubyException raisedException = rj.getException();
if (runtime.getSystemExit().isInstance(raisedException)) {
IRubyObject status = raisedException.callMethod(runtime.getCurrentContext(), "status");
if (status != null && !status.isNil()) {
return RubyNumeric.fix2int(status);
}
} else {
runtime.printError(raisedException);
return 1;
}
}
}
return 0;
}
private void showVersion() {
config.getOutput().print(config.getVersionString());
}
private void showCopyright() {
config.getOutput().print(config.getCopyrightString());
}
public void printUsage() {
if (!hasPrintedUsage) {
config.getOutput().print(config.getBasicUsageHelp());
hasPrintedUsage = true;
}
}
public void printProperties() {
config.getOutput().print(config.getPropertyHelp());
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.lang.ref.SoftReference;
import org.jruby.runtime.builtin.IRubyObject;
public final class MetaClass extends RubyClass {
private SoftReference<IRubyObject> attached = new SoftReference<IRubyObject>(null);
/** NEWOBJ (in RubyObject#getSingletonClassClone())
*
*/
public MetaClass(Ruby runtime) {
super(runtime, null, false);
}
/** rb_class_boot (for MetaClasses) (in makeMetaClass(RubyClass))
*
*/
public MetaClass(Ruby runtime, RubyClass superClass) {
super(runtime, superClass, false);
index = superClass.index; // use same ClassIndex as metaclass, since we're technically still of that type
}
public boolean isSingleton() {
return true;
}
/**
* If an object uses an anonymous class 'class << obj', then this grabs the original
* metaclass and not the one that get injected as a result of 'class << obj'.
*/
public RubyClass getRealClass() {
return superClass.getRealClass();
}
public final IRubyObject allocate(){
throw getRuntime().newTypeError("can't create instance of virtual class");
}
public IRubyObject getAttached() {
return attached.get();
}
public void setAttached(IRubyObject attached) {
this.attached = new SoftReference<IRubyObject>(attached);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2005 David Corbin <dcorbin@users.sourceforge.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.PrintStream;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.javasupport.Java;
import org.jruby.javasupport.JavaObject;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyClass(name = "NativeException", parent = "RuntimeError")
public class NativeException extends RubyException {
private final Throwable cause;
public static final String CLASS_NAME = "NativeException";
private final Ruby runtime;
public NativeException(Ruby runtime, RubyClass rubyClass, Throwable cause) {
super(runtime, rubyClass, cause.getClass().getName() + ": " + cause.getMessage());
this.runtime = runtime;
this.cause = cause;
}
public static RubyClass createClass(Ruby runtime, RubyClass baseClass) {
// FIXME: If NativeException is expected to be used from Ruby code, it should provide
// a real allocator to be used. Otherwise Class.new will fail, as will marshalling. JRUBY-415
RubyClass exceptionClass = runtime.defineClass(CLASS_NAME, baseClass, ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
exceptionClass.defineAnnotatedMethods(NativeException.class);
return exceptionClass;
}
@JRubyMethod(frame = true)
public IRubyObject cause(Block unusedBlock) {
return Java.wrap(getRuntime(), JavaObject.wrap(getRuntime(), cause));
}
public IRubyObject backtrace() {
IRubyObject rubyTrace = super.backtrace();
if (rubyTrace.isNil()) {
return rubyTrace;
}
RubyArray array = (RubyArray) rubyTrace.dup();
StackTraceElement[] stackTrace = cause.getStackTrace();
for (int i = stackTrace.length - 1; i >= 0; i--) {
StackTraceElement element = stackTrace[i];
String className = element.getClassName();
String line = null;
if (element.getFileName() == null) {
line = className + ":" + element.getLineNumber() + ":in `" + element.getMethodName() + "'";
} else {
int index = className.lastIndexOf(".");
String packageName = null;
if (index == -1) {
packageName = "";
} else {
packageName = className.substring(0, index) + "/";
}
line = packageName.replace(".", "/") + element.getFileName() + ":" + element.getLineNumber() + ":in `" + element.getMethodName() + "'";
}
RubyString string = runtime.newString(line);
array.unshift(string);
}
return array;
}
public void printBacktrace(PrintStream errorStream) {
super.printBacktrace(errorStream);
errorStream.println("Complete Java stackTrace");
cause.printStackTrace(errorStream);
}
public Throwable getCause() {
return cause;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public interface Profile {
Profile ALL = new Profile() {
public boolean allowBuiltin(String name) { return true; }
public boolean allowClass(String name) { return true; }
public boolean allowModule(String name) { return true; }
public boolean allowLoad(String name) { return true; }
public boolean allowRequire(String name) { return true; }
};
Profile DEBUG_ALLOW = new Profile() {
public boolean allowBuiltin(String name) { System.err.println("allowBuiltin("+name+")"); return true; }
public boolean allowClass(String name) { System.err.println("allowClass("+name+")"); return true; }
public boolean allowModule(String name) { System.err.println("allowModule("+name+")"); return true; }
public boolean allowLoad(String name) { System.err.println("allowLoad("+name+")"); return true; }
public boolean allowRequire(String name) { System.err.println("allowRequire("+name+")"); return true; }
};
Profile NO_FILE_CLASS = new Profile() {
public boolean allowBuiltin(String name) { return true; }
public boolean allowClass(String name) { return !name.equals("File"); }
public boolean allowModule(String name) { return true; }
public boolean allowLoad(String name) { return true; }
public boolean allowRequire(String name) { return true; }
};
Profile ANY = ALL;
Profile DEFAULT = ALL;
boolean allowBuiltin(String name);
boolean allowClass(String name);
boolean allowModule(String name);
boolean allowLoad(String name);
boolean allowRequire(String name);
}// Profile
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
* Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.joda.time.DateTimeZone;
import org.jruby.ast.Node;
import org.jruby.ast.executable.RubiniusRunner;
import org.jruby.ast.executable.Script;
import org.jruby.ast.executable.YARVCompiledRunner;
import org.jruby.common.RubyWarnings;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.compiler.ASTCompiler;
import org.jruby.compiler.ASTInspector;
import org.jruby.compiler.JITCompiler;
import org.jruby.compiler.NotCompilableException;
import org.jruby.compiler.impl.StandardASMCompiler;
import org.jruby.compiler.yarv.StandardYARVCompiler;
import org.jruby.exceptions.JumpException;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.JRubyPOSIXHandler;
import org.jruby.ext.LateLoadingLibrary;
import org.jruby.ext.posix.POSIX;
import org.jruby.ext.posix.POSIXFactory;
import org.jruby.internal.runtime.GlobalVariables;
import org.jruby.internal.runtime.ThreadService;
import org.jruby.internal.runtime.ValueAccessor;
import org.jruby.javasupport.JavaSupport;
import org.jruby.management.BeanManager;
import org.jruby.management.ClassCache;
import org.jruby.management.Config;
import org.jruby.parser.Parser;
import org.jruby.parser.ParserConfiguration;
import org.jruby.runtime.Binding;
import org.jruby.runtime.Block;
import org.jruby.runtime.CacheMap;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.DynamicScope;
import org.jruby.runtime.EventHook;
import org.jruby.runtime.GlobalVariable;
import org.jruby.runtime.IAccessor;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ObjectSpace;
import org.jruby.runtime.RubyEvent;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.Library;
import org.jruby.runtime.load.LoadService;
import org.jruby.util.BuiltinScript;
import org.jruby.util.ByteList;
import org.jruby.util.IOInputStream;
import org.jruby.util.IOOutputStream;
import org.jruby.util.JRubyClassLoader;
import org.jruby.util.JavaNameMangler;
import org.jruby.util.KCode;
import org.jruby.util.SafePropertyAccessor;
import org.jruby.util.collections.WeakHashSet;
import org.jruby.util.io.ChannelDescriptor;
/**
* The Ruby object represents the top-level of a JRuby "instance" in a given VM.
* JRuby supports spawning multiple instances in the same JVM. Generally, objects
* created under these instances are tied to a given runtime, for such details
* as identity and type, because multiple Ruby instances means there are
* multiple instances of each class. This means that in multi-runtime mode
* (or really, multi-VM mode, where each JRuby instance is a ruby "VM"), objects
* generally can't be transported across runtimes without marshaling.
*
* This class roots everything that makes the JRuby runtime function, and
* provides a number of utility methods for constructing global types and
* accessing global runtime structures.
*/
public final class Ruby {
/**
* Returns a new instance of the JRuby runtime configured with defaults.
*
* @return the JRuby runtime
* @see org.jruby.RubyInstanceConfig
*/
public static Ruby newInstance() {
return newInstance(new RubyInstanceConfig());
}
/**
* Returns a new instance of the JRuby runtime configured as specified.
*
* @param config The instance configuration
* @return The JRuby runtime
* @see org.jruby.RubyInstanceConfig
*/
public static Ruby newInstance(RubyInstanceConfig config) {
Ruby ruby = new Ruby(config);
ruby.init();
return ruby;
}
/**
* Returns a new instance of the JRuby runtime configured with the given
* input, output and error streams and otherwise default configuration
* (except where specified system properties alter defaults).
*
* @param in the custom input stream
* @param out the custom output stream
* @param err the custom error stream
* @return the JRuby runtime
* @see org.jruby.RubyInstanceConfig
*/
public static Ruby newInstance(InputStream in, PrintStream out, PrintStream err) {
RubyInstanceConfig config = new RubyInstanceConfig();
config.setInput(in);
config.setOutput(out);
config.setError(err);
return newInstance(config);
}
/**
* Create and initialize a new JRuby runtime. The properties of the
* specified RubyInstanceConfig will be used to determine various JRuby
* runtime characteristics.
*
* @param config The configuration to use for the new instance
* @see org.jruby.RubyInstanceConfig
*/
private Ruby(RubyInstanceConfig config) {
this.config = config;
this.threadService = new ThreadService(this);
if(config.isSamplingEnabled()) {
org.jruby.util.SimpleSampler.registerThreadContext(threadService.getCurrentContext());
}
this.in = config.getInput();
this.out = config.getOutput();
this.err = config.getError();
this.objectSpaceEnabled = config.isObjectSpaceEnabled();
this.profile = config.getProfile();
this.currentDirectory = config.getCurrentDirectory();
this.kcode = config.getKCode();
this.beanManager = new BeanManager(this, config.isManagementEnabled());
this.jitCompiler = new JITCompiler(this);
this.beanManager.register(new Config(this));
this.beanManager.register(new ClassCache(this));
this.cacheMap = new CacheMap(this);
}
/**
* Evaluates a script under the current scope (perhaps the top-level
* scope) and returns the result (generally the last value calculated).
* This version goes straight into the interpreter, bypassing compilation
* and runtime preparation typical to normal script runs.
*
* @param script The scriptlet to run
* @returns The result of the eval
*/
public IRubyObject evalScriptlet(String script) {
ThreadContext context = getCurrentContext();
Node node = parseEval(script, "<script>", context.getCurrentScope(), 0);
try {
return node.interpret(this, context, context.getFrameSelf(), Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
throw newLocalJumpError("return", (IRubyObject)rj.getValue(), "unexpected return");
} catch (JumpException.BreakJump bj) {
throw newLocalJumpError("break", (IRubyObject)bj.getValue(), "unexpected break");
} catch (JumpException.RedoJump rj) {
throw newLocalJumpError("redo", (IRubyObject)rj.getValue(), "unexpected redo");
}
}
/**
* Parse and execute the specified script
* This differs from the other methods in that it accepts a string-based script and
* parses and runs it as though it were loaded at a command-line. This is the preferred
* way to start up a new script when calling directly into the Ruby object (which is
* generally *dis*couraged.
*
* @param script The contents of the script to run as a normal, root script
* @return The last value of the script
*/
public IRubyObject executeScript(String script, String filename) {
byte[] bytes;
try {
bytes = script.getBytes(KCode.NONE.getKCode());
} catch (UnsupportedEncodingException e) {
bytes = script.getBytes();
}
Node node = parseInline(new ByteArrayInputStream(bytes), filename, null);
ThreadContext context = getCurrentContext();
String oldFile = context.getFile();
int oldLine = context.getLine();
try {
context.setFile(node.getPosition().getFile());
context.setLine(node.getPosition().getStartLine());
return runNormally(node, false);
} finally {
context.setFile(oldFile);
context.setLine(oldLine);
}
}
/**
* Run the script contained in the specified input stream, using the
* specified filename as the name of the script being executed. The stream
* will be read fully before being parsed and executed. The given filename
* will be used for the ruby $PROGRAM_NAME and $0 global variables in this
* runtime.
*
* This method is intended to be called once per runtime, generally from
* Main or from main-like top-level entry points.
*
* As part of executing the script loaded from the input stream, various
* RubyInstanceConfig properties will be used to determine whether to
* compile the script before execution or run with various wrappers (for
* looping, printing, and so on, see jruby -help).
*
* @param inputStream The InputStream from which to read the script contents
* @param filename The filename to use when parsing, and for $PROGRAM_NAME
* and $0 ruby global variables.
*/
public void runFromMain(InputStream inputStream, String filename) {
IAccessor d = new ValueAccessor(newString(filename));
getGlobalVariables().define("$PROGRAM_NAME", d);
getGlobalVariables().define("$0", d);
for (Iterator i = config.getOptionGlobals().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
Object value = entry.getValue();
IRubyObject varvalue;
if (value != null) {
varvalue = newString(value.toString());
} else {
varvalue = getTrue();
}
getGlobalVariables().set("$" + entry.getKey().toString(), varvalue);
}
if(config.isYARVEnabled()) {
if (config.isShowBytecode()) System.err.print("error: bytecode printing only works with JVM bytecode");
new YARVCompiledRunner(this, inputStream, filename).run();
} else if(config.isRubiniusEnabled()) {
if (config.isShowBytecode()) System.err.print("error: bytecode printing only works with JVM bytecode");
new RubiniusRunner(this, inputStream, filename).run();
} else {
Node scriptNode = parseFromMain(inputStream, filename);
ThreadContext context = getCurrentContext();
String oldFile = context.getFile();
int oldLine = context.getLine();
try {
context.setFile(scriptNode.getPosition().getFile());
context.setLine(scriptNode.getPosition().getStartLine());
if (config.isAssumePrinting() || config.isAssumeLoop()) {
runWithGetsLoop(scriptNode, config.isAssumePrinting(), config.isProcessLineEnds(),
config.isSplit(), config.isYARVCompileEnabled());
} else {
runNormally(scriptNode, config.isYARVCompileEnabled());
}
} finally {
context.setFile(oldFile);
context.setLine(oldLine);
}
}
}
/**
* Parse the script contained in the given input stream, using the given
* filename as the name of the script, and return the root Node. This
* is used to verify that the script syntax is valid, for jruby -c. The
* current scope (generally the top-level scope) is used as the parent
* scope for parsing.
*
* @param inputStream The input stream from which to read the script
* @param filename The filename to use for parsing
* @returns The root node of the parsed script
*/
public Node parseFromMain(InputStream inputStream, String filename) {
if (config.isInlineScript()) {
return parseInline(inputStream, filename, getCurrentContext().getCurrentScope());
} else {
return parseFile(inputStream, filename, getCurrentContext().getCurrentScope());
}
}
/**
* Run the given script with a "while gets; end" loop wrapped around it.
* This is primarily used for the -n command-line flag, to allow writing
* a short script that processes input lines using the specified code.
*
* @param scriptNode The root node of the script to execute
* @param printing Whether $_ should be printed after each loop (as in the
* -p command-line flag)
* @param processLineEnds Whether line endings should be processed by
* setting $\ to $/ and <code>chop!</code>ing every line read
* @param split Whether to split each line read using <code>String#split</code>
* @param yarvCompile Whether to compile the target script to YARV (Ruby 1.9)
* bytecode before executing.
* @return The result of executing the specified script
*/
public IRubyObject runWithGetsLoop(Node scriptNode, boolean printing, boolean processLineEnds, boolean split, boolean yarvCompile) {
ThreadContext context = getCurrentContext();
Script script = null;
YARVCompiledRunner runner = null;
boolean compile = getInstanceConfig().getCompileMode().shouldPrecompileCLI();
if (compile || !yarvCompile) {
script = tryCompile(scriptNode);
if (compile && script == null) {
// terminate; tryCompile will have printed out an error and we're done
return getNil();
}
} else if (yarvCompile) {
runner = tryCompileYarv(scriptNode);
}
if (processLineEnds) {
getGlobalVariables().set("$\\", getGlobalVariables().get("$/"));
}
while (RubyKernel.gets(context, getTopSelf(), IRubyObject.NULL_ARRAY).isTrue()) {
loop: while (true) { // Used for the 'redo' command
try {
if (processLineEnds) {
getGlobalVariables().get("$_").callMethod(context, "chop!");
}
if (split) {
getGlobalVariables().set("$F", getGlobalVariables().get("$_").callMethod(context, "split"));
}
if (script != null) {
runScript(script);
} else if (runner != null) {
runYarv(runner);
} else {
runInterpreter(scriptNode);
}
if (printing) RubyKernel.print(context, getKernel(), new IRubyObject[] {getGlobalVariables().get("$_")});
break loop;
} catch (JumpException.RedoJump rj) {
// do nothing, this iteration restarts
} catch (JumpException.NextJump nj) {
// recheck condition
break loop;
} catch (JumpException.BreakJump bj) {
// end loop
return (IRubyObject) bj.getValue();
}
}
}
return getNil();
}
/**
* Run the specified script without any of the loop-processing wrapper
* code.
*
* @param scriptNode The root node of the script to be executed
* @param yarvCompile Whether to compile the script to YARV (Ruby 1.9)
* bytecode before execution
* @return The result of executing the script
*/
public IRubyObject runNormally(Node scriptNode, boolean yarvCompile) {
Script script = null;
YARVCompiledRunner runner = null;
boolean compile = getInstanceConfig().getCompileMode().shouldPrecompileCLI();
boolean forceCompile = getInstanceConfig().getCompileMode().shouldPrecompileAll();
if (yarvCompile) {
runner = tryCompileYarv(scriptNode);
} else if (compile) {
script = tryCompile(scriptNode);
if (forceCompile && script == null) {
System.err.println("Error, could not compile; pass -J-Djruby.jit.logging.verbose=true for more details");
return getNil();
}
}
if (script != null) {
if (config.isShowBytecode()) {
return nilObject;
} else {
return runScript(script);
}
} else if (runner != null) {
return runYarv(runner);
} else {
if (config.isShowBytecode()) System.err.print("error: bytecode printing only works with JVM bytecode");
return runInterpreter(scriptNode);
}
}
private Script tryCompile(Node node) {
return tryCompile(node, new JRubyClassLoader(getJRubyClassLoader()));
}
private Script tryCompile(Node node, JRubyClassLoader classLoader) {
Script script = null;
try {
String filename = node.getPosition().getFile();
String classname = JavaNameMangler.mangledFilenameForStartupClasspath(filename);
ASTInspector inspector = new ASTInspector();
inspector.inspect(node);
StandardASMCompiler asmCompiler = new StandardASMCompiler(classname, filename);
ASTCompiler compiler = new ASTCompiler();
if (config.isShowBytecode()) {
compiler.compileRoot(node, asmCompiler, inspector, false, false);
asmCompiler.dumpClass(System.out);
} else {
compiler.compileRoot(node, asmCompiler, inspector, true, false);
}
script = (Script)asmCompiler.loadClass(classLoader).newInstance();
if (config.isJitLogging()) {
System.err.println("compiled: " + node.getPosition().getFile());
}
} catch (NotCompilableException nce) {
if (config.isJitLoggingVerbose()) {
System.err.println("Error -- Not compileable: " + nce.getMessage());
nce.printStackTrace();
}
} catch (ClassNotFoundException e) {
if (config.isJitLoggingVerbose()) {
System.err.println("Error -- Not compileable: " + e.getMessage());
e.printStackTrace();
}
} catch (InstantiationException e) {
if (config.isJitLoggingVerbose()) {
System.err.println("Error -- Not compileable: " + e.getMessage());
e.printStackTrace();
}
} catch (IllegalAccessException e) {
if (config.isJitLoggingVerbose()) {
System.err.println("Error -- Not compileable: " + e.getMessage());
e.printStackTrace();
}
} catch (Throwable t) {
if (config.isJitLoggingVerbose()) {
System.err.println("could not compile: " + node.getPosition().getFile() + " because of: \"" + t.getMessage() + "\"");
t.printStackTrace();
}
}
return script;
}
private YARVCompiledRunner tryCompileYarv(Node node) {
try {
StandardYARVCompiler compiler = new StandardYARVCompiler(this);
ASTCompiler.getYARVCompiler().compile(node, compiler);
org.jruby.lexer.yacc.ISourcePosition p = node.getPosition();
if(p == null && node instanceof org.jruby.ast.RootNode) {
p = ((org.jruby.ast.RootNode)node).getBodyNode().getPosition();
}
return new YARVCompiledRunner(this,compiler.getInstructionSequence("<main>",p.getFile(),"toplevel"));
} catch (NotCompilableException nce) {
System.err.println("Error -- Not compileable: " + nce.getMessage());
return null;
} catch (JumpException.ReturnJump rj) {
return null;
}
}
private IRubyObject runScript(Script script) {
ThreadContext context = getCurrentContext();
try {
return script.load(context, context.getFrameSelf(), IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
return (IRubyObject) rj.getValue();
}
}
private IRubyObject runYarv(YARVCompiledRunner runner) {
try {
return runner.run();
} catch (JumpException.ReturnJump rj) {
return (IRubyObject) rj.getValue();
}
}
private IRubyObject runInterpreter(Node scriptNode) {
ThreadContext context = getCurrentContext();
assert scriptNode != null : "scriptNode is not null";
try {
return scriptNode.interpret(this, context, getTopSelf(), Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
return (IRubyObject) rj.getValue();
}
}
public BeanManager getBeanManager() {
return beanManager;
}
public JITCompiler getJITCompiler() {
return jitCompiler;
}
/**
* @deprecated use #newInstance()
*/
public static Ruby getDefaultInstance() {
return newInstance();
}
@Deprecated
public static Ruby getCurrentInstance() {
return null;
}
@Deprecated
public static void setCurrentInstance(Ruby runtime) {
}
public int allocSymbolId() {
return symbolLastId.incrementAndGet();
}
public int allocModuleId() {
return moduleLastId.incrementAndGet();
}
/**
* Retrieve the module with the given name from the Object namespace.
*
* @param name The name of the module
* @return The module or null if not found
*/
public RubyModule getModule(String name) {
return (RubyModule) objectClass.getConstantAt(name);
}
/**
* Retrieve the module with the given name from the Object namespace. The
* module name must be an interned string, but this method will be faster
* than the non-interned version.
*
* @param internedName The name of the module; <em>must</em> be an interned String
* @return The module or null if not found
*/
public RubyModule fastGetModule(String internedName) {
return (RubyModule) objectClass.fastGetConstantAt(internedName);
}
/**
* Retrieve the class with the given name from the Object namespace.
*
* @param name The name of the class
* @return The class
*/
public RubyClass getClass(String name) {
return objectClass.getClass(name);
}
/**
* Retrieve the class with the given name from the Object namespace. The
* module name must be an interned string, but this method will be faster
* than the non-interned version.
*
* @param internedName the name of the class; <em>must</em> be an interned String!
* @return
*/
public RubyClass fastGetClass(String internedName) {
return objectClass.fastGetClass(internedName);
}
/**
* Define a new class under the Object namespace. Roughly equivalent to
* rb_define_class in MRI.
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @return The new class
*/
public RubyClass defineClass(String name, RubyClass superClass, ObjectAllocator allocator) {
return defineClassUnder(name, superClass, allocator, objectClass);
}
/**
* A variation of defineClass that allows passing in an array of subplementary
* call sites for improving dynamic invocation performance.
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @return The new class
*/
public RubyClass defineClass(String name, RubyClass superClass, ObjectAllocator allocator, CallSite[] callSites) {
return defineClassUnder(name, superClass, allocator, objectClass, callSites);
}
/**
* Define a new class with the given name under the given module or class
* namespace. Roughly equivalent to rb_define_class_under in MRI.
*
* If the name specified is already bound, its value will be returned if:
* * It is a class
* * No new superclass is being defined
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @param parent The namespace under which to define the new class
* @return The new class
*/
public RubyClass defineClassUnder(String name, RubyClass superClass, ObjectAllocator allocator, RubyModule parent) {
return defineClassUnder(name, superClass, allocator, parent, null);
}
/**
* A variation of defineClassUnder that allows passing in an array of
* supplementary call sites to improve dynamic invocation.
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @param parent The namespace under which to define the new class
* @param callSites The array of call sites to add
* @return The new class
*/
public RubyClass defineClassUnder(String name, RubyClass superClass, ObjectAllocator allocator, RubyModule parent, CallSite[] callSites) {
IRubyObject classObj = parent.getConstantAt(name);
if (classObj != null) {
if (!(classObj instanceof RubyClass)) throw newTypeError(name + " is not a class");
RubyClass klazz = (RubyClass)classObj;
if (klazz.getSuperClass().getRealClass() != superClass) {
throw newNameError(name + " is already defined", name);
}
// If we define a class in Ruby, but later want to allow it to be defined in Java,
// the allocator needs to be updated
if (klazz.getAllocator() != allocator) {
klazz.setAllocator(allocator);
}
return klazz;
}
boolean parentIsObject = parent == objectClass;
if (superClass == null) {
String className = parentIsObject ? name : parent.getName() + "::" + name;
warnings.warn(ID.NO_SUPER_CLASS, "no super class for `" + className + "', Object assumed", className);
superClass = objectClass;
}
return RubyClass.newClass(this, superClass, name, allocator, parent, !parentIsObject, callSites);
}
/**
* Define a new module under the Object namespace. Roughly equivalent to
* rb_define_module in MRI.
*
* @param name The name of the new module
* @returns The new module
*/
public RubyModule defineModule(String name) {
return defineModuleUnder(name, objectClass);
}
/**
* Define a new module with the given name under the given module or
* class namespace. Roughly equivalent to rb_define_module_under in MRI.
*
* @param name The name of the new module
* @param parent The class or module namespace under which to define the
* module
* @returns The new module
*/
public RubyModule defineModuleUnder(String name, RubyModule parent) {
IRubyObject moduleObj = parent.getConstantAt(name);
boolean parentIsObject = parent == objectClass;
if (moduleObj != null ) {
if (moduleObj.isModule()) return (RubyModule)moduleObj;
if (parentIsObject) {
throw newTypeError(moduleObj.getMetaClass().getName() + " is not a module");
} else {
throw newTypeError(parent.getName() + "::" + moduleObj.getMetaClass().getName() + " is not a module");
}
}
return RubyModule.newModule(this, name, parent, !parentIsObject);
}
/**
* From Object, retrieve the named module. If it doesn't exist a
* new module is created.
*
* @param name The name of the module
* @returns The existing or new module
*/
public RubyModule getOrCreateModule(String name) {
IRubyObject module = objectClass.getConstantAt(name);
if (module == null) {
module = defineModule(name);
} else if (getSafeLevel() >= 4) {
throw newSecurityError("Extending module prohibited.");
} else if (!module.isModule()) {
throw newTypeError(name + " is not a Module");
}
return (RubyModule) module;
}
/**
* Retrieve the current safe level.
*
* @see org.jruby.Ruby#setSaveLevel
*/
public int getSafeLevel() {
return this.safeLevel;
}
/**
* Set the current safe level:
*
* 0 - strings from streams/environment/ARGV are tainted (default)
* 1 - no dangerous operation by tainted value
* 2 - process/file operations prohibited
* 3 - all generated objects are tainted
* 4 - no global (non-tainted) variable modification/no direct output
*
* The safe level is set using $SAFE in Ruby code. It is not particularly
* well supported in JRuby.
*/
public void setSafeLevel(int safeLevel) {
this.safeLevel = safeLevel;
}
public KCode getKCode() {
return kcode;
}
public void setKCode(KCode kcode) {
this.kcode = kcode;
}
public void secure(int level) {
if (level <= safeLevel) {
throw newSecurityError("Insecure operation '" + getCurrentContext().getFrameName() + "' at level " + safeLevel);
}
}
// FIXME moved this here to get what's obviously a utility method out of IRubyObject.
// perhaps security methods should find their own centralized home at some point.
public void checkSafeString(IRubyObject object) {
if (getSafeLevel() > 0 && object.isTaint()) {
ThreadContext tc = getCurrentContext();
if (tc.getFrameName() != null) {
throw newSecurityError("Insecure operation - " + tc.getFrameName());
}
throw newSecurityError("Insecure operation: -r");
}
secure(4);
if (!(object instanceof RubyString)) {
throw newTypeError(
"wrong argument type " + object.getMetaClass().getName() + " (expected String)");
}
}
/** rb_define_global_const
*
*/
public void defineGlobalConstant(String name, IRubyObject value) {
objectClass.defineConstant(name, value);
}
public boolean isClassDefined(String name) {
return getModule(name) != null;
}
/**
* A ThreadFactory for when we're using pooled threads; we want to create
* the threads with daemon = true so they don't keep us from shutting down.
*/
public static class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}
}
/**
* This method is called immediately after constructing the Ruby instance.
* The main thread is prepared for execution, all core classes and libraries
* are initialized, and any libraries required on the command line are
* loaded.
*/
private void init() {
// Get the main threadcontext (gets constructed for us)
ThreadContext tc = getCurrentContext();
safeLevel = config.getSafeLevel();
// Construct key services
loadService = config.createLoadService(this);
posix = POSIXFactory.getPOSIX(new JRubyPOSIXHandler(this), RubyInstanceConfig.nativeEnabled);
javaSupport = new JavaSupport(this);
if (RubyInstanceConfig.POOLING_ENABLED) {
Executors.newCachedThreadPool();
executor = new ThreadPoolExecutor(
RubyInstanceConfig.POOL_MIN,
RubyInstanceConfig.POOL_MAX,
RubyInstanceConfig.POOL_TTL,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new DaemonThreadFactory());
}
// initialize the root of the class hierarchy completely
initRoot(tc);
// Construct the top-level execution frame and scope for the main thread
tc.prepareTopLevel(objectClass, topSelf);
// Initialize all the core classes
bootstrap();
// Create global constants and variables
RubyGlobal.createGlobals(tc, this);
// Prepare LoadService and load path
getLoadService().init(config.loadPaths());
// initialize builtin libraries
initBuiltins();
// Require in all libraries specified on command line
for (String scriptName : config.requiredLibraries()) {
RubyKernel.require(getTopSelf(), newString(scriptName), Block.NULL_BLOCK);
}
}
private void bootstrap() {
initCore();
initExceptions();
}
private void initRoot(ThreadContext context) {
// Bootstrap the top of the hierarchy
objectClass = RubyClass.createBootstrapClass(this, "Object", null, RubyObject.OBJECT_ALLOCATOR);
moduleClass = RubyClass.createBootstrapClass(this, "Module", objectClass, RubyModule.MODULE_ALLOCATOR);
classClass = RubyClass.createBootstrapClass(this, "Class", moduleClass, RubyClass.CLASS_ALLOCATOR);
objectClass.setMetaClass(classClass);
moduleClass.setMetaClass(classClass);
classClass.setMetaClass(classClass);
RubyClass metaClass;
metaClass = objectClass.makeMetaClass(classClass);
metaClass = moduleClass.makeMetaClass(metaClass);
metaClass = classClass.makeMetaClass(metaClass);
RubyObject.createObjectClass(this, objectClass);
RubyModule.createModuleClass(this, moduleClass);
RubyClass.createClassClass(this, classClass);
// set constants now that they're initialized
objectClass.setConstant("Object", objectClass);
objectClass.setConstant("Class", classClass);
objectClass.setConstant("Module", moduleClass);
// Initialize Kernel and include into Object
RubyKernel.createKernelModule(this);
objectClass.includeModule(kernelModule);
// Initialize the "dummy" class used as a marker
dummyClass = new RubyClass(this);
dummyClass.freeze(context);
// Object is ready, create top self
topSelf = TopSelfFactory.createTopSelf(this);
}
private void initCore() {
// Pre-create all the core classes potentially referenced during startup
RubyNil.createNilClass(this);
RubyBoolean.createFalseClass(this);
RubyBoolean.createTrueClass(this);
nilObject = new RubyNil(this);
falseObject = new RubyBoolean(this, false);
trueObject = new RubyBoolean(this, true);
RubyComparable.createComparable(this);
RubyEnumerable.createEnumerableModule(this);
RubyString.createStringClass(this);
RubySymbol.createSymbolClass(this);
if (profile.allowClass("ThreadGroup")) {
RubyThreadGroup.createThreadGroupClass(this);
}
if (profile.allowClass("Thread")) {
RubyThread.createThreadClass(this);
}
if (profile.allowClass("Exception")) {
RubyException.createExceptionClass(this);
}
if (profile.allowModule("Precision")) {
RubyPrecision.createPrecisionModule(this);
}
if (profile.allowClass("Numeric")) {
RubyNumeric.createNumericClass(this);
}
if (profile.allowClass("Integer")) {
RubyInteger.createIntegerClass(this);
}
if (profile.allowClass("Fixnum")) {
RubyFixnum.createFixnumClass(this);
}
if (config.getCompatVersion() == CompatVersion.RUBY1_9) {
if (profile.allowClass("Complex")) {
RubyComplex.createComplexClass(this);
}
if (profile.allowClass("Rational")) {
RubyRational.createRationalClass(this);
}
}
if (profile.allowClass("Hash")) {
RubyHash.createHashClass(this);
}
if (profile.allowClass("Array")) {
RubyArray.createArrayClass(this);
}
if (profile.allowClass("Float")) {
RubyFloat.createFloatClass(this);
}
if (profile.allowClass("Bignum")) {
RubyBignum.createBignumClass(this);
}
ioClass = RubyIO.createIOClass(this);
if (profile.allowClass("Struct")) {
RubyStruct.createStructClass(this);
}
if (profile.allowClass("Tms")) {
tmsStruct = RubyStruct.newInstance(structClass, new IRubyObject[]{newString("Tms"), newSymbol("utime"), newSymbol("stime"), newSymbol("cutime"), newSymbol("cstime")}, Block.NULL_BLOCK);
}
if (profile.allowClass("Binding")) {
RubyBinding.createBindingClass(this);
}
// Math depends on all numeric types
if (profile.allowModule("Math")) {
RubyMath.createMathModule(this);
}
if (profile.allowClass("Regexp")) {
RubyRegexp.createRegexpClass(this);
}
if (profile.allowClass("Range")) {
RubyRange.createRangeClass(this);
}
if (profile.allowModule("ObjectSpace")) {
RubyObjectSpace.createObjectSpaceModule(this);
}
if (profile.allowModule("GC")) {
RubyGC.createGCModule(this);
}
if (profile.allowClass("Proc")) {
RubyProc.createProcClass(this);
}
if (profile.allowClass("Method")) {
RubyMethod.createMethodClass(this);
}
if (profile.allowClass("MatchData")) {
RubyMatchData.createMatchDataClass(this);
}
if (profile.allowModule("Marshal")) {
RubyMarshal.createMarshalModule(this);
}
if (profile.allowClass("Dir")) {
RubyDir.createDirClass(this);
}
if (profile.allowModule("FileTest")) {
RubyFileTest.createFileTestModule(this);
}
// depends on IO, FileTest
if (profile.allowClass("File")) {
RubyFile.createFileClass(this);
}
if (profile.allowClass("File::Stat")) {
RubyFileStat.createFileStatClass(this);
}
if (profile.allowModule("Process")) {
RubyProcess.createProcessModule(this);
}
if (profile.allowClass("Time")) {
RubyTime.createTimeClass(this);
}
if (profile.allowClass("UnboundMethod")) {
RubyUnboundMethod.defineUnboundMethodClass(this);
}
if (profile.allowClass("Data")) {
defineClass("Data", objectClass, objectClass.getAllocator());
}
if (!isSecurityRestricted()) {
// Signal uses sun.misc.* classes, this is not allowed
// in the security-sensitive environments
if (profile.allowModule("Signal")) {
RubySignal.createSignal(this);
}
}
if (profile.allowClass("Continuation")) {
RubyContinuation.createContinuation(this);
}
}
private void initExceptions() {
standardError = defineClassIfAllowed("StandardError", exceptionClass);
runtimeError = defineClassIfAllowed("RuntimeError", standardError);
ioError = defineClassIfAllowed("IOError", standardError);
scriptError = defineClassIfAllowed("ScriptError", exceptionClass);
rangeError = defineClassIfAllowed("RangeError", standardError);
signalException = defineClassIfAllowed("SignalException", exceptionClass);
if (profile.allowClass("NameError")) {
nameError = RubyNameError.createNameErrorClass(this, standardError);
nameErrorMessage = RubyNameError.createNameErrorMessageClass(this, nameError);
}
if (profile.allowClass("NoMethodError")) {
noMethodError = RubyNoMethodError.createNoMethodErrorClass(this, nameError);
}
if (profile.allowClass("SystemExit")) {
systemExit = RubySystemExit.createSystemExitClass(this, exceptionClass);
}
if (profile.allowClass("LocalJumpError")) {
localJumpError = RubyLocalJumpError.createLocalJumpErrorClass(this, standardError);
}
if (profile.allowClass("NativeException")) {
nativeException = NativeException.createClass(this, runtimeError);
}
if (profile.allowClass("SystemCallError")) {
systemCallError = RubySystemCallError.createSystemCallErrorClass(this, standardError);
}
fatal = defineClassIfAllowed("Fatal", exceptionClass);
interrupt = defineClassIfAllowed("Interrupt", signalException);
typeError = defineClassIfAllowed("TypeError", standardError);
argumentError = defineClassIfAllowed("ArgumentError", standardError);
indexError = defineClassIfAllowed("IndexError", standardError);
syntaxError = defineClassIfAllowed("SyntaxError", scriptError);
loadError = defineClassIfAllowed("LoadError", scriptError);
notImplementedError = defineClassIfAllowed("NotImplementedError", scriptError);
securityError = defineClassIfAllowed("SecurityError", standardError);
noMemoryError = defineClassIfAllowed("NoMemoryError", exceptionClass);
regexpError = defineClassIfAllowed("RegexpError", standardError);
eofError = defineClassIfAllowed("EOFError", ioError);
threadError = defineClassIfAllowed("ThreadError", standardError);
concurrencyError = defineClassIfAllowed("ConcurrencyError", threadError);
systemStackError = defineClassIfAllowed("SystemStackError", standardError);
zeroDivisionError = defineClassIfAllowed("ZeroDivisionError", standardError);
floatDomainError = defineClassIfAllowed("FloatDomainError", rangeError);
initErrno();
}
private RubyClass defineClassIfAllowed(String name, RubyClass superClass) {
// TODO: should probably apply the null object pattern for a
// non-allowed class, rather than null
if (superClass != null && profile.allowClass(name)) {
return defineClass(name, superClass, superClass.getAllocator());
}
return null;
}
private Map<Integer, RubyClass> errnos = new HashMap<Integer, RubyClass>();
public RubyClass getErrno(int n) {
return errnos.get(n);
}
/**
* Create module Errno's Variables. We have this method since Errno does not have it's
* own java class.
*/
private void initErrno() {
if (profile.allowModule("Errno")) {
errnoModule = defineModule("Errno");
Field[] fields = IErrno.class.getFields();
for (int i = 0; i < fields.length; i++) {
try {
createSysErr(fields[i].getInt(IErrno.class), fields[i].getName());
} catch (IllegalAccessException e) {
throw new RuntimeException("Someone defined a non-public constant in IErrno.java", e);
}
}
}
}
/**
* Creates a system error.
* @param i the error code (will probably use a java exception instead)
* @param name of the error to define.
**/
private void createSysErr(int i, String name) {
if(profile.allowClass(name)) {
RubyClass errno = getErrno().defineClassUnder(name, systemCallError, systemCallError.getAllocator());
errnos.put(i, errno);
errno.defineConstant("Errno", newFixnum(i));
}
}
private void initBuiltins() {
addLazyBuiltin("java.rb", "java", "org.jruby.javasupport.Java");
addLazyBuiltin("jruby.rb", "jruby", "org.jruby.libraries.JRubyLibrary");
addLazyBuiltin("minijava.rb", "minijava", "org.jruby.java.MiniJava");
addLazyBuiltin("jruby/ext.rb", "jruby/ext", "org.jruby.RubyJRuby$ExtLibrary");
addLazyBuiltin("jruby/type.rb", "jruby/type", "org.jruby.RubyJRuby$TypeLibrary");
addLazyBuiltin("iconv.so", "iconv", "org.jruby.libraries.IConvLibrary");
addLazyBuiltin("nkf.so", "nkf", "org.jruby.libraries.NKFLibrary");
addLazyBuiltin("stringio.so", "stringio", "org.jruby.libraries.StringIOLibrary");
addLazyBuiltin("strscan.so", "strscan", "org.jruby.libraries.StringScannerLibrary");
addLazyBuiltin("zlib.so", "zlib", "org.jruby.libraries.ZlibLibrary");
addLazyBuiltin("yaml_internal.rb", "yaml_internal", "org.jruby.libraries.YamlLibrary");
addLazyBuiltin("enumerator.so", "enumerator", "org.jruby.libraries.EnumeratorLibrary");
addLazyBuiltin("generator_internal.rb", "generator_internal", "org.jruby.ext.Generator$Service");
addLazyBuiltin("readline.so", "readline", "org.jruby.ext.Readline$Service");
addLazyBuiltin("thread.so", "thread", "org.jruby.libraries.ThreadLibrary");
addLazyBuiltin("digest.so", "digest", "org.jruby.libraries.DigestLibrary");
addLazyBuiltin("digest.rb", "digest", "org.jruby.libraries.DigestLibrary");
addLazyBuiltin("digest/md5.so", "digest/md5", "org.jruby.libraries.DigestLibrary$MD5");
addLazyBuiltin("digest/rmd160.so", "digest/rmd160", "org.jruby.libraries.DigestLibrary$RMD160");
addLazyBuiltin("digest/sha1.so", "digest/sha1", "org.jruby.libraries.DigestLibrary$SHA1");
addLazyBuiltin("digest/sha2.so", "digest/sha2", "org.jruby.libraries.DigestLibrary$SHA2");
addLazyBuiltin("bigdecimal.so", "bigdecimal", "org.jruby.libraries.BigDecimalLibrary");
addLazyBuiltin("io/wait.so", "io/wait", "org.jruby.libraries.IOWaitLibrary");
addLazyBuiltin("etc.so", "etc", "org.jruby.libraries.EtcLibrary");
addLazyBuiltin("weakref.rb", "weakref", "org.jruby.ext.WeakRef$WeakRefLibrary");
addLazyBuiltin("socket.so", "socket", "org.jruby.ext.socket.RubySocket$Service");
addLazyBuiltin("rbconfig.rb", "rbconfig", "org.jruby.libraries.RbConfigLibrary");
addLazyBuiltin("jruby/serialization.rb", "serialization", "org.jruby.libraries.JRubySerializationLibrary");
addLazyBuiltin("ffi.so", "ffi", "org.jruby.ext.ffi.Factory$Service");
if(RubyInstanceConfig.NATIVE_NET_PROTOCOL) {
addLazyBuiltin("net/protocol.rb", "net/protocol", "org.jruby.libraries.NetProtocolBufferedIOLibrary");
}
if (config.getCompatVersion() == CompatVersion.RUBY1_9) {
addLazyBuiltin("fiber.so", "fiber", "org.jruby.libraries.FiberLibrary");
}
addBuiltinIfAllowed("openssl.so", new Library() {
public void load(Ruby runtime, boolean wrap) throws IOException {
runtime.getLoadService().require("jruby/openssl/stub");
}
});
String[] builtins = {"fcntl", "yaml", "yaml/syck", "jsignal" };
for (String library : builtins) {
addBuiltinIfAllowed(library + ".rb", new BuiltinScript(library));
}
getLoadService().require("builtin/core_ext/symbol");
RubyKernel.autoload(topSelf, newSymbol("Java"), newString("java"));
getLoadService().require("enumerator");
}
private void addLazyBuiltin(String name, String shortName, String className) {
addBuiltinIfAllowed(name, new LateLoadingLibrary(shortName, className, getJRubyClassLoader()));
}
private void addBuiltinIfAllowed(String name, Library lib) {
if(profile.allowBuiltin(name)) {
loadService.addBuiltinLibrary(name,lib);
}
}
Object getRespondToMethod() {
return respondToMethod;
}
void setRespondToMethod(Object rtm) {
this.respondToMethod = rtm;
}
public Object getObjectToYamlMethod() {
return objectToYamlMethod;
}
void setObjectToYamlMethod(Object otym) {
this.objectToYamlMethod = otym;
}
/**
* Retrieve mappings of cached methods to where they have been cached. When a cached
* method needs to be invalidated this map can be used to remove all places it has been
* cached.
*
* @return the mappings of where cached methods have been stored
*/
public CacheMap getCacheMap() {
return cacheMap;
}
/** Getter for property rubyTopSelf.
* @return Value of property rubyTopSelf.
*/
public IRubyObject getTopSelf() {
return topSelf;
}
public void setCurrentDirectory(String dir) {
currentDirectory = dir;
}
public String getCurrentDirectory() {
return currentDirectory;
}
public RubyModule getEtc() {
return etcModule;
}
public void setEtc(RubyModule etcModule) {
this.etcModule = etcModule;
}
public RubyClass getObject() {
return objectClass;
}
public RubyClass getModule() {
return moduleClass;
}
public RubyClass getClassClass() {
return classClass;
}
public RubyModule getKernel() {
return kernelModule;
}
void setKernel(RubyModule kernelModule) {
this.kernelModule = kernelModule;
}
public RubyClass getDummy() {
return dummyClass;
}
public RubyModule getComparable() {
return comparableModule;
}
void setComparable(RubyModule comparableModule) {
this.comparableModule = comparableModule;
}
public RubyClass getNumeric() {
return numericClass;
}
void setNumeric(RubyClass numericClass) {
this.numericClass = numericClass;
}
public RubyClass getFloat() {
return floatClass;
}
void setFloat(RubyClass floatClass) {
this.floatClass = floatClass;
}
public RubyClass getInteger() {
return integerClass;
}
void setInteger(RubyClass integerClass) {
this.integerClass = integerClass;
}
public RubyClass getFixnum() {
return fixnumClass;
}
void setFixnum(RubyClass fixnumClass) {
this.fixnumClass = fixnumClass;
}
public RubyClass getComplex() {
return complexClass;
}
void setComplex(RubyClass complexClass) {
this.complexClass = complexClass;
}
public RubyClass getRational() {
return rationalClass;
}
void setRational(RubyClass rationalClass) {
this.rationalClass = rationalClass;
}
public RubyModule getEnumerable() {
return enumerableModule;
}
void setEnumerable(RubyModule enumerableModule) {
this.enumerableModule = enumerableModule;
}
public RubyModule getEnumerator() {
return enumeratorClass;
}
void setEnumerator(RubyClass enumeratorClass) {
this.enumeratorClass = enumeratorClass;
}
public RubyClass getString() {
return stringClass;
}
void setString(RubyClass stringClass) {
this.stringClass = stringClass;
}
public RubyClass getSymbol() {
return symbolClass;
}
void setSymbol(RubyClass symbolClass) {
this.symbolClass = symbolClass;
}
public RubyClass getArray() {
return arrayClass;
}
void setArray(RubyClass arrayClass) {
this.arrayClass = arrayClass;
}
public RubyClass getHash() {
return hashClass;
}
void setHash(RubyClass hashClass) {
this.hashClass = hashClass;
}
public RubyClass getRange() {
return rangeClass;
}
void setRange(RubyClass rangeClass) {
this.rangeClass = rangeClass;
}
/** Returns the "true" instance from the instance pool.
* @return The "true" instance.
*/
public RubyBoolean getTrue() {
return trueObject;
}
/** Returns the "false" instance from the instance pool.
* @return The "false" instance.
*/
public RubyBoolean getFalse() {
return falseObject;
}
/** Returns the "nil" singleton instance.
* @return "nil"
*/
public IRubyObject getNil() {
return nilObject;
}
public RubyClass getNilClass() {
return nilClass;
}
void setNilClass(RubyClass nilClass) {
this.nilClass = nilClass;
}
public RubyClass getTrueClass() {
return trueClass;
}
void setTrueClass(RubyClass trueClass) {
this.trueClass = trueClass;
}
public RubyClass getFalseClass() {
return falseClass;
}
void setFalseClass(RubyClass falseClass) {
this.falseClass = falseClass;
}
public RubyClass getProc() {
return procClass;
}
void setProc(RubyClass procClass) {
this.procClass = procClass;
}
public RubyClass getBinding() {
return bindingClass;
}
void setBinding(RubyClass bindingClass) {
this.bindingClass = bindingClass;
}
public RubyClass getMethod() {
return methodClass;
}
void setMethod(RubyClass methodClass) {
this.methodClass = methodClass;
}
public RubyClass getUnboundMethod() {
return unboundMethodClass;
}
void setUnboundMethod(RubyClass unboundMethodClass) {
this.unboundMethodClass = unboundMethodClass;
}
public RubyClass getMatchData() {
return matchDataClass;
}
void setMatchData(RubyClass matchDataClass) {
this.matchDataClass = matchDataClass;
}
public RubyClass getRegexp() {
return regexpClass;
}
void setRegexp(RubyClass regexpClass) {
this.regexpClass = regexpClass;
}
public RubyClass getTime() {
return timeClass;
}
void setTime(RubyClass timeClass) {
this.timeClass = timeClass;
}
public RubyModule getMath() {
return mathModule;
}
void setMath(RubyModule mathModule) {
this.mathModule = mathModule;
}
public RubyModule getMarshal() {
return marshalModule;
}
void setMarshal(RubyModule marshalModule) {
this.marshalModule = marshalModule;
}
public RubyClass getBignum() {
return bignumClass;
}
void setBignum(RubyClass bignumClass) {
this.bignumClass = bignumClass;
}
public RubyClass getDir() {
return dirClass;
}
void setDir(RubyClass dirClass) {
this.dirClass = dirClass;
}
public RubyClass getFile() {
return fileClass;
}
void setFile(RubyClass fileClass) {
this.fileClass = fileClass;
}
public RubyClass getFileStat() {
return fileStatClass;
}
void setFileStat(RubyClass fileStatClass) {
this.fileStatClass = fileStatClass;
}
public RubyModule getFileTest() {
return fileTestModule;
}
void setFileTest(RubyModule fileTestModule) {
this.fileTestModule = fileTestModule;
}
public RubyClass getIO() {
return ioClass;
}
void setIO(RubyClass ioClass) {
this.ioClass = ioClass;
}
public RubyClass getThread() {
return threadClass;
}
void setThread(RubyClass threadClass) {
this.threadClass = threadClass;
}
public RubyClass getThreadGroup() {
return threadGroupClass;
}
void setThreadGroup(RubyClass threadGroupClass) {
this.threadGroupClass = threadGroupClass;
}
public RubyThreadGroup getDefaultThreadGroup() {
return defaultThreadGroup;
}
void setDefaultThreadGroup(RubyThreadGroup defaultThreadGroup) {
this.defaultThreadGroup = defaultThreadGroup;
}
public RubyClass getContinuation() {
return continuationClass;
}
void setContinuation(RubyClass continuationClass) {
this.continuationClass = continuationClass;
}
public RubyClass getStructClass() {
return structClass;
}
void setStructClass(RubyClass structClass) {
this.structClass = structClass;
}
public IRubyObject getTmsStruct() {
return tmsStruct;
}
void setTmsStruct(RubyClass tmsStruct) {
this.tmsStruct = tmsStruct;
}
public IRubyObject getPasswdStruct() {
return passwdStruct;
}
void setPasswdStruct(RubyClass passwdStruct) {
this.passwdStruct = passwdStruct;
}
public IRubyObject getGroupStruct() {
return groupStruct;
}
void setGroupStruct(RubyClass groupStruct) {
this.groupStruct = groupStruct;
}
public RubyModule getGC() {
return gcModule;
}
void setGC(RubyModule gcModule) {
this.gcModule = gcModule;
}
public RubyModule getObjectSpaceModule() {
return objectSpaceModule;
}
void setObjectSpaceModule(RubyModule objectSpaceModule) {
this.objectSpaceModule = objectSpaceModule;
}
public RubyModule getProcess() {
return processModule;
}
void setProcess(RubyModule processModule) {
this.processModule = processModule;
}
public RubyClass getProcStatus() {
return procStatusClass;
}
void setProcStatus(RubyClass procStatusClass) {
this.procStatusClass = procStatusClass;
}
public RubyModule getProcUID() {
return procUIDModule;
}
void setProcUID(RubyModule procUIDModule) {
this.procUIDModule = procUIDModule;
}
public RubyModule getProcGID() {
return procGIDModule;
}
void setProcGID(RubyModule procGIDModule) {
this.procGIDModule = procGIDModule;
}
public RubyModule getProcSysModule() {
return procSysModule;
}
void setProcSys(RubyModule procSysModule) {
this.procSysModule = procSysModule;
}
public RubyModule getPrecision() {
return precisionModule;
}
void setPrecision(RubyModule precisionModule) {
this.precisionModule = precisionModule;
}
public RubyModule getErrno() {
return errnoModule;
}
public RubyClass getException() {
return exceptionClass;
}
void setException(RubyClass exceptionClass) {
this.exceptionClass = exceptionClass;
}
public RubyClass getNameError() {
return nameError;
}
public RubyClass getNameErrorMessage() {
return nameErrorMessage;
}
public RubyClass getNoMethodError() {
return noMethodError;
}
public RubyClass getSignalException() {
return signalException;
}
public RubyClass getRangeError() {
return rangeError;
}
public RubyClass getSystemExit() {
return systemExit;
}
public RubyClass getLocalJumpError() {
return localJumpError;
}
public RubyClass getNativeException() {
return nativeException;
}
public RubyClass getSystemCallError() {
return systemCallError;
}
public RubyClass getFatal() {
return fatal;
}
public RubyClass getInterrupt() {
return interrupt;
}
public RubyClass getTypeError() {
return typeError;
}
public RubyClass getArgumentError() {
return argumentError;
}
public RubyClass getIndexError() {
return indexError;
}
public RubyClass getSyntaxError() {
return syntaxError;
}
public RubyClass getStandardError() {
return standardError;
}
public RubyClass getRuntimeError() {
return runtimeError;
}
public RubyClass getIOError() {
return ioError;
}
public RubyClass getLoadError() {
return loadError;
}
public RubyClass getNotImplementedError() {
return notImplementedError;
}
public RubyClass getSecurityError() {
return securityError;
}
public RubyClass getNoMemoryError() {
return noMemoryError;
}
public RubyClass getRegexpError() {
return regexpError;
}
public RubyClass getEOFError() {
return eofError;
}
public RubyClass getThreadError() {
return threadError;
}
public RubyClass getConcurrencyError() {
return concurrencyError;
}
public RubyClass getSystemStackError() {
return systemStackError;
}
public RubyClass getZeroDivisionError() {
return zeroDivisionError;
}
public RubyClass getFloatDomainError() {
return floatDomainError;
}
private RubyHash charsetMap;
public RubyHash getCharsetMap() {
if (charsetMap == null) charsetMap = new RubyHash(this);
return charsetMap;
}
/** Getter for property isVerbose.
* @return Value of property isVerbose.
*/
public IRubyObject getVerbose() {
return verbose;
}
/** Setter for property isVerbose.
* @param verbose New value of property isVerbose.
*/
public void setVerbose(IRubyObject verbose) {
this.verbose = verbose;
}
/** Getter for property isDebug.
* @return Value of property isDebug.
*/
public IRubyObject getDebug() {
return debug;
}
/** Setter for property isDebug.
* @param debug New value of property isDebug.
*/
public void setDebug(IRubyObject debug) {
this.debug = debug;
}
public JavaSupport getJavaSupport() {
return javaSupport;
}
public static ClassLoader getClassLoader() {
// we try to get the classloader that loaded JRuby, falling back on System
ClassLoader loader = Ruby.class.getClassLoader();
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
return loader;
}
public synchronized JRubyClassLoader getJRubyClassLoader() {
// FIXME: Get rid of laziness and handle restricted access elsewhere
if (!Ruby.isSecurityRestricted() && jrubyClassLoader == null) {
jrubyClassLoader = new JRubyClassLoader(config.getLoader());
}
return jrubyClassLoader;
}
/** Defines a global variable
*/
public void defineVariable(final GlobalVariable variable) {
globalVariables.define(variable.name(), new IAccessor() {
public IRubyObject getValue() {
return variable.get();
}
public IRubyObject setValue(IRubyObject newValue) {
return variable.set(newValue);
}
});
}
/** defines a readonly global variable
*
*/
public void defineReadonlyVariable(String name, IRubyObject value) {
globalVariables.defineReadonly(name, new ValueAccessor(value));
}
public Node parseFile(InputStream in, String file, DynamicScope scope) {
return parser.parse(file, in, scope, new ParserConfiguration(0, false, false, true));
}
public Node parseInline(InputStream in, String file, DynamicScope scope) {
return parser.parse(file, in, scope, new ParserConfiguration(0, false, true));
}
public Node parseEval(String content, String file, DynamicScope scope, int lineNumber) {
byte[] bytes;
try {
bytes = content.getBytes(KCode.NONE.getKCode());
} catch (UnsupportedEncodingException e) {
bytes = content.getBytes();
}
return parser.parse(file, new ByteArrayInputStream(bytes), scope,
new ParserConfiguration(lineNumber, false));
}
public Node parse(String content, String file, DynamicScope scope, int lineNumber,
boolean extraPositionInformation) {
byte[] bytes;
try {
bytes = content.getBytes(KCode.NONE.getKCode());
} catch (UnsupportedEncodingException e) {
bytes = content.getBytes();
}
return parser.parse(file, new ByteArrayInputStream(bytes), scope,
new ParserConfiguration(lineNumber, extraPositionInformation, false));
}
public Node parseEval(ByteList content, String file, DynamicScope scope, int lineNumber) {
return parser.parse(file, content, scope, new ParserConfiguration(lineNumber, false));
}
public Node parse(ByteList content, String file, DynamicScope scope, int lineNumber,
boolean extraPositionInformation) {
return parser.parse(file, content, scope,
new ParserConfiguration(lineNumber, extraPositionInformation, false));
}
public ThreadService getThreadService() {
return threadService;
}
public ThreadContext getCurrentContext() {
return threadService.getCurrentContext();
}
/**
* Returns the loadService.
* @return ILoadService
*/
public LoadService getLoadService() {
return loadService;
}
public RubyWarnings getWarnings() {
return warnings;
}
public PrintStream getErrorStream() {
// FIXME: We can't guarantee this will always be a RubyIO...so the old code here is not safe
/*java.io.OutputStream os = ((RubyIO) getGlobalVariables().get("$stderr")).getOutStream();
if(null != os) {
return new PrintStream(os);
} else {
return new PrintStream(new org.jruby.util.SwallowingOutputStream());
}*/
return new PrintStream(new IOOutputStream(getGlobalVariables().get("$stderr")));
}
public InputStream getInputStream() {
return new IOInputStream(getGlobalVariables().get("$stdin"));
}
public PrintStream getOutputStream() {
return new PrintStream(new IOOutputStream(getGlobalVariables().get("$stdout")));
}
public RubyModule getClassFromPath(String path) {
RubyModule c = getObject();
if (path.length() == 0 || path.charAt(0) == '#') {
throw newTypeError("can't retrieve anonymous class " + path);
}
int pbeg = 0, p = 0;
for(int l=path.length(); p<l; ) {
while(p<l && path.charAt(p) != ':') {
p++;
}
String str = path.substring(pbeg, p);
if(p<l && path.charAt(p) == ':') {
if(p+1 < l && path.charAt(p+1) != ':') {
throw newTypeError("undefined class/module " + path.substring(pbeg,p));
}
p += 2;
pbeg = p;
}
IRubyObject cc = c.getConstant(str);
if(!(cc instanceof RubyModule)) {
throw newTypeError("" + path + " does not refer to class/module");
}
c = (RubyModule)cc;
}
return c;
}
/** Prints an error with backtrace to the error stream.
*
* MRI: eval.c - error_print()
*
*/
public void printError(RubyException excp) {
if (excp == null || excp.isNil()) {
return;
}
ThreadContext context = getCurrentContext();
IRubyObject backtrace = excp.callMethod(context, "backtrace");
PrintStream errorStream = getErrorStream();
if (backtrace.isNil() || !(backtrace instanceof RubyArray)) {
if (context.getFile() != null) {
errorStream.print(context.getFile() + ":" + context.getLine());
} else {
errorStream.print(context.getLine());
}
} else if (((RubyArray) backtrace).getLength() == 0) {
printErrorPos(context, errorStream);
} else {
IRubyObject mesg = ((RubyArray) backtrace).first();
if (mesg.isNil()) {
printErrorPos(context, errorStream);
} else {
errorStream.print(mesg);
}
}
RubyClass type = excp.getMetaClass();
String info = excp.toString();
if (type == getRuntimeError() && (info == null || info.length() == 0)) {
errorStream.print(": unhandled exception\n");
} else {
String path = type.getName();
if (info.length() == 0) {
errorStream.print(": " + path + '\n');
} else {
if (path.startsWith("#")) {
path = null;
}
String tail = null;
if (info.indexOf("\n") != -1) {
tail = info.substring(info.indexOf("\n") + 1);
info = info.substring(0, info.indexOf("\n"));
}
errorStream.print(": " + info);
if (path != null) {
errorStream.print(" (" + path + ")\n");
}
if (tail != null) {
errorStream.print(tail + '\n');
}
}
}
excp.printBacktrace(errorStream);
}
private void printErrorPos(ThreadContext context, PrintStream errorStream) {
if (context.getFile() != null) {
if (context.getFrameName() != null) {
errorStream.print(context.getFile() + ":" + context.getLine());
errorStream.print(":in '" + context.getFrameName() + '\'');
} else if (context.getLine() != 0) {
errorStream.print(context.getFile() + ":" + context.getLine());
} else {
errorStream.print(context.getFile());
}
}
}
public void loadFile(String scriptName, InputStream in, boolean wrap) {
IRubyObject self = wrap ? TopSelfFactory.createTopSelf(this) : getTopSelf();
ThreadContext context = getCurrentContext();
String file = context.getFile();
try {
secure(4); /* should alter global state */
context.setFile(scriptName);
context.preNodeEval(objectClass, self, scriptName);
parseFile(in, scriptName, null).interpret(this, context, self, Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
return;
} finally {
context.postNodeEval();
context.setFile(file);
}
}
public void compileAndLoadFile(String filename, InputStream in, boolean wrap) {
IRubyObject self = wrap ? TopSelfFactory.createTopSelf(this) : getTopSelf();
ThreadContext context = getCurrentContext();
String file = context.getFile();
try {
secure(4); /* should alter global state */
context.setFile(filename);
context.preNodeEval(objectClass, self, filename);
Node scriptNode = parseFile(in, filename, null);
Script script = tryCompile(scriptNode, new JRubyClassLoader(jrubyClassLoader));
if (script == null) {
System.err.println("Error, could not compile; pass -J-Djruby.jit.logging.verbose=true for more details");
}
runScript(script);
} catch (JumpException.ReturnJump rj) {
return;
} finally {
context.postNodeEval();
context.setFile(file);
}
}
public void loadScript(Script script) {
IRubyObject self = getTopSelf();
ThreadContext context = getCurrentContext();
try {
secure(4); /* should alter global state */
context.preNodeEval(objectClass, self);
script.load(context, self, IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
return;
} finally {
context.postNodeEval();
}
}
public class CallTraceFuncHook extends EventHook {
private RubyProc traceFunc;
public void setTraceFunc(RubyProc traceFunc) {
this.traceFunc = traceFunc;
}
public void eventHandler(ThreadContext context, String eventName, String file, int line, String name, IRubyObject type) {
if (!context.isWithinTrace()) {
if (file == null) file = "(ruby)";
if (type == null) type = getFalse();
RubyBinding binding = RubyBinding.newBinding(Ruby.this);
context.preTrace();
try {
traceFunc.call(context, new IRubyObject[] {
newString(eventName), // event name
newString(file), // filename
newFixnum(line), // line numbers should be 1-based
name != null ? newSymbol(name) : getNil(),
binding,
type
});
} finally {
context.postTrace();
}
}
}
public boolean isInterestedInEvent(RubyEvent event) {
return true;
}
};
private final CallTraceFuncHook callTraceFuncHook = new CallTraceFuncHook();
public void addEventHook(EventHook hook) {
eventHooks.add(hook);
hasEventHooks = true;
}
public void removeEventHook(EventHook hook) {
eventHooks.remove(hook);
hasEventHooks = !eventHooks.isEmpty();
}
public void setTraceFunction(RubyProc traceFunction) {
removeEventHook(callTraceFuncHook);
if (traceFunction == null) {
return;
}
callTraceFuncHook.setTraceFunc(traceFunction);
addEventHook(callTraceFuncHook);
}
public void callEventHooks(ThreadContext context, RubyEvent event, String file, int line, String name, IRubyObject type) {
for (EventHook eventHook : eventHooks) {
if (eventHook.isInterestedInEvent(event)) {
eventHook.event(context, event, file, line, name, type);
}
}
}
public boolean hasEventHooks() {
return hasEventHooks;
}
public GlobalVariables getGlobalVariables() {
return globalVariables;
}
// For JSR 223 support: see http://scripting.java.net/
public void setGlobalVariables(GlobalVariables globalVariables) {
this.globalVariables = globalVariables;
}
public CallbackFactory callbackFactory(Class<?> type) {
return CallbackFactory.createFactory(this, type);
}
/**
* Push block onto exit stack. When runtime environment exits
* these blocks will be evaluated.
*
* @return the element that was pushed onto stack
*/
public IRubyObject pushExitBlock(RubyProc proc) {
atExitBlocks.push(proc);
return proc;
}
// use this for JRuby-internal finalizers
public void addInternalFinalizer(Finalizable finalizer) {
synchronized (internalFinalizersMutex) {
if (internalFinalizers == null) {
internalFinalizers = new WeakHashMap<Finalizable, Object>();
}
internalFinalizers.put(finalizer, null);
}
}
// this method is for finalizers registered via ObjectSpace
public void addFinalizer(Finalizable finalizer) {
synchronized (finalizersMutex) {
if (finalizers == null) {
finalizers = new WeakHashMap<Finalizable, Object>();
}
finalizers.put(finalizer, null);
}
}
public void removeInternalFinalizer(Finalizable finalizer) {
synchronized (internalFinalizersMutex) {
if (internalFinalizers != null) {
internalFinalizers.remove(finalizer);
}
}
}
public void removeFinalizer(Finalizable finalizer) {
synchronized (finalizersMutex) {
if (finalizers != null) {
finalizers.remove(finalizer);
}
}
}
/**
* Make sure Kernel#at_exit procs get invoked on runtime shutdown.
* This method needs to be explicitly called to work properly.
* I thought about using finalize(), but that did not work and I
* am not sure the runtime will be at a state to run procs by the
* time Ruby is going away. This method can contain any other
* things that need to be cleaned up at shutdown.
*/
public void tearDown() {
int status = 0;
while (!atExitBlocks.empty()) {
RubyProc proc = atExitBlocks.pop();
try {
proc.call(getCurrentContext(), IRubyObject.NULL_ARRAY);
} catch (RaiseException rj) {
RubyException raisedException = rj.getException();
if (!getSystemExit().isInstance(raisedException)) {
status = 1;
printError(raisedException);
} else {
IRubyObject statusObj = raisedException.callMethod(
getCurrentContext(), "status");
if (statusObj != null && !statusObj.isNil()) {
status = RubyNumeric.fix2int(statusObj);
}
}
}
}
if (finalizers != null) {
synchronized (finalizers) {
for (Iterator<Finalizable> finalIter = new ArrayList<Finalizable>(finalizers.keySet()).iterator(); finalIter.hasNext();) {
finalIter.next().finalize();
finalIter.remove();
}
}
}
synchronized (internalFinalizersMutex) {
if (internalFinalizers != null) {
for (Iterator<Finalizable> finalIter = new ArrayList<Finalizable>(
internalFinalizers.keySet()).iterator(); finalIter.hasNext();) {
finalIter.next().finalize();
finalIter.remove();
}
}
}
getThreadService().disposeCurrentThread();
getBeanManager().unregisterCompiler();
getBeanManager().unregisterConfig();
getBeanManager().unregisterClassCache();
getBeanManager().unregisterMethodCache();
if (status != 0) {
throw newSystemExit(status);
}
}
// new factory methods ------------------------------------------------------------------------
public RubyArray newEmptyArray() {
return RubyArray.newEmptyArray(this);
}
public RubyArray newArray() {
return RubyArray.newArray(this);
}
public RubyArray newArrayLight() {
return RubyArray.newArrayLight(this);
}
public RubyArray newArray(IRubyObject object) {
return RubyArray.newArray(this, object);
}
public RubyArray newArray(IRubyObject car, IRubyObject cdr) {
return RubyArray.newArray(this, car, cdr);
}
public RubyArray newArray(IRubyObject[] objects) {
return RubyArray.newArray(this, objects);
}
public RubyArray newArrayNoCopy(IRubyObject[] objects) {
return RubyArray.newArrayNoCopy(this, objects);
}
public RubyArray newArrayNoCopyLight(IRubyObject[] objects) {
return RubyArray.newArrayNoCopyLight(this, objects);
}
public RubyArray newArray(List<IRubyObject> list) {
return RubyArray.newArray(this, list);
}
public RubyArray newArray(int size) {
return RubyArray.newArray(this, size);
}
public RubyBoolean newBoolean(boolean value) {
return RubyBoolean.newBoolean(this, value);
}
public RubyFileStat newFileStat(String filename, boolean lstat) {
return RubyFileStat.newFileStat(this, filename, lstat);
}
public RubyFileStat newFileStat(FileDescriptor descriptor) {
return RubyFileStat.newFileStat(this, descriptor);
}
public RubyFixnum newFixnum(long value) {
return RubyFixnum.newFixnum(this, value);
}
public RubyFixnum newFixnum(int value) {
return RubyFixnum.newFixnum(this, value);
}
public RubyFloat newFloat(double value) {
return RubyFloat.newFloat(this, value);
}
public RubyNumeric newNumeric() {
return RubyNumeric.newNumeric(this);
}
public RubyProc newProc(Block.Type type, Block block) {
if (type != Block.Type.LAMBDA && block.getProcObject() != null) return block.getProcObject();
RubyProc proc = RubyProc.newProc(this, type);
proc.callInit(IRubyObject.NULL_ARRAY, block);
return proc;
}
public RubyProc newBlockPassProc(Block.Type type, Block block) {
if (type != Block.Type.LAMBDA && block.getProcObject() != null) return block.getProcObject();
RubyProc proc = RubyProc.newProc(this, type);
proc.initialize(getCurrentContext(), block);
return proc;
}
public RubyBinding newBinding() {
return RubyBinding.newBinding(this);
}
public RubyBinding newBinding(Binding binding) {
return RubyBinding.newBinding(this, binding);
}
public RubyString newString() {
return RubyString.newString(this, new ByteList());
}
public RubyString newString(String string) {
return RubyString.newString(this, string);
}
public RubyString newString(ByteList byteList) {
return RubyString.newString(this, byteList);
}
@Deprecated
public RubyString newStringShared(ByteList byteList) {
return RubyString.newStringShared(this, byteList);
}
public RubySymbol newSymbol(String name) {
return symbolTable.getSymbol(name);
}
/**
* Faster than {@link #newSymbol(String)} if you already have an interned
* name String. Don't intern your string just to call this version - the
* overhead of interning will more than wipe out any benefit from the faster
* lookup.
*
* @param internedName the symbol name, <em>must</em> be interned! if in
* doubt, call {@link #newSymbol(String)} instead.
* @return the symbol for name
*/
public RubySymbol fastNewSymbol(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
return symbolTable.fastGetSymbol(internedName);
}
public RubyTime newTime(long milliseconds) {
return RubyTime.newTime(this, milliseconds);
}
public RaiseException newRuntimeError(String message) {
return newRaiseException(getRuntimeError(), message);
}
public RaiseException newArgumentError(String message) {
return newRaiseException(getArgumentError(), message);
}
public RaiseException newArgumentError(int got, int expected) {
return newRaiseException(getArgumentError(), "wrong # of arguments(" + got + " for " + expected + ")");
}
public RaiseException newErrnoEBADFError() {
return newRaiseException(getErrno().fastGetClass("EBADF"), "Bad file descriptor");
}
public RaiseException newErrnoENOPROTOOPTError() {
return newRaiseException(getErrno().fastGetClass("ENOPROTOOPT"), "Protocol not available");
}
public RaiseException newErrnoEPIPEError() {
return newRaiseException(getErrno().fastGetClass("EPIPE"), "Broken pipe");
}
public RaiseException newErrnoECONNREFUSEDError() {
return newRaiseException(getErrno().fastGetClass("ECONNREFUSED"), "Connection refused");
}
public RaiseException newErrnoECONNRESETError() {
return newRaiseException(getErrno().fastGetClass("ECONNRESET"), "Connection reset by peer");
}
public RaiseException newErrnoEADDRINUSEError() {
return newRaiseException(getErrno().fastGetClass("EADDRINUSE"), "Address in use");
}
public RaiseException newErrnoEINVALError() {
return newRaiseException(getErrno().fastGetClass("EINVAL"), "Invalid file");
}
public RaiseException newErrnoENOENTError() {
return newRaiseException(getErrno().fastGetClass("ENOENT"), "File not found");
}
public RaiseException newErrnoEACCESError(String message) {
return newRaiseException(getErrno().fastGetClass("EACCES"), message);
}
public RaiseException newErrnoEAGAINError(String message) {
return newRaiseException(getErrno().fastGetClass("EAGAIN"), message);
}
public RaiseException newErrnoEISDirError() {
return newRaiseException(getErrno().fastGetClass("EISDIR"), "Is a directory");
}
public RaiseException newErrnoESPIPEError() {
return newRaiseException(getErrno().fastGetClass("ESPIPE"), "Illegal seek");
}
public RaiseException newErrnoEBADFError(String message) {
return newRaiseException(getErrno().fastGetClass("EBADF"), message);
}
public RaiseException newErrnoEINVALError(String message) {
return newRaiseException(getErrno().fastGetClass("EINVAL"), message);
}
public RaiseException newErrnoENOTDIRError(String message) {
return newRaiseException(getErrno().fastGetClass("ENOTDIR"), message);
}
public RaiseException newErrnoENOTSOCKError(String message) {
return newRaiseException(getErrno().fastGetClass("ENOTSOCK"), message);
}
public RaiseException newErrnoENOENTError(String message) {
return newRaiseException(getErrno().fastGetClass("ENOENT"), message);
}
public RaiseException newErrnoESPIPEError(String message) {
return newRaiseException(getErrno().fastGetClass("ESPIPE"), message);
}
public RaiseException newErrnoEEXISTError(String message) {
return newRaiseException(getErrno().fastGetClass("EEXIST"), message);
}
public RaiseException newErrnoEDOMError(String message) {
return newRaiseException(getErrno().fastGetClass("EDOM"), "Domain error - " + message);
}
public RaiseException newErrnoECHILDError() {
return newRaiseException(getErrno().fastGetClass("ECHILD"), "No child processes");
}
public RaiseException newIndexError(String message) {
return newRaiseException(getIndexError(), message);
}
public RaiseException newSecurityError(String message) {
return newRaiseException(getSecurityError(), message);
}
public RaiseException newSystemCallError(String message) {
return newRaiseException(getSystemCallError(), message);
}
public RaiseException newTypeError(String message) {
return newRaiseException(getTypeError(), message);
}
public RaiseException newThreadError(String message) {
return newRaiseException(getThreadError(), message);
}
public RaiseException newConcurrencyError(String message) {
return newRaiseException(getConcurrencyError(), message);
}
public RaiseException newSyntaxError(String message) {
return newRaiseException(getSyntaxError(), message);
}
public RaiseException newRegexpError(String message) {
return newRaiseException(getRegexpError(), message);
}
public RaiseException newRangeError(String message) {
return newRaiseException(getRangeError(), message);
}
public RaiseException newNotImplementedError(String message) {
return newRaiseException(getNotImplementedError(), message);
}
public RaiseException newInvalidEncoding(String message) {
return newRaiseException(fastGetClass("Iconv").fastGetClass("InvalidEncoding"), message);
}
public RaiseException newNoMethodError(String message, String name, IRubyObject args) {
return new RaiseException(new RubyNoMethodError(this, getNoMethodError(), message, name, args), true);
}
public RaiseException newNameError(String message, String name) {
return newNameError(message, name, null);
}
public RaiseException newNameError(String message, String name, Throwable origException) {
return newNameError(message, name, origException, true);
}
public RaiseException newNameError(String message, String name, Throwable origException, boolean printWhenVerbose) {
if (printWhenVerbose && origException != null && this.getVerbose().isTrue()) {
origException.printStackTrace(getErrorStream());
}
return new RaiseException(new RubyNameError(
this, getNameError(), message, name), true);
}
public RaiseException newLocalJumpError(String reason, IRubyObject exitValue, String message) {
return new RaiseException(new RubyLocalJumpError(this, getLocalJumpError(), message, reason, exitValue), true);
}
public RaiseException newRedoLocalJumpError() {
return new RaiseException(new RubyLocalJumpError(this, getLocalJumpError(), "unexpected redo", "redo", getNil()), true);
}
public RaiseException newLoadError(String message) {
return newRaiseException(getLoadError(), message);
}
public RaiseException newFrozenError(String objectType) {
// TODO: Should frozen error have its own distinct class? If not should more share?
return newRaiseException(getTypeError(), "can't modify frozen " + objectType);
}
public RaiseException newSystemStackError(String message) {
return newRaiseException(getSystemStackError(), message);
}
public RaiseException newSystemExit(int status) {
return new RaiseException(RubySystemExit.newInstance(this, status));
}
public RaiseException newIOError(String message) {
return newRaiseException(getIOError(), message);
}
public RaiseException newStandardError(String message) {
return newRaiseException(getStandardError(), message);
}
public RaiseException newIOErrorFromException(IOException ioe) {
// TODO: this is kinda gross
if(ioe.getMessage() != null) {
if (ioe.getMessage().equals("Broken pipe")) {
throw newErrnoEPIPEError();
} else if (ioe.getMessage().equals("Connection reset by peer")) {
throw newErrnoECONNRESETError();
}
return newRaiseException(getIOError(), ioe.getMessage());
} else {
return newRaiseException(getIOError(), "IO Error");
}
}
public RaiseException newTypeError(IRubyObject receivedObject, RubyClass expectedType) {
return newRaiseException(getTypeError(), "wrong argument type " +
receivedObject.getMetaClass().getRealClass() + " (expected " + expectedType + ")");
}
public RaiseException newEOFError() {
return newRaiseException(getEOFError(), "End of file reached");
}
public RaiseException newEOFError(String message) {
return newRaiseException(getEOFError(), message);
}
public RaiseException newZeroDivisionError() {
return newRaiseException(getZeroDivisionError(), "divided by 0");
}
public RaiseException newFloatDomainError(String message){
return newRaiseException(getFloatDomainError(), message);
}
/**
* @param exceptionClass
* @param message
* @return
*/
private RaiseException newRaiseException(RubyClass exceptionClass, String message) {
RaiseException re = new RaiseException(this, exceptionClass, message, true);
return re;
}
public RubySymbol.SymbolTable getSymbolTable() {
return symbolTable;
}
public void setStackTraces(int stackTraces) {
this.stackTraces = stackTraces;
}
public int getStackTraces() {
return stackTraces;
}
public void setRandomSeed(long randomSeed) {
this.randomSeed = randomSeed;
}
public long getRandomSeed() {
return randomSeed;
}
public Random getRandom() {
return random;
}
public ObjectSpace getObjectSpace() {
return objectSpace;
}
public Map<Integer, WeakReference<ChannelDescriptor>> getDescriptors() {
return descriptors;
}
public long incrementRandomSeedSequence() {
return randomSeedSequence++;
}
public InputStream getIn() {
return in;
}
public PrintStream getOut() {
return out;
}
public PrintStream getErr() {
return err;
}
public boolean isGlobalAbortOnExceptionEnabled() {
return globalAbortOnExceptionEnabled;
}
public void setGlobalAbortOnExceptionEnabled(boolean enable) {
globalAbortOnExceptionEnabled = enable;
}
public boolean isDoNotReverseLookupEnabled() {
return doNotReverseLookupEnabled;
}
public void setDoNotReverseLookupEnabled(boolean b) {
doNotReverseLookupEnabled = b;
}
private ThreadLocal<Map<Object, Object>> inspect = new ThreadLocal<Map<Object, Object>>();
public void registerInspecting(Object obj) {
Map<Object, Object> val = inspect.get();
if (val == null) inspect.set(val = new IdentityHashMap<Object, Object>());
val.put(obj, null);
}
public boolean isInspecting(Object obj) {
Map<Object, Object> val = inspect.get();
return val == null ? false : val.containsKey(obj);
}
public void unregisterInspecting(Object obj) {
Map<Object, Object> val = inspect.get();
if (val != null ) val.remove(obj);
}
public boolean isObjectSpaceEnabled() {
return objectSpaceEnabled;
}
// The method is intentionally not public, since it typically should
// not be used outside of the core.
/* package-private */ void setObjectSpaceEnabled(boolean objectSpaceEnabled) {
this.objectSpaceEnabled = objectSpaceEnabled;
}
public long getStartTime() {
return startTime;
}
public Profile getProfile() {
return profile;
}
public String getJRubyHome() {
return config.getJRubyHome();
}
public void setJRubyHome(String home) {
config.setJRubyHome(home);
}
public RubyInstanceConfig getInstanceConfig() {
return config;
}
/** GET_VM_STATE_VERSION */
public long getGlobalState() {
synchronized(this) {
return globalState;
}
}
/** INC_VM_STATE_VERSION */
public void incGlobalState() {
synchronized(this) {
globalState = (globalState+1) & 0x8fffffff;
}
}
public static boolean isSecurityRestricted() {
return securityRestricted;
}
public static void setSecurityRestricted(boolean restricted) {
securityRestricted = restricted;
}
public POSIX getPosix() {
return posix;
}
public void setRecordSeparatorVar(GlobalVariable recordSeparatorVar) {
this.recordSeparatorVar = recordSeparatorVar;
}
public GlobalVariable getRecordSeparatorVar() {
return recordSeparatorVar;
}
public Set<Script> getJittedMethods() {
return jittedMethods;
}
public ExecutorService getExecutor() {
return executor;
}
public Map<String, DateTimeZone> getLocalTimezoneCache() {
return localTimeZoneCache;
}
private final CacheMap cacheMap;
private final ThreadService threadService;
private Hashtable<Object, Object> runtimeInformation;
private POSIX posix;
private int stackTraces = 0;
private ObjectSpace objectSpace = new ObjectSpace();
private final RubySymbol.SymbolTable symbolTable = new RubySymbol.SymbolTable(this);
private Map<Integer, WeakReference<ChannelDescriptor>> descriptors = new ConcurrentHashMap<Integer, WeakReference<ChannelDescriptor>>();
private long randomSeed = 0;
private long randomSeedSequence = 0;
private Random random = new Random();
private List<EventHook> eventHooks = new Vector<EventHook>();
private boolean hasEventHooks;
private boolean globalAbortOnExceptionEnabled = false;
private boolean doNotReverseLookupEnabled = false;
private volatile boolean objectSpaceEnabled;
private final Set<Script> jittedMethods = Collections.synchronizedSet(new WeakHashSet<Script>());
private static ThreadLocal<Ruby> currentRuntime = new ThreadLocal<Ruby>();
private long globalState = 1;
private int safeLevel = -1;
// Default objects
private IRubyObject topSelf;
private RubyNil nilObject;
private RubyBoolean trueObject;
private RubyBoolean falseObject;
public final RubyFixnum[] fixnumCache = new RubyFixnum[256];
private IRubyObject verbose;
private IRubyObject debug;
private RubyThreadGroup defaultThreadGroup;
/**
* All the core classes we keep hard references to. These are here largely
* so that if someone redefines String or Array we won't start blowing up
* creating strings and arrays internally. They also provide much faster
* access than going through normal hash lookup on the Object class.
*/
private RubyClass
objectClass, moduleClass, classClass, nilClass, trueClass,
falseClass, numericClass, floatClass, integerClass, fixnumClass,
complexClass, rationalClass, enumeratorClass,
arrayClass, hashClass, rangeClass, stringClass, symbolClass,
procClass, bindingClass, methodClass, unboundMethodClass,
matchDataClass, regexpClass, timeClass, bignumClass, dirClass,
fileClass, fileStatClass, ioClass, threadClass, threadGroupClass,
continuationClass, structClass, tmsStruct, passwdStruct,
groupStruct, procStatusClass, exceptionClass, runtimeError, ioError,
scriptError, nameError, nameErrorMessage, noMethodError, signalException,
rangeError, dummyClass, systemExit, localJumpError, nativeException,
systemCallError, fatal, interrupt, typeError, argumentError, indexError,
syntaxError, standardError, loadError, notImplementedError, securityError, noMemoryError,
regexpError, eofError, threadError, concurrencyError, systemStackError, zeroDivisionError, floatDomainError;
/**
* All the core modules we keep direct references to, for quick access and
* to ensure they remain available.
*/
private RubyModule
kernelModule, comparableModule, enumerableModule, mathModule,
marshalModule, etcModule, fileTestModule, gcModule,
objectSpaceModule, processModule, procUIDModule, procGIDModule,
procSysModule, precisionModule, errnoModule;
// record separator var, to speed up io ops that use it
private GlobalVariable recordSeparatorVar;
// former java.lang.System concepts now internalized for MVM
private String currentDirectory;
private long startTime = System.currentTimeMillis();
private RubyInstanceConfig config;
private InputStream in;
private PrintStream out;
private PrintStream err;
// Java support
private JavaSupport javaSupport;
private JRubyClassLoader jrubyClassLoader;
// Management/monitoring
private BeanManager beanManager;
// Compilation
private final JITCompiler jitCompiler;
// Note: this field and the following static initializer
// must be located be in this order!
private volatile static boolean securityRestricted = false;
static {
if (SafePropertyAccessor.isSecurityProtected("jruby.reflection")) {
// can't read non-standard properties
securityRestricted = true;
} else {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkCreateClassLoader();
} catch (SecurityException se) {
// can't create custom classloaders
securityRestricted = true;
}
}
}
}
private Parser parser = new Parser(this);
private LoadService loadService;
private GlobalVariables globalVariables = new GlobalVariables(this);
private RubyWarnings warnings = new RubyWarnings(this);
// Contains a list of all blocks (as Procs) that should be called when
// the runtime environment exits.
private Stack<RubyProc> atExitBlocks = new Stack<RubyProc>();
private Profile profile;
private KCode kcode = KCode.NONE;
// Atomic integers for symbol and method IDs
private AtomicInteger symbolLastId = new AtomicInteger(128);
private AtomicInteger moduleLastId = new AtomicInteger(0);
private Object respondToMethod;
private Object objectToYamlMethod;
private Map<String, DateTimeZone> localTimeZoneCache = new HashMap<String,DateTimeZone>();
/**
* A list of "external" finalizers (the ones, registered via ObjectSpace),
* weakly referenced, to be executed on tearDown.
*/
private Map<Finalizable, Object> finalizers;
/**
* A list of JRuby-internal finalizers, weakly referenced,
* to be executed on tearDown.
*/
private Map<Finalizable, Object> internalFinalizers;
// mutex that controls modifications of user-defined finalizers
private final Object finalizersMutex = new Object();
// mutex that controls modifications of internal finalizers
private final Object internalFinalizersMutex = new Object();
// A thread pool to use for executing this runtime's Ruby threads
private ExecutorService executor;
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.FrameField;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
public class RubyArgsFile {
private static final class ArgsFileData {
private final Ruby runtime;
public ArgsFileData(Ruby runtime) {
this.runtime = runtime;
}
public IRubyObject currentFile;
public int currentLineNumber;
public boolean startedProcessing = false;
public boolean finishedProcessing = false;
public boolean nextArgsFile(ThreadContext context) {
if (finishedProcessing) {
return false;
}
RubyArray args = (RubyArray)runtime.getGlobalVariables().get("$*");
if (args.getLength() == 0) {
if (!startedProcessing) {
currentFile = runtime.getGlobalVariables().get("$stdin");
((RubyString) runtime.getGlobalVariables().get("$FILENAME")).setValue(new ByteList(new byte[]{'-'}));
currentLineNumber = 0;
startedProcessing = true;
return true;
} else {
finishedProcessing = true;
return false;
}
}
IRubyObject arg = args.shift();
RubyString filename = (RubyString)((RubyObject)arg).to_s();
ByteList filenameBytes = filename.getByteList();
((RubyString) runtime.getGlobalVariables().get("$FILENAME")).setValue(filenameBytes);
if (filenameBytes.length() == 1 && filenameBytes.get(0) == '-') {
currentFile = runtime.getGlobalVariables().get("$stdin");
} else {
currentFile = RubyFile.open(context, runtime.getFile(),
new IRubyObject[] {filename.strDup(context.getRuntime())}, Block.NULL_BLOCK);
}
startedProcessing = true;
return true;
}
public static ArgsFileData getDataFrom(IRubyObject recv) {
ArgsFileData data = (ArgsFileData)recv.dataGetStruct();
if(data == null) {
data = new ArgsFileData(recv.getRuntime());
recv.dataWrapStruct(data);
}
return data;
}
}
public static void setCurrentLineNumber(IRubyObject recv, int newLineNumber) {
ArgsFileData.getDataFrom(recv).currentLineNumber = newLineNumber;
}
public static void initArgsFile(Ruby runtime) {
RubyObject argsFile = new RubyObject(runtime, runtime.getObject());
runtime.getEnumerable().extend_object(argsFile);
runtime.defineReadonlyVariable("$<", argsFile);
runtime.defineGlobalConstant("ARGF", argsFile);
RubyClass argfClass = argsFile.getMetaClass();
argfClass.defineAnnotatedMethods(RubyArgsFile.class);
runtime.defineReadonlyVariable("$FILENAME", runtime.newString("-"));
}
@JRubyMethod(name = {"fileno", "to_i"})
public static IRubyObject fileno(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if (data.currentFile == null && !data.nextArgsFile(context)) {
throw context.getRuntime().newArgumentError("no stream");
}
return ((RubyIO) data.currentFile).fileno(context);
}
@JRubyMethod(name = "to_io")
public static IRubyObject to_io(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if (data.currentFile == null && !data.nextArgsFile(context)) {
throw context.getRuntime().newArgumentError("no stream");
}
return data.currentFile;
}
public static IRubyObject internalGets(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
return context.getRuntime().getNil();
}
IRubyObject line = data.currentFile.callMethod(context, "gets", args);
while (line instanceof RubyNil) {
data.currentFile.callMethod(context, "close");
if (!data.nextArgsFile(context)) {
data.currentFile = null;
return line;
}
line = data.currentFile.callMethod(context, "gets", args);
}
data.currentLineNumber++;
context.getRuntime().getGlobalVariables().set("$.", context.getRuntime().newFixnum(data.currentLineNumber));
return line;
}
// ARGF methods
/** Read a line.
*
*/
@JRubyMethod(name = "gets", optional = 1, frame = true, writes = FrameField.LASTLINE)
public static IRubyObject gets(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject result = internalGets(context, recv, args);
if (!result.isNil()) {
context.getCurrentFrame().setLastLine(result);
}
return result;
}
/** Read a line.
*
*/
@JRubyMethod(name = "readline", optional = 1, frame = true, writes = FrameField.LASTLINE)
public static IRubyObject readline(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject line = gets(context, recv, args);
if (line.isNil()) {
throw context.getRuntime().newEOFError();
}
return line;
}
@JRubyMethod(name = "readlines", optional = 1, frame = true)
public static RubyArray readlines(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject[] separatorArgument;
if (args.length > 0) {
if (!context.getRuntime().getNilClass().isInstance(args[0]) &&
!context.getRuntime().getString().isInstance(args[0])) {
throw context.getRuntime().newTypeError(args[0], context.getRuntime().getString());
}
separatorArgument = new IRubyObject[] { args[0] };
} else {
separatorArgument = IRubyObject.NULL_ARRAY;
}
RubyArray result = context.getRuntime().newArray();
IRubyObject line;
while (! (line = internalGets(context, recv, separatorArgument)).isNil()) {
result.append(line);
}
return result;
}
@JRubyMethod(name = "each_byte", frame = true)
public static IRubyObject each_byte(ThreadContext context, IRubyObject recv, Block block) {
IRubyObject bt;
while(!(bt = getc(context, recv)).isNil()) {
block.yield(context, bt);
}
return recv;
}
/** Invoke a block for each line.
*
*/
@JRubyMethod(name = "each_line", alias = {"each"}, optional = 1, frame = true)
public static IRubyObject each_line(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
IRubyObject nextLine = internalGets(context, recv, args);
while (!nextLine.isNil()) {
block.yield(context, nextLine);
nextLine = internalGets(context, recv, args);
}
return recv;
}
@JRubyMethod(name = "file")
public static IRubyObject file(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
return context.getRuntime().getNil();
}
return data.currentFile;
}
@JRubyMethod(name = "skip")
public static IRubyObject skip(IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
data.currentFile = null;
return recv;
}
@JRubyMethod(name = "close")
public static IRubyObject close(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
return recv;
}
data.currentFile = null;
data.currentLineNumber = 0;
return recv;
}
@JRubyMethod(name = "closed?")
public static IRubyObject closed_p(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
return recv;
}
return ((RubyIO)data.currentFile).closed_p(context);
}
@JRubyMethod(name = "binmode")
public static IRubyObject binmode(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
throw context.getRuntime().newArgumentError("no stream");
}
return ((RubyIO)data.currentFile).binmode();
}
@JRubyMethod(name = "lineno")
public static IRubyObject lineno(ThreadContext context, IRubyObject recv) {
return context.getRuntime().newFixnum(ArgsFileData.getDataFrom(recv).currentLineNumber);
}
@JRubyMethod(name = "tell", alias = {"pos"})
public static IRubyObject tell(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
throw context.getRuntime().newArgumentError("no stream to tell");
}
return ((RubyIO)data.currentFile).pos(context);
}
@JRubyMethod(name = "rewind")
public static IRubyObject rewind(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
throw context.getRuntime().newArgumentError("no stream to rewind");
}
return ((RubyIO)data.currentFile).rewind(context);
}
@JRubyMethod(name = {"eof", "eof?"})
public static IRubyObject eof(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if (data.currentFile == null && !data.nextArgsFile(context)) {
return context.getRuntime().getTrue();
}
return ((RubyIO) data.currentFile).eof_p(context);
}
@JRubyMethod(name = "pos=", required = 1)
public static IRubyObject set_pos(ThreadContext context, IRubyObject recv, IRubyObject offset) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
throw context.getRuntime().newArgumentError("no stream to set position");
}
return ((RubyIO)data.currentFile).pos_set(context, offset);
}
@JRubyMethod(name = "seek", required = 1, optional = 1)
public static IRubyObject seek(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
if(data.currentFile == null && !data.nextArgsFile(context)) {
throw context.getRuntime().newArgumentError("no stream to seek");
}
return ((RubyIO)data.currentFile).seek(context, args);
}
@JRubyMethod(name = "lineno=", required = 1)
public static IRubyObject set_lineno(ThreadContext context, IRubyObject recv, IRubyObject line) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
data.currentLineNumber = RubyNumeric.fix2int(line);
return context.getRuntime().getNil();
}
@JRubyMethod(name = "readchar")
public static IRubyObject readchar(ThreadContext context, IRubyObject recv) {
IRubyObject c = getc(context, recv);
if(c.isNil()) throw context.getRuntime().newEOFError();
return c;
}
@JRubyMethod(name = "getc")
public static IRubyObject getc(ThreadContext context, IRubyObject recv) {
ArgsFileData data = ArgsFileData.getDataFrom(recv);
IRubyObject bt;
while(true) {
if(data.currentFile == null && !data.nextArgsFile(context)) {
return context.getRuntime().getNil();
}
if(!(data.currentFile instanceof RubyFile)) {
bt = data.currentFile.callMethod(context,"getc");
} else {
bt = ((RubyIO)data.currentFile).getc();
}
if(bt.isNil()) {
data.currentFile = null;
continue;
}
return bt;
}
}
@JRubyMethod(name = "read", optional = 2)
public static IRubyObject read(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
ArgsFileData data = ArgsFileData.getDataFrom(recv);
IRubyObject tmp, str, length;
long len = 0;
if(args.length > 0) {
length = args[0];
if(args.length > 1) {
str = args[1];
} else {
str = runtime.getNil();
}
} else {
length = str = runtime.getNil();
}
if(!length.isNil()) {
len = RubyNumeric.num2long(length);
}
if(!str.isNil()) {
str = str.convertToString();
((RubyString)str).modify();
((RubyString)str).getByteList().length(0);
args[1] = runtime.getNil();
}
while(true) {
if(data.currentFile == null && !data.nextArgsFile(context)) {
return str;
}
if(!(data.currentFile instanceof RubyIO)) {
tmp = data.currentFile.callMethod(context, "read", args);
} else {
tmp = ((RubyIO)data.currentFile).read(args);
}
if(str.isNil()) {
str = tmp;
} else if(!tmp.isNil()) {
((RubyString)str).append(tmp);
}
if(tmp.isNil() || length.isNil()) {
data.currentFile = null;
continue;
} else if(args.length >= 1) {
if(((RubyString)str).getByteList().length() < len) {
len -= ((RubyString)str).getByteList().length();
args[0] = runtime.newFixnum(len);
continue;
}
}
return str;
}
}
@JRubyMethod(name = "filename", alias = {"path"})
public static RubyString filename(ThreadContext context, IRubyObject recv) {
return (RubyString) context.getRuntime().getGlobalVariables().get("$FILENAME");
}
@JRubyMethod(name = "to_s")
public static IRubyObject to_s(IRubyObject recv) {
return recv.getRuntime().newString("ARGF");
}
}
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Ola Bini <Ola.Bini@ki.se>
* Copyright (C) 2006 Daniel Steer <damian.steer@hp.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.lang.reflect.Array;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.Pack;
/**
* The implementation of the built-in class Array in Ruby.
*
* Concurrency: no synchronization is required among readers, but
* all users must synchronize externally with writers.
*
*/
@JRubyClass(name="Array")
public class RubyArray extends RubyObject implements List {
public static RubyClass createArrayClass(Ruby runtime) {
RubyClass arrayc = runtime.defineClass("Array", runtime.getObject(), ARRAY_ALLOCATOR);
runtime.setArray(arrayc);
arrayc.index = ClassIndex.ARRAY;
arrayc.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyArray;
}
};
arrayc.includeModule(runtime.getEnumerable());
arrayc.defineAnnotatedMethods(RubyArray.class);
return arrayc;
}
private static ObjectAllocator ARRAY_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyArray(runtime, klass);
}
};
@Override
public int getNativeTypeIndex() {
return ClassIndex.ARRAY;
}
private final void concurrentModification() {
throw getRuntime().newConcurrencyError("Detected invalid array contents due to unsynchronized modifications with concurrent users");
}
/** rb_ary_s_create
*
*/
@JRubyMethod(name = "[]", rest = true, frame = true, meta = true)
public static IRubyObject create(IRubyObject klass, IRubyObject[] args, Block block) {
RubyArray arr = (RubyArray) ((RubyClass) klass).allocate();
arr.callInit(IRubyObject.NULL_ARRAY, block);
if (args.length > 0) {
arr.alloc(args.length);
System.arraycopy(args, 0, arr.values, 0, args.length);
arr.realLength = args.length;
}
return arr;
}
/** rb_ary_new2
*
*/
public static final RubyArray newArray(final Ruby runtime, final long len) {
return new RubyArray(runtime, len);
}
public static final RubyArray newArrayLight(final Ruby runtime, final long len) {
return new RubyArray(runtime, len, false);
}
/** rb_ary_new
*
*/
public static final RubyArray newArray(final Ruby runtime) {
return new RubyArray(runtime, ARRAY_DEFAULT_SIZE);
}
/** rb_ary_new
*
*/
public static final RubyArray newArrayLight(final Ruby runtime) {
/* Ruby arrays default to holding 16 elements, so we create an
* ArrayList of the same size if we're not told otherwise
*/
RubyArray arr = new RubyArray(runtime, false);
arr.alloc(ARRAY_DEFAULT_SIZE);
return arr;
}
public static RubyArray newArray(Ruby runtime, IRubyObject obj) {
return new RubyArray(runtime, new IRubyObject[] { obj });
}
public static RubyArray newArrayLight(Ruby runtime, IRubyObject obj) {
return new RubyArray(runtime, new IRubyObject[] { obj }, false);
}
/** rb_assoc_new
*
*/
public static RubyArray newArray(Ruby runtime, IRubyObject car, IRubyObject cdr) {
return new RubyArray(runtime, new IRubyObject[] { car, cdr });
}
public static RubyArray newEmptyArray(Ruby runtime) {
return new RubyArray(runtime, NULL_ARRAY);
}
/** rb_ary_new4, rb_ary_new3
*
*/
public static RubyArray newArray(Ruby runtime, IRubyObject[] args) {
RubyArray arr = new RubyArray(runtime, args.length);
System.arraycopy(args, 0, arr.values, 0, args.length);
arr.realLength = args.length;
return arr;
}
public static RubyArray newArrayNoCopy(Ruby runtime, IRubyObject[] args) {
return new RubyArray(runtime, args);
}
public static RubyArray newArrayNoCopy(Ruby runtime, IRubyObject[] args, int begin) {
return new RubyArray(runtime, args, begin);
}
public static RubyArray newArrayNoCopyLight(Ruby runtime, IRubyObject[] args) {
RubyArray arr = new RubyArray(runtime, false);
arr.values = args;
arr.realLength = args.length;
return arr;
}
public static RubyArray newArray(Ruby runtime, Collection collection) {
RubyArray arr = new RubyArray(runtime, collection.size());
collection.toArray(arr.values);
arr.realLength = arr.values.length;
return arr;
}
public static final int ARRAY_DEFAULT_SIZE = 16;
// volatile to ensure that initial nil-fill is visible to other threads
private volatile IRubyObject[] values;
private static final int TMPLOCK_ARR_F = 1 << 9;
private static final int TMPLOCK_OR_FROZEN_ARR_F = TMPLOCK_ARR_F | FROZEN_F;
private volatile boolean isShared = false;
private int begin = 0;
private int realLength = 0;
/*
* plain internal array assignment
*/
private RubyArray(Ruby runtime, IRubyObject[] vals) {
super(runtime, runtime.getArray());
values = vals;
realLength = vals.length;
}
/*
* plain internal array assignment
*/
private RubyArray(Ruby runtime, IRubyObject[] vals, boolean objectSpace) {
super(runtime, runtime.getArray(), objectSpace);
values = vals;
realLength = vals.length;
}
/*
* plain internal array assignment
*/
private RubyArray(Ruby runtime, IRubyObject[] vals, int begin) {
super(runtime, runtime.getArray());
this.values = vals;
this.begin = begin;
this.realLength = vals.length - begin;
this.isShared = true;
}
/* rb_ary_new2
* just allocates the internal array
*/
private RubyArray(Ruby runtime, long length) {
super(runtime, runtime.getArray());
checkLength(length);
alloc((int) length);
}
private RubyArray(Ruby runtime, long length, boolean objectspace) {
super(runtime, runtime.getArray(), objectspace);
checkLength(length);
alloc((int)length);
}
/* rb_ary_new3, rb_ary_new4
* allocates the internal array of size length and copies the 'length' elements
*/
public RubyArray(Ruby runtime, long length, IRubyObject[] vals) {
super(runtime, runtime.getArray());
checkLength(length);
int ilength = (int) length;
alloc(ilength);
if (ilength > 0 && vals.length > 0) System.arraycopy(vals, 0, values, 0, ilength);
realLength = ilength;
}
/* NEWOBJ and OBJSETUP equivalent
* fastest one, for shared arrays, optional objectspace
*/
private RubyArray(Ruby runtime, boolean objectSpace) {
super(runtime, runtime.getArray(), objectSpace);
}
private RubyArray(Ruby runtime) {
super(runtime, runtime.getArray());
alloc(ARRAY_DEFAULT_SIZE);
}
public RubyArray(Ruby runtime, RubyClass klass) {
super(runtime, klass);
alloc(ARRAY_DEFAULT_SIZE);
}
/* Array constructors taking the MetaClass to fulfil MRI Array subclass behaviour
*
*/
private RubyArray(Ruby runtime, RubyClass klass, int length) {
super(runtime, klass);
alloc(length);
}
private RubyArray(Ruby runtime, RubyClass klass, long length) {
super(runtime, klass);
checkLength(length);
alloc((int)length);
}
private RubyArray(Ruby runtime, RubyClass klass, long length, boolean objectspace) {
super(runtime, klass, objectspace);
checkLength(length);
alloc((int)length);
}
private RubyArray(Ruby runtime, RubyClass klass, boolean objectSpace) {
super(runtime, klass, objectSpace);
}
private RubyArray(Ruby runtime, RubyClass klass, RubyArray original) {
super(runtime, klass);
realLength = original.realLength;
alloc(realLength);
try {
System.arraycopy(original.values, original.begin, values, 0, realLength);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
}
private final IRubyObject[] reserve(int length) {
final IRubyObject[] arr = new IRubyObject[length];
Arrays.fill(arr, getRuntime().getNil());
return arr;
}
private final void alloc(int length) {
final IRubyObject[] newValues = new IRubyObject[length];
Arrays.fill(newValues, getRuntime().getNil());
values = newValues;
}
private final void realloc(int newLength) {
IRubyObject[] reallocated = new IRubyObject[newLength];
Arrays.fill(reallocated, getRuntime().getNil());
try {
System.arraycopy(values, 0, reallocated, 0, newLength > realLength ? realLength : newLength);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
values = reallocated;
}
private final void checkLength(long length) {
if (length < 0) {
throw getRuntime().newArgumentError("negative array size (or size too big)");
}
if (length >= Integer.MAX_VALUE) {
throw getRuntime().newArgumentError("array size too big");
}
}
/** Getter for property list.
* @return Value of property list.
*/
public List getList() {
return Arrays.asList(toJavaArray());
}
public int getLength() {
return realLength;
}
public IRubyObject[] toJavaArray() {
IRubyObject[] copy = reserve(realLength);
try {
System.arraycopy(values, begin, copy, 0, realLength);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
return copy;
}
public IRubyObject[] toJavaArrayUnsafe() {
return !isShared ? values : toJavaArray();
}
public IRubyObject[] toJavaArrayMaybeUnsafe() {
return (!isShared && begin == 0 && values.length == realLength) ? values : toJavaArray();
}
/** rb_ary_make_shared
*
*/
private final RubyArray makeShared(int beg, int len, RubyClass klass) {
return makeShared(beg, len, klass, klass.getRuntime().isObjectSpaceEnabled());
}
/** rb_ary_make_shared
*
*/
private final RubyArray makeShared(int beg, int len, RubyClass klass, boolean objectSpace) {
RubyArray sharedArray = new RubyArray(getRuntime(), klass, objectSpace);
isShared = true;
sharedArray.values = values;
sharedArray.isShared = true;
sharedArray.begin = beg;
sharedArray.realLength = len;
return sharedArray;
}
/** rb_ary_modify_check
*
*/
private final void modifyCheck() {
if ((flags & TMPLOCK_OR_FROZEN_ARR_F) != 0) {
if ((flags & FROZEN_F) != 0) throw getRuntime().newFrozenError("array");
if ((flags & TMPLOCK_ARR_F) != 0) throw getRuntime().newTypeError("can't modify array during iteration");
}
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't modify array");
}
}
/** rb_ary_modify
*
*/
private final void modify() {
modifyCheck();
if (isShared) {
IRubyObject[] vals = reserve(realLength);
isShared = false;
try {
System.arraycopy(values, begin, vals, 0, realLength);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
begin = 0;
values = vals;
}
}
/* ================
* Instance Methods
* ================
*/
/** rb_ary_initialize
*
*/
@JRubyMethod(name = "initialize", required = 0, optional = 2, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) {
int argc = args.length;
Ruby runtime = getRuntime();
if (argc == 0) {
modifyCheck();
realLength = 0;
if (block.isGiven()) runtime.getWarnings().warn(ID.BLOCK_UNUSED, "given block not used");
return this;
}
if (argc == 1 && !(args[0] instanceof RubyFixnum)) {
IRubyObject val = args[0].checkArrayType();
if (!val.isNil()) {
replace(val);
return this;
}
}
long len = RubyNumeric.num2long(args[0]);
if (len < 0) throw runtime.newArgumentError("negative array size");
if (len >= Integer.MAX_VALUE) throw runtime.newArgumentError("array size too big");
int ilen = (int) len;
modify();
if (ilen > values.length) values = reserve(ilen);
if (block.isGiven()) {
if (argc == 2) {
runtime.getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument");
}
for (int i = 0; i < ilen; i++) {
store(i, block.yield(context, new RubyFixnum(runtime, i)));
realLength = i + 1;
}
} else {
try {
Arrays.fill(values, 0, ilen, (argc == 2) ? args[1] : runtime.getNil());
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
realLength = ilen;
}
return this;
}
/** rb_ary_initialize_copy
*
*/
@JRubyMethod(name = {"initialize_copy"}, required = 1, visibility=Visibility.PRIVATE)
@Override
public IRubyObject initialize_copy(IRubyObject orig) {
return this.replace(orig);
}
/** rb_ary_replace
*
*/
@JRubyMethod(name = {"replace"}, required = 1)
public IRubyObject replace(IRubyObject orig) {
modifyCheck();
RubyArray origArr = orig.convertToArray();
if (this == orig) return this;
origArr.isShared = true;
isShared = true;
values = origArr.values;
realLength = origArr.realLength;
begin = origArr.begin;
return this;
}
/** rb_ary_to_s
*
*/
@JRubyMethod(name = "to_s")
@Override
public IRubyObject to_s() {
if (realLength == 0) return RubyString.newEmptyString(getRuntime());
return join(getRuntime().getCurrentContext(), getRuntime().getGlobalVariables().get("$,"));
}
public boolean includes(ThreadContext context, IRubyObject item) {
int begin = this.begin;
for (int i = begin; i < begin + realLength; i++) {
final IRubyObject value;
try {
value = values[i];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
continue;
}
if (equalInternal(context, value, item)) return true;
}
return false;
}
/** rb_ary_hash
*
*/
@JRubyMethod(name = "hash")
public RubyFixnum hash(ThreadContext context) {
int h = realLength;
Ruby runtime = getRuntime();
int begin = this.begin;
for (int i = begin; i < begin + realLength; i++) {
h = (h << 1) | (h < 0 ? 1 : 0);
final IRubyObject value;
try {
value = values[i];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
continue;
}
h ^= RubyNumeric.num2long(value.callMethod(context, MethodIndex.HASH, "hash"));
}
return runtime.newFixnum(h);
}
/** rb_ary_store
*
*/
public final IRubyObject store(long index, IRubyObject value) {
if (index < 0) {
index += realLength;
if (index < 0) {
throw getRuntime().newIndexError("index " + (index - realLength) + " out of array");
}
}
modify();
if (index >= realLength) {
if (index >= values.length) {
long newLength = values.length >> 1;
if (newLength < ARRAY_DEFAULT_SIZE) newLength = ARRAY_DEFAULT_SIZE;
newLength += index;
if (index >= Integer.MAX_VALUE || newLength >= Integer.MAX_VALUE) {
throw getRuntime().newArgumentError("index too big");
}
realloc((int) newLength);
}
realLength = (int) index + 1;
}
try {
values[(int) index] = value;
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
return value;
}
/** rb_ary_elt
*
*/
private final IRubyObject elt(long offset) {
if (offset < 0 || offset >= realLength) {
return getRuntime().getNil();
}
try {
return values[begin + (int)offset];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return getRuntime().getNil();
}
}
/** rb_ary_entry
*
*/
public final IRubyObject entry(long offset) {
return (offset < 0 ) ? elt(offset + realLength) : elt(offset);
}
/** rb_ary_entry
*
*/
public final IRubyObject entry(int offset) {
return (offset < 0 ) ? elt(offset + realLength) : elt(offset);
}
public final IRubyObject eltInternal(int offset) {
return values[begin + offset];
}
public final IRubyObject eltInternalSet(int offset, IRubyObject item) {
return values[begin + offset] = item;
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public IRubyObject fetch(ThreadContext context, IRubyObject[] args, Block block) {
switch (args.length) {
case 1:
return fetch(context, args[0], block);
case 2:
return fetch(context, args[0], args[1], block);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_ary_fetch
*
*/
@JRubyMethod(name = "fetch", frame = true)
public IRubyObject fetch(ThreadContext context, IRubyObject arg0, Block block) {
long index = RubyNumeric.num2long(arg0);
if (index < 0) index += realLength;
if (index < 0 || index >= realLength) {
if (block.isGiven()) return block.yield(context, arg0);
throw getRuntime().newIndexError("index " + index + " out of array");
}
try {
return values[begin + (int) index];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return getRuntime().getNil();
}
}
/** rb_ary_fetch
*
*/
@JRubyMethod(name = "fetch", frame = true)
public IRubyObject fetch(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
if (block.isGiven()) getRuntime().getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument");
long index = RubyNumeric.num2long(arg0);
if (index < 0) index += realLength;
if (index < 0 || index >= realLength) {
if (block.isGiven()) return block.yield(context, arg0);
return arg1;
}
try {
return values[begin + (int) index];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return getRuntime().getNil();
}
}
/** rb_ary_to_ary
*
*/
private static RubyArray aryToAry(IRubyObject obj) {
if (obj instanceof RubyArray) return (RubyArray) obj;
if (obj.respondsTo("to_ary")) return obj.convertToArray();
RubyArray arr = new RubyArray(obj.getRuntime(), false); // possibly should not in object space
arr.alloc(1);
arr.values[0] = obj;
arr.realLength = 1;
return arr;
}
/** rb_ary_splice
*
*/
private final void splice(long beg, long len, IRubyObject rpl) {
if (len < 0) throw getRuntime().newIndexError("negative length (" + len + ")");
if (beg < 0) {
beg += realLength;
if (beg < 0) {
beg -= realLength;
throw getRuntime().newIndexError("index " + beg + " out of array");
}
}
final RubyArray rplArr;
final int rlen;
if (rpl == null || rpl.isNil()) {
rplArr = null;
rlen = 0;
} else {
rplArr = aryToAry(rpl);
rlen = rplArr.realLength;
}
modify();
if (beg >= realLength) {
len = beg + rlen;
if (len >= values.length) {
int tryNewLength = values.length + (values.length >> 1);
realloc(len > tryNewLength ? (int)len : tryNewLength);
}
realLength = (int) len;
} else {
if (beg + len > realLength) len = realLength - beg;
long alen = realLength + rlen - len;
if (alen >= values.length) {
int tryNewLength = values.length + (values.length >> 1);
realloc(alen > tryNewLength ? (int)alen : tryNewLength);
}
if (len != rlen) {
try {
System.arraycopy(values, (int) (beg + len), values, (int) beg + rlen, realLength - (int) (beg + len));
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
realLength = (int) alen;
}
}
if (rlen > 0) {
try {
System.arraycopy(rplArr.values, rplArr.begin, values, (int) beg, rlen);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
}
}
/** rb_ary_splice
*
*/
private final void spliceOne(long beg, long len, IRubyObject rpl) {
if (len < 0) throw getRuntime().newIndexError("negative length (" + len + ")");
if (beg < 0) {
beg += realLength;
if (beg < 0) {
beg -= realLength;
throw getRuntime().newIndexError("index " + beg + " out of array");
}
}
modify();
if (beg >= realLength) {
len = beg + 1;
if (len >= values.length) {
int tryNewLength = values.length + (values.length >> 1);
realloc(len > tryNewLength ? (int)len : tryNewLength);
}
realLength = (int) len;
} else {
if (beg + len > realLength) len = realLength - beg;
int alen = realLength + 1 - (int)len;
if (alen >= values.length) {
int tryNewLength = values.length + (values.length >> 1);
realloc(alen > tryNewLength ? alen : tryNewLength);
}
if (len != 1) {
try {
System.arraycopy(values, (int) (beg + len), values, (int) beg + 1, realLength - (int) (beg + len));
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
realLength = alen;
}
}
try {
values[(int)beg] = rpl;
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
}
@JRubyMethod
public IRubyObject insert() {
throw getRuntime().newArgumentError(0, 1);
}
/** rb_ary_insert
*
*/
@JRubyMethod
public IRubyObject insert(IRubyObject arg) {
return this;
}
/** rb_ary_insert
*
*/
@JRubyMethod
public IRubyObject insert(IRubyObject arg1, IRubyObject arg2) {
long pos = RubyNumeric.num2long(arg1);
if (pos == -1) pos = realLength;
if (pos < 0) pos++;
spliceOne(pos, 0, arg2); // rb_ary_new4
return this;
}
/** rb_ary_insert
*
*/
@JRubyMethod(name = "insert", required = 1, rest = true)
public IRubyObject insert(IRubyObject[] args) {
if (args.length == 1) return this;
long pos = RubyNumeric.num2long(args[0]);
if (pos == -1) pos = realLength;
if (pos < 0) pos++;
RubyArray inserted = new RubyArray(getRuntime(), false);
inserted.values = args;
inserted.begin = 1;
inserted.realLength = args.length - 1;
splice(pos, 0, inserted); // rb_ary_new4
return this;
}
/** rb_ary_dup
*
*/
public final RubyArray aryDup() {
RubyArray dup = new RubyArray(getRuntime(), getMetaClass(), this);
dup.flags |= flags & TAINTED_F; // from DUP_SETUP
// rb_copy_generic_ivar from DUP_SETUP here ...unlikely..
return dup;
}
/** rb_ary_transpose
*
*/
@JRubyMethod(name = "transpose")
public RubyArray transpose() {
RubyArray tmp, result = null;
int alen = realLength;
if (alen == 0) return aryDup();
Ruby runtime = getRuntime();
int elen = -1;
int end = begin + alen;
for (int i = begin; i < end; i++) {
tmp = elt(i).convertToArray();
if (elen < 0) {
elen = tmp.realLength;
result = new RubyArray(runtime, elen);
for (int j = 0; j < elen; j++) {
result.store(j, new RubyArray(runtime, alen));
}
} else if (elen != tmp.realLength) {
throw runtime.newIndexError("element size differs (" + tmp.realLength
+ " should be " + elen + ")");
}
for (int j = 0; j < elen; j++) {
((RubyArray) result.elt(j)).store(i - begin, tmp.elt(j));
}
}
return result;
}
/** rb_values_at (internal)
*
*/
private final IRubyObject values_at(long olen, IRubyObject[] args) {
RubyArray result = new RubyArray(getRuntime(), args.length);
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof RubyFixnum) {
result.append(entry(((RubyFixnum)args[i]).getLongValue()));
continue;
}
long beglen[];
if (!(args[i] instanceof RubyRange)) {
} else if ((beglen = ((RubyRange) args[i]).begLen(olen, 0)) == null) {
continue;
} else {
int beg = (int) beglen[0];
int len = (int) beglen[1];
int end = begin + len;
for (int j = begin; j < end; j++) {
result.append(entry(j + beg));
}
continue;
}
result.append(entry(RubyNumeric.num2long(args[i])));
}
return result;
}
/** rb_values_at
*
*/
@JRubyMethod(name = "values_at", rest = true)
public IRubyObject values_at(IRubyObject[] args) {
return values_at(realLength, args);
}
/** rb_ary_subseq
*
*/
public IRubyObject subseq(long beg, long len) {
if (beg > realLength || beg < 0 || len < 0) return getRuntime().getNil();
if (beg + len > realLength) {
len = realLength - beg;
if (len < 0) len = 0;
}
if (len == 0) return new RubyArray(getRuntime(), getMetaClass(), 0);
return makeShared(begin + (int) beg, (int) len, getMetaClass());
}
/** rb_ary_subseq
*
*/
public IRubyObject subseqLight(long beg, long len) {
if (beg > realLength || beg < 0 || len < 0) return getRuntime().getNil();
if (beg + len > realLength) {
len = realLength - beg;
if (len < 0) len = 0;
}
if (len == 0) return new RubyArray(getRuntime(), getMetaClass(), 0, false);
return makeShared(begin + (int) beg, (int) len, getMetaClass(), false);
}
/** rb_ary_length
*
*/
@JRubyMethod(name = "length", alias = "size")
public RubyFixnum length() {
return getRuntime().newFixnum(realLength);
}
/** rb_ary_push - specialized rb_ary_store
*
*/
@JRubyMethod(name = "<<", required = 1)
public RubyArray append(IRubyObject item) {
modify();
if (realLength == values.length) {
if (realLength == Integer.MAX_VALUE) throw getRuntime().newArgumentError("index too big");
long newLength = values.length + (values.length >> 1);
if ( newLength > Integer.MAX_VALUE ) {
newLength = Integer.MAX_VALUE;
}else if ( newLength < ARRAY_DEFAULT_SIZE ) {
newLength = ARRAY_DEFAULT_SIZE;
}
realloc((int) newLength);
}
try {
values[realLength++] = item;
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
return this;
}
/** rb_ary_push_m
* FIXME: Whis is this named "push_m"?
*/
@JRubyMethod(name = "push", rest = true)
public RubyArray push_m(IRubyObject[] items) {
for (int i = 0; i < items.length; i++) {
append(items[i]);
}
return this;
}
/** rb_ary_pop
*
*/
@JRubyMethod(name = "pop")
public IRubyObject pop() {
modifyCheck();
if (realLength == 0) return getRuntime().getNil();
if (isShared) {
try {
return values[begin + --realLength];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return getRuntime().getNil();
}
} else {
int index = begin + --realLength;
try {
final IRubyObject obj = values[index];
values[index] = getRuntime().getNil();
return obj;
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return getRuntime().getNil();
}
}
}
/** rb_ary_shift
*
*/
@JRubyMethod(name = "shift")
public IRubyObject shift() {
modify();
if (realLength == 0) return getRuntime().getNil();
final IRubyObject obj;
try {
obj = values[begin];
values[begin] = getRuntime().getNil();
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return getRuntime().getNil();
}
isShared = true;
begin++;
realLength--;
return obj;
}
/** rb_ary_unshift
*
*/
public RubyArray unshift(IRubyObject item) {
modify();
if (realLength == values.length) {
int newLength = values.length >> 1;
if (newLength < ARRAY_DEFAULT_SIZE) newLength = ARRAY_DEFAULT_SIZE;
newLength += values.length;
realloc(newLength);
}
try {
System.arraycopy(values, 0, values, 1, realLength);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
realLength++;
values[0] = item;
return this;
}
/** rb_ary_unshift_m
*
*/
@JRubyMethod(name = "unshift", rest = true)
public RubyArray unshift_m(IRubyObject[] items) {
long len = realLength;
if (items.length == 0) return this;
store(len + items.length - 1, getRuntime().getNil());
try {
// it's safe to use zeroes here since modified by store()
System.arraycopy(values, 0, values, items.length, (int) len);
System.arraycopy(items, 0, values, 0, items.length);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
return this;
}
/** rb_ary_includes
*
*/
@JRubyMethod(name = "include?", required = 1)
public RubyBoolean include_p(ThreadContext context, IRubyObject item) {
return context.getRuntime().newBoolean(includes(context, item));
}
/** rb_ary_frozen_p
*
*/
@JRubyMethod(name = "frozen?")
@Override
public RubyBoolean frozen_p(ThreadContext context) {
return context.getRuntime().newBoolean(isFrozen() || (flags & TMPLOCK_ARR_F) != 0);
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public IRubyObject aref(IRubyObject[] args) {
switch (args.length) {
case 1:
return aref(args[0]);
case 2:
return aref(args[0], args[1]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_ary_aref
*/
@JRubyMethod(name = {"[]", "slice"})
public IRubyObject aref(IRubyObject arg0) {
if (arg0 instanceof RubyFixnum) return entry(((RubyFixnum)arg0).getLongValue());
if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index");
long[] beglen;
if (!(arg0 instanceof RubyRange)) {
} else if ((beglen = ((RubyRange) arg0).begLen(realLength, 0)) == null) {
return getRuntime().getNil();
} else {
return subseq(beglen[0], beglen[1]);
}
return entry(RubyNumeric.num2long(arg0));
}
/** rb_ary_aref
*/
@JRubyMethod(name = {"[]", "slice"})
public IRubyObject aref(IRubyObject arg0, IRubyObject arg1) {
if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index");
long beg = RubyNumeric.num2long(arg0);
if (beg < 0) beg += realLength;
return subseq(beg, RubyNumeric.num2long(arg1));
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public IRubyObject aset(IRubyObject[] args) {
switch (args.length) {
case 2:
return aset(args[0], args[1]);
case 3:
return aset(args[0], args[1], args[2]);
default:
throw getRuntime().newArgumentError("wrong number of arguments (" + args.length + " for 2)");
}
}
/** rb_ary_aset
*
*/
@JRubyMethod(name = "[]=")
public IRubyObject aset(IRubyObject arg0, IRubyObject arg1) {
if (arg0 instanceof RubyFixnum) {
store(((RubyFixnum)arg0).getLongValue(), arg1);
return arg1;
}
if (arg0 instanceof RubyRange) {
long[] beglen = ((RubyRange) arg0).begLen(realLength, 1);
splice(beglen[0], beglen[1], arg1);
return arg1;
}
if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index");
store(RubyNumeric.num2long(arg0), arg1);
return arg1;
}
/** rb_ary_aset
*
*/
@JRubyMethod(name = "[]=")
public IRubyObject aset(IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
if (arg0 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as array index");
if (arg1 instanceof RubySymbol) throw getRuntime().newTypeError("Symbol as subarray length");
splice(RubyNumeric.num2long(arg0), RubyNumeric.num2long(arg1), arg2);
return arg2;
}
/** rb_ary_at
*
*/
@JRubyMethod(name = "at", required = 1)
public IRubyObject at(IRubyObject pos) {
return entry(RubyNumeric.num2long(pos));
}
/** rb_ary_concat
*
*/
@JRubyMethod(name = "concat", required = 1)
public RubyArray concat(IRubyObject obj) {
RubyArray ary = obj.convertToArray();
if (ary.realLength > 0) splice(realLength, 0, ary);
return this;
}
/** inspect_ary
*
*/
private IRubyObject inspectAry(ThreadContext context) {
ByteList buffer = new ByteList();
buffer.append('[');
boolean tainted = isTaint();
for (int i = 0; i < realLength; i++) {
if (i > 0) buffer.append(',').append(' ');
RubyString str = inspect(context, values[begin + i]);
if (str.isTaint()) tainted = true;
buffer.append(str.getByteList());
}
buffer.append(']');
RubyString str = getRuntime().newString(buffer);
if (tainted) str.setTaint(true);
return str;
}
/** rb_ary_inspect
*
*/
@JRubyMethod(name = "inspect")
@Override
public IRubyObject inspect() {
if (realLength == 0) return getRuntime().newString("[]");
if (getRuntime().isInspecting(this)) return getRuntime().newString("[...]");
try {
getRuntime().registerInspecting(this);
return inspectAry(getRuntime().getCurrentContext());
} finally {
getRuntime().unregisterInspecting(this);
}
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public IRubyObject first(IRubyObject[] args) {
switch (args.length) {
case 0:
return first();
case 1:
return first(args[0]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 0, 1);
return null; // not reached
}
}
/** rb_ary_first
*
*/
@JRubyMethod(name = "first")
public IRubyObject first() {
if (realLength == 0) return getRuntime().getNil();
return values[begin];
}
/** rb_ary_first
*
*/
@JRubyMethod(name = "first")
public IRubyObject first(IRubyObject arg0) {
long n = RubyNumeric.num2long(arg0);
if (n > realLength) {
n = realLength;
} else if (n < 0) {
throw getRuntime().newArgumentError("negative array size (or size too big)");
}
return makeShared(begin, (int) n, getRuntime().getArray());
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public IRubyObject last(IRubyObject[] args) {
switch (args.length) {
case 0:
return last();
case 1:
return last(args[0]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 0, 1);
return null; // not reached
}
}
/** rb_ary_last
*
*/
@JRubyMethod(name = "last")
public IRubyObject last() {
if (realLength == 0) return getRuntime().getNil();
return values[begin + realLength - 1];
}
/** rb_ary_last
*
*/
@JRubyMethod(name = "last")
public IRubyObject last(IRubyObject arg0) {
long n = RubyNumeric.num2long(arg0);
if (n > realLength) {
n = realLength;
} else if (n < 0) {
throw getRuntime().newArgumentError("negative array size (or size too big)");
}
return makeShared(begin + realLength - (int) n, (int) n, getRuntime().getArray());
}
/** rb_ary_each
*
*/
@JRubyMethod(name = "each", frame = true)
public IRubyObject each(ThreadContext context, Block block) {
for (int i = 0; i < realLength; i++) {
block.yield(context, values[begin + i]);
}
return this;
}
/** rb_ary_each_index
*
*/
@JRubyMethod(name = "each_index", frame = true)
public IRubyObject each_index(ThreadContext context, Block block) {
Ruby runtime = getRuntime();
for (int i = 0; i < realLength; i++) {
block.yield(context, runtime.newFixnum(i));
}
return this;
}
/** rb_ary_reverse_each
*
*/
@JRubyMethod(name = "reverse_each", frame = true)
public IRubyObject reverse_each(ThreadContext context, Block block) {
int len = realLength;
while(len-- > 0) {
block.yield(context, values[begin + len]);
if (realLength < len) len = realLength;
}
return this;
}
private IRubyObject inspectJoin(ThreadContext context, RubyArray tmp, IRubyObject sep) {
Ruby runtime = getRuntime();
// If already inspecting, there is no need to register/unregister again.
if (runtime.isInspecting(this)) {
return tmp.join(context, sep);
}
try {
runtime.registerInspecting(this);
return tmp.join(context, sep);
} finally {
runtime.unregisterInspecting(this);
}
}
/** rb_ary_join
*
*/
public RubyString join(ThreadContext context, IRubyObject sep) {
final Ruby runtime = getRuntime();
if (realLength == 0) return RubyString.newEmptyString(getRuntime());
boolean taint = isTaint() || sep.isTaint();
long len = 1;
for (int i = begin; i < begin + realLength; i++) {
IRubyObject value;
try {
value = values[i];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return runtime.newString("");
}
IRubyObject tmp = value.checkStringType();
len += tmp.isNil() ? 10 : ((RubyString) tmp).getByteList().length();
}
RubyString strSep = null;
if (!sep.isNil()) {
sep = strSep = sep.convertToString();
len += strSep.getByteList().length() * (realLength - 1);
}
ByteList buf = new ByteList((int)len);
for (int i = begin; i < begin + realLength; i++) {
IRubyObject tmp;
try {
tmp = values[i];
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
return runtime.newString("");
}
if (tmp instanceof RubyString) {
// do nothing
} else if (tmp instanceof RubyArray) {
if (runtime.isInspecting(tmp)) {
tmp = runtime.newString("[...]");
} else {
tmp = inspectJoin(context, (RubyArray)tmp, sep);
}
} else {
tmp = RubyString.objAsString(context, tmp);
}
if (i > begin && !sep.isNil()) buf.append(strSep.getByteList());
buf.append(tmp.asString().getByteList());
if (tmp.isTaint()) taint = true;
}
RubyString result = runtime.newString(buf);
if (taint) result.setTaint(true);
return result;
}
/** rb_ary_join_m
*
*/
@JRubyMethod(name = "join", optional = 1)
public RubyString join_m(ThreadContext context, IRubyObject[] args) {
int argc = args.length;
IRubyObject sep = (argc == 1) ? args[0] : getRuntime().getGlobalVariables().get("$,");
return join(context, sep);
}
/** rb_ary_to_a
*
*/
@JRubyMethod(name = "to_a")
@Override
public RubyArray to_a() {
if(getMetaClass() != getRuntime().getArray()) {
RubyArray dup = new RubyArray(getRuntime(), getRuntime().isObjectSpaceEnabled());
isShared = true;
dup.isShared = true;
dup.values = values;
dup.realLength = realLength;
dup.begin = begin;
return dup;
}
return this;
}
@JRubyMethod(name = "to_ary")
public IRubyObject to_ary() {
return this;
}
@Override
public RubyArray convertToArray() {
return this;
}
@Override
public IRubyObject checkArrayType(){
return this;
}
/** rb_ary_equal
*
*/
@JRubyMethod(name = "==", required = 1)
@Override
public IRubyObject op_equal(ThreadContext context, IRubyObject obj) {
if (this == obj) return getRuntime().getTrue();
if (!(obj instanceof RubyArray)) {
if (!obj.respondsTo("to_ary")) {
return getRuntime().getFalse();
} else {
if (equalInternal(context, obj.callMethod(context, "to_ary"), this)) return getRuntime().getTrue();
return getRuntime().getFalse();
}
}
RubyArray ary = (RubyArray) obj;
if (realLength != ary.realLength) return getRuntime().getFalse();
Ruby runtime = getRuntime();
for (long i = 0; i < realLength; i++) {
if (!equalInternal(context, elt(i), ary.elt(i))) return runtime.getFalse();
}
return runtime.getTrue();
}
/** rb_ary_eql
*
*/
@JRubyMethod(name = "eql?", required = 1)
public RubyBoolean eql_p(ThreadContext context, IRubyObject obj) {
if (this == obj) return getRuntime().getTrue();
if (!(obj instanceof RubyArray)) return getRuntime().getFalse();
RubyArray ary = (RubyArray) obj;
if (realLength != ary.realLength) return getRuntime().getFalse();
Ruby runtime = getRuntime();
for (int i = 0; i < realLength; i++) {
if (!eqlInternal(context, elt(i), ary.elt(i))) return runtime.getFalse();
}
return runtime.getTrue();
}
/** rb_ary_compact_bang
*
*/
@JRubyMethod(name = "compact!")
public IRubyObject compact_bang() {
modify();
int p = 0;
int t = 0;
int end = p + realLength;
while (t < end) {
if (values[t].isNil()) {
t++;
} else {
values[p++] = values[t++];
}
}
if (realLength == p) return getRuntime().getNil();
realloc(p);
realLength = p;
return this;
}
/** rb_ary_compact
*
*/
@JRubyMethod(name = "compact")
public IRubyObject compact() {
RubyArray ary = aryDup();
ary.compact_bang();
return ary;
}
/** rb_ary_empty_p
*
*/
@JRubyMethod(name = "empty?")
public IRubyObject empty_p() {
return realLength == 0 ? getRuntime().getTrue() : getRuntime().getFalse();
}
/** rb_ary_clear
*
*/
@JRubyMethod(name = "clear")
public IRubyObject rb_clear() {
modifyCheck();
if(isShared) {
alloc(ARRAY_DEFAULT_SIZE);
isShared = true;
} else if (values.length > ARRAY_DEFAULT_SIZE << 1){
alloc(ARRAY_DEFAULT_SIZE << 1);
} else {
final int begin = this.begin;
try {
Arrays.fill(values, begin, begin + realLength, getRuntime().getNil());
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
}
begin = 0;
realLength = 0;
return this;
}
/** rb_ary_fill
*
*/
@JRubyMethod(name = "fill", optional = 3, frame = true)
public IRubyObject fill(ThreadContext context, IRubyObject[] args, Block block) {
IRubyObject item = null;
IRubyObject begObj = null;
IRubyObject lenObj = null;
int argc = args.length;
if (block.isGiven()) {
Arity.checkArgumentCount(getRuntime(), args, 0, 2);
item = null;
begObj = argc > 0 ? args[0] : null;
lenObj = argc > 1 ? args[1] : null;
argc++;
} else {
Arity.checkArgumentCount(getRuntime(), args, 1, 3);
item = args[0];
begObj = argc > 1 ? args[1] : null;
lenObj = argc > 2 ? args[2] : null;
}
int beg = 0, end = 0, len = 0;
switch (argc) {
case 1:
beg = 0;
len = realLength;
break;
case 2:
if (begObj instanceof RubyRange) {
long[] beglen = ((RubyRange) begObj).begLen(realLength, 1);
beg = (int) beglen[0];
len = (int) beglen[1];
break;
}
/* fall through */
case 3:
beg = begObj.isNil() ? 0 : RubyNumeric.num2int(begObj);
if (beg < 0) {
beg = realLength + beg;
if (beg < 0) beg = 0;
}
len = (lenObj == null || lenObj.isNil()) ? realLength - beg : RubyNumeric.num2int(lenObj);
// TODO: In MRI 1.9, an explicit check for negative length is
// added here. IndexError is raised when length is negative.
// See [ruby-core:12953] for more details.
//
// New note: This is actually under re-evaluation,
// see [ruby-core:17483].
break;
}
modify();
// See [ruby-core:17483]
if (len < 0) {
return this;
}
if (len > Integer.MAX_VALUE - beg) {
throw getRuntime().newArgumentError("argument too big");
}
end = beg + len;
if (end > realLength) {
if (end >= values.length) realloc(end);
realLength = end;
}
if (block.isGiven()) {
Ruby runtime = getRuntime();
for (int i = beg; i < end; i++) {
IRubyObject v = block.yield(context, runtime.newFixnum(i));
if (i >= realLength) break;
try {
values[i] = v;
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
}
} else {
if (len > 0) {
try {
Arrays.fill(values, beg, beg + len, item);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
}
}
return this;
}
/** rb_ary_index
*
*/
@JRubyMethod(name = "index", required = 1)
public IRubyObject index(ThreadContext context, IRubyObject obj) {
Ruby runtime = getRuntime();
for (int i = begin; i < begin + realLength; i++) {
if (equalInternal(context, values[i], obj)) return runtime.newFixnum(i - begin);
}
return runtime.getNil();
}
/** rb_ary_rindex
*
*/
@JRubyMethod(name = "rindex", required = 1)
public IRubyObject rindex(ThreadContext context, IRubyObject obj) {
Ruby runtime = getRuntime();
int i = realLength;
while (i-- > 0) {
if (i > realLength) {
i = realLength;
continue;
}
if (equalInternal(context, values[begin + i], obj)) return getRuntime().newFixnum(i);
}
return runtime.getNil();
}
/** rb_ary_indexes
*
*/
@JRubyMethod(name = {"indexes", "indices"}, required = 1, rest = true)
public IRubyObject indexes(IRubyObject[] args) {
getRuntime().getWarnings().warn(ID.DEPRECATED_METHOD, "Array#indexes is deprecated; use Array#values_at", "Array#indexes", "Array#values_at");
RubyArray ary = new RubyArray(getRuntime(), args.length);
IRubyObject[] arefArgs = new IRubyObject[1];
for (int i = 0; i < args.length; i++) {
arefArgs[0] = args[i];
ary.append(aref(arefArgs));
}
return ary;
}
/** rb_ary_reverse_bang
*
*/
@JRubyMethod(name = "reverse!")
public IRubyObject reverse_bang() {
modify();
final int realLength = this.realLength;
final IRubyObject[] values = this.values;
try {
if (realLength > 1) {
int p1 = 0;
int p2 = p1 + realLength - 1;
while (p1 < p2) {
final IRubyObject tmp = values[p1];
values[p1++] = values[p2];
values[p2--] = tmp;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
return this;
}
/** rb_ary_reverse_m
*
*/
@JRubyMethod(name = "reverse")
public IRubyObject reverse() {
return aryDup().reverse_bang();
}
/** rb_ary_collect
*
*/
@JRubyMethod(name = {"collect", "map"}, frame = true)
public RubyArray collect(ThreadContext context, Block block) {
Ruby runtime = getRuntime();
if (!block.isGiven()) return new RubyArray(getRuntime(), runtime.getArray(), this);
RubyArray collect = new RubyArray(runtime, realLength);
for (int i = begin; i < begin + realLength; i++) {
collect.append(block.yield(context, values[i]));
}
return collect;
}
/** rb_ary_collect_bang
*
*/
@JRubyMethod(name = {"collect!", "map!"}, frame = true)
public RubyArray collect_bang(ThreadContext context, Block block) {
modify();
for (int i = 0, len = realLength; i < len; i++) {
store(i, block.yield(context, values[begin + i]));
}
return this;
}
/** rb_ary_select
*
*/
@JRubyMethod(name = "select", frame = true)
public RubyArray select(ThreadContext context, Block block) {
Ruby runtime = getRuntime();
RubyArray result = new RubyArray(runtime, realLength);
if (isShared) {
for (int i = begin; i < begin + realLength; i++) {
if (block.yield(context, values[i]).isTrue()) result.append(elt(i - begin));
}
} else {
for (int i = 0; i < realLength; i++) {
if (block.yield(context, values[i]).isTrue()) result.append(elt(i));
}
}
return result;
}
/** rb_ary_delete
*
*/
@JRubyMethod(name = "delete", required = 1, frame = true)
public IRubyObject delete(ThreadContext context, IRubyObject item, Block block) {
int i2 = 0;
Ruby runtime = getRuntime();
for (int i1 = 0; i1 < realLength; i1++) {
IRubyObject e = values[begin + i1];
if (equalInternal(context, e, item)) continue;
if (i1 != i2) store(i2, e);
i2++;
}
if (realLength == i2) {
if (block.isGiven()) return block.yield(context, item);
return runtime.getNil();
}
modify();
final int realLength = this.realLength;
final int begin = this.begin;
final IRubyObject[] values = this.values;
if (realLength > i2) {
try {
Arrays.fill(values, begin + i2, begin + realLength, getRuntime().getNil());
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
this.realLength = i2;
if (i2 << 1 < values.length && values.length > ARRAY_DEFAULT_SIZE) realloc(i2 << 1);
}
return item;
}
/** rb_ary_delete_at
*
*/
private final IRubyObject delete_at(int pos) {
int len = realLength;
if (pos >= len) return getRuntime().getNil();
if (pos < 0) pos += len;
if (pos < 0) return getRuntime().getNil();
modify();
IRubyObject obj = values[pos];
try {
System.arraycopy(values, pos + 1, values, pos, len - (pos + 1));
values[realLength-1] = getRuntime().getNil();
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
realLength--;
return obj;
}
/** rb_ary_delete_at_m
*
*/
@JRubyMethod(name = "delete_at", required = 1)
public IRubyObject delete_at(IRubyObject obj) {
return delete_at((int) RubyNumeric.num2long(obj));
}
/** rb_ary_reject_bang
*
*/
@JRubyMethod(name = "reject", frame = true)
public IRubyObject reject(ThreadContext context, Block block) {
RubyArray ary = aryDup();
ary.reject_bang(context, block);
return ary;
}
/** rb_ary_reject_bang
*
*/
@JRubyMethod(name = "reject!", frame = true)
public IRubyObject reject_bang(ThreadContext context, Block block) {
int i2 = 0;
modify();
for (int i1 = 0; i1 < realLength; i1++) {
IRubyObject v = values[i1];
if (block.yield(context, v).isTrue()) continue;
if (i1 != i2) store(i2, v);
i2++;
}
if (realLength == i2) return getRuntime().getNil();
if (i2 < realLength) {
try {
Arrays.fill(values, i2, realLength, getRuntime().getNil());
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
realLength = i2;
}
return this;
}
/** rb_ary_delete_if
*
*/
@JRubyMethod(name = "delete_if", frame = true)
public IRubyObject delete_if(ThreadContext context, Block block) {
reject_bang(context, block);
return this;
}
/** rb_ary_zip
*
*/
@JRubyMethod(name = "zip", optional = 1, rest = true, frame = true)
public IRubyObject zip(ThreadContext context, IRubyObject[] args, Block block) {
for (int i = 0; i < args.length; i++) {
args[i] = args[i].convertToArray();
}
Ruby runtime = getRuntime();
if (block.isGiven()) {
for (int i = 0; i < realLength; i++) {
RubyArray tmp = new RubyArray(runtime, args.length + 1);
tmp.append(elt(i));
for (int j = 0; j < args.length; j++) {
tmp.append(((RubyArray) args[j]).elt(i));
}
block.yield(context, tmp);
}
return runtime.getNil();
}
int len = realLength;
RubyArray result = new RubyArray(runtime, len);
for (int i = 0; i < len; i++) {
RubyArray tmp = new RubyArray(runtime, args.length + 1);
tmp.append(elt(i));
for (int j = 0; j < args.length; j++) {
tmp.append(((RubyArray) args[j]).elt(i));
}
result.append(tmp);
}
return result;
}
/** rb_ary_cmp
*
*/
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(ThreadContext context, IRubyObject obj) {
RubyArray ary2 = obj.convertToArray();
int len = realLength;
if (len > ary2.realLength) len = ary2.realLength;
Ruby runtime = getRuntime();
for (int i = 0; i < len; i++) {
IRubyObject v = elt(i).callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", ary2.elt(i));
if (!(v instanceof RubyFixnum) || ((RubyFixnum) v).getLongValue() != 0) return v;
}
len = realLength - ary2.realLength;
if (len == 0) return RubyFixnum.zero(runtime);
if (len > 0) return RubyFixnum.one(runtime);
return RubyFixnum.minus_one(runtime);
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public IRubyObject slice_bang(IRubyObject[] args) {
switch (args.length) {
case 1:
return slice_bang(args[0]);
case 2:
return slice_bang(args[0], args[1]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_ary_slice_bang
*
*/
@JRubyMethod(name = "slice!")
public IRubyObject slice_bang(IRubyObject arg0) {
if (arg0 instanceof RubyRange) {
long[] beglen = ((RubyRange) arg0).begLen(realLength, 1);
long pos = beglen[0];
long len = beglen[1];
if (pos < 0) pos = realLength + pos;
arg0 = subseq(pos, len);
splice(pos, len, null);
return arg0;
}
return delete_at((int) RubyNumeric.num2long(arg0));
}
/** rb_ary_slice_bang
*
*/
@JRubyMethod(name = "slice!")
public IRubyObject slice_bang(IRubyObject arg0, IRubyObject arg1) {
long pos = RubyNumeric.num2long(arg0);
long len = RubyNumeric.num2long(arg1);
if (pos < 0) pos = realLength + pos;
arg1 = subseq(pos, len);
splice(pos, len, null);
return arg1;
}
/** rb_ary_assoc
*
*/
@JRubyMethod(name = "assoc", required = 1)
public IRubyObject assoc(ThreadContext context, IRubyObject key) {
Ruby runtime = getRuntime();
for (int i = begin; i < begin + realLength; i++) {
IRubyObject v = values[i];
if (v instanceof RubyArray) {
RubyArray arr = (RubyArray)v;
if (arr.realLength > 0 && equalInternal(context, arr.values[arr.begin], key)) return arr;
}
}
return runtime.getNil();
}
/** rb_ary_rassoc
*
*/
@JRubyMethod(name = "rassoc", required = 1)
public IRubyObject rassoc(ThreadContext context, IRubyObject value) {
Ruby runtime = getRuntime();
for (int i = begin; i < begin + realLength; i++) {
IRubyObject v = values[i];
if (v instanceof RubyArray) {
RubyArray arr = (RubyArray)v;
if (arr.realLength > 1 && equalInternal(context, arr.values[arr.begin + 1], value)) return arr;
}
}
return runtime.getNil();
}
/** flatten
*
*/
private final int flatten(ThreadContext context, int index, RubyArray ary2, RubyArray memo) {
int i = index;
int n;
int lim = index + ary2.realLength;
IRubyObject id = ary2.id();
if (memo.includes(context, id)) throw getRuntime().newArgumentError("tried to flatten recursive array");
memo.append(id);
splice(index, 1, ary2);
while (i < lim) {
IRubyObject tmp = elt(i).checkArrayType();
if (!tmp.isNil()) {
n = flatten(context, i, (RubyArray) tmp, memo);
i += n;
lim += n;
}
i++;
}
memo.pop();
return lim - index - 1; /* returns number of increased items */
}
/** rb_ary_flatten_bang
*
*/
@JRubyMethod(name = "flatten!")
public IRubyObject flatten_bang(ThreadContext context) {
int i = 0;
RubyArray memo = null;
while (i < realLength) {
IRubyObject ary2 = values[begin + i];
IRubyObject tmp = ary2.checkArrayType();
if (!tmp.isNil()) {
if (memo == null) {
memo = new RubyArray(getRuntime(), false);
memo.values = reserve(ARRAY_DEFAULT_SIZE);
}
i += flatten(context, i, (RubyArray) tmp, memo);
}
i++;
}
if (memo == null) return getRuntime().getNil();
return this;
}
/** rb_ary_flatten
*
*/
@JRubyMethod(name = "flatten")
public IRubyObject flatten(ThreadContext context) {
RubyArray ary = aryDup();
ary.flatten_bang(context);
return ary;
}
/** rb_ary_nitems
*
*/
@JRubyMethod(name = "nitems")
public IRubyObject nitems() {
int n = 0;
for (int i = begin; i < begin + realLength; i++) {
if (!values[i].isNil()) n++;
}
return getRuntime().newFixnum(n);
}
/** rb_ary_plus
*
*/
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus(IRubyObject obj) {
RubyArray y = obj.convertToArray();
int len = realLength + y.realLength;
RubyArray z = new RubyArray(getRuntime(), len);
try {
System.arraycopy(values, begin, z.values, 0, realLength);
System.arraycopy(y.values, y.begin, z.values, realLength, y.realLength);
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
z.realLength = len;
return z;
}
/** rb_ary_times
*
*/
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_times(ThreadContext context, IRubyObject times) {
IRubyObject tmp = times.checkStringType();
if (!tmp.isNil()) return join(context, tmp);
long len = RubyNumeric.num2long(times);
if (len == 0) return new RubyArray(getRuntime(), getMetaClass(), 0);
if (len < 0) throw getRuntime().newArgumentError("negative argument");
if (Long.MAX_VALUE / len < realLength) {
throw getRuntime().newArgumentError("argument too big");
}
len *= realLength;
RubyArray ary2 = new RubyArray(getRuntime(), getMetaClass(), len);
ary2.realLength = (int) len;
try {
for (int i = 0; i < len; i += realLength) {
System.arraycopy(values, begin, ary2.values, i, realLength);
}
} catch (ArrayIndexOutOfBoundsException e) {
concurrentModification();
}
ary2.infectBy(this);
return ary2;
}
/** ary_make_hash
*
*/
private final RubyHash makeHash(RubyArray ary2) {
RubyHash hash = new RubyHash(getRuntime(), false);
int begin = this.begin;
for (int i = begin; i < begin + realLength; i++) {
hash.fastASet(values[i], NEVER);
}
if (ary2 != null) {
begin = ary2.begin;
for (int i = begin; i < begin + ary2.realLength; i++) {
hash.fastASet(ary2.values[i], NEVER);
}
}
return hash;
}
/** rb_ary_uniq_bang
*
*/
@JRubyMethod(name = "uniq!")
public IRubyObject uniq_bang() {
RubyHash hash = makeHash(null);
if (realLength == hash.size()) return getRuntime().getNil();
int j = 0;
for (int i = 0; i < realLength; i++) {
IRubyObject v = elt(i);
if (hash.fastDelete(v)) store(j++, v);
}
realLength = j;
return this;
}
/** rb_ary_uniq
*
*/
@JRubyMethod(name = "uniq")
public IRubyObject uniq() {
RubyArray ary = aryDup();
ary.uniq_bang();
return ary;
}
/** rb_ary_diff
*
*/
@JRubyMethod(name = "-", required = 1)
public IRubyObject op_diff(IRubyObject other) {
RubyHash hash = other.convertToArray().makeHash(null);
RubyArray ary3 = new RubyArray(getRuntime());
int begin = this.begin;
for (int i = begin; i < begin + realLength; i++) {
if (hash.fastARef(values[i]) != null) continue;
ary3.append(elt(i - begin));
}
return ary3;
}
/** rb_ary_and
*
*/
@JRubyMethod(name = "&", required = 1)
public IRubyObject op_and(IRubyObject other) {
RubyArray ary2 = other.convertToArray();
RubyHash hash = ary2.makeHash(null);
RubyArray ary3 = new RubyArray(getRuntime(),
realLength < ary2.realLength ? realLength : ary2.realLength);
for (int i = 0; i < realLength; i++) {
IRubyObject v = elt(i);
if (hash.fastDelete(v)) ary3.append(v);
}
return ary3;
}
/** rb_ary_or
*
*/
@JRubyMethod(name = "|", required = 1)
public IRubyObject op_or(IRubyObject other) {
RubyArray ary2 = other.convertToArray();
RubyHash set = makeHash(ary2);
RubyArray ary3 = new RubyArray(getRuntime(), realLength + ary2.realLength);
for (int i = 0; i < realLength; i++) {
IRubyObject v = elt(i);
if (set.fastDelete(v)) ary3.append(v);
}
for (int i = 0; i < ary2.realLength; i++) {
IRubyObject v = ary2.elt(i);
if (set.fastDelete(v)) ary3.append(v);
}
return ary3;
}
/** rb_ary_sort
*
*/
@JRubyMethod(name = "sort", frame = true)
public RubyArray sort(Block block) {
RubyArray ary = aryDup();
ary.sort_bang(block);
return ary;
}
/** rb_ary_sort_bang
*
*/
@JRubyMethod(name = "sort!", frame = true)
public RubyArray sort_bang(Block block) {
modify();
if (realLength > 1) {
flags |= TMPLOCK_ARR_F;
try {
if (block.isGiven()) {
Arrays.sort(values, 0, realLength, new BlockComparator(block));
} else {
Arrays.sort(values, 0, realLength, new DefaultComparator());
}
} finally {
flags &= ~TMPLOCK_ARR_F;
}
}
return this;
}
final class BlockComparator implements Comparator {
private Block block;
public BlockComparator(Block block) {
this.block = block;
}
public int compare(Object o1, Object o2) {
ThreadContext context = getRuntime().getCurrentContext();
IRubyObject obj1 = (IRubyObject) o1;
IRubyObject obj2 = (IRubyObject) o2;
IRubyObject ret = block.yield(context, getRuntime().newArray(obj1, obj2), null, null, true);
int n = RubyComparable.cmpint(context, ret, obj1, obj2);
//TODO: ary_sort_check should be done here
return n;
}
}
static final class DefaultComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 instanceof RubyFixnum && o2 instanceof RubyFixnum) {
return compareFixnums(o1, o2);
}
if (o1 instanceof RubyString && o2 instanceof RubyString) {
return ((RubyString) o1).op_cmp((RubyString) o2);
}
//TODO: ary_sort_check should be done here
return compareOthers((IRubyObject)o1, (IRubyObject)o2);
}
private int compareFixnums(Object o1, Object o2) {
long a = ((RubyFixnum) o1).getLongValue();
long b = ((RubyFixnum) o2).getLongValue();
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
}
private int compareOthers(IRubyObject o1, IRubyObject o2) {
ThreadContext context = o1.getRuntime().getCurrentContext();
IRubyObject ret = o1.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", o2);
int n = RubyComparable.cmpint(context, ret, o1, o2);
//TODO: ary_sort_check should be done here
return n;
}
}
public static void marshalTo(RubyArray array, MarshalStream output) throws IOException {
output.registerLinkTarget(array);
output.writeInt(array.getList().size());
for (Iterator iter = array.getList().iterator(); iter.hasNext();) {
output.dumpObject((IRubyObject) iter.next());
}
}
public static RubyArray unmarshalFrom(UnmarshalStream input) throws IOException {
RubyArray result = input.getRuntime().newArray();
input.registerLinkTarget(result);
int size = input.unmarshalInt();
for (int i = 0; i < size; i++) {
result.append(input.unmarshalObject());
}
return result;
}
/**
* @see org.jruby.util.Pack#pack
*/
@JRubyMethod(name = "pack", required = 1)
public RubyString pack(ThreadContext context, IRubyObject obj) {
RubyString iFmt = RubyString.objAsString(context, obj);
return Pack.pack(getRuntime(), this, iFmt.getByteList());
}
@Override
public Class getJavaClass() {
return List.class;
}
// Satisfy java.util.List interface (for Java integration)
public int size() {
return realLength;
}
public boolean isEmpty() {
return realLength == 0;
}
public boolean contains(Object element) {
return indexOf(element) != -1;
}
public Object[] toArray() {
Object[] array = new Object[realLength];
for (int i = begin; i < realLength; i++) {
array[i - begin] = JavaUtil.convertRubyToJava(values[i]);
}
return array;
}
public Object[] toArray(final Object[] arg) {
Object[] array = arg;
if (array.length < realLength) {
Class type = array.getClass().getComponentType();
array = (Object[]) Array.newInstance(type, realLength);
}
int length = realLength - begin;
for (int i = 0; i < length; i++) {
array[i] = JavaUtil.convertRubyToJava(values[i + begin]);
}
return array;
}
public boolean add(Object element) {
append(JavaUtil.convertJavaToRuby(getRuntime(), element));
return true;
}
public boolean remove(Object element) {
IRubyObject deleted = delete(getRuntime().getCurrentContext(), JavaUtil.convertJavaToRuby(getRuntime(), element), Block.NULL_BLOCK);
return deleted.isNil() ? false : true; // TODO: is this correct ?
}
public boolean containsAll(Collection c) {
for (Iterator iter = c.iterator(); iter.hasNext();) {
if (indexOf(iter.next()) == -1) {
return false;
}
}
return true;
}
public boolean addAll(Collection c) {
for (Iterator iter = c.iterator(); iter.hasNext();) {
add(iter.next());
}
return !c.isEmpty();
}
public boolean addAll(int index, Collection c) {
Iterator iter = c.iterator();
for (int i = index; iter.hasNext(); i++) {
add(i, iter.next());
}
return !c.isEmpty();
}
public boolean removeAll(Collection c) {
boolean listChanged = false;
for (Iterator iter = c.iterator(); iter.hasNext();) {
if (remove(iter.next())) {
listChanged = true;
}
}
return listChanged;
}
public boolean retainAll(Collection c) {
boolean listChanged = false;
for (Iterator iter = iterator(); iter.hasNext();) {
Object element = iter.next();
if (!c.contains(element)) {
remove(element);
listChanged = true;
}
}
return listChanged;
}
public Object get(int index) {
return JavaUtil.convertRubyToJava((IRubyObject) elt(index), Object.class);
}
public Object set(int index, Object element) {
return store(index, JavaUtil.convertJavaToRuby(getRuntime(), element));
}
// TODO: make more efficient by not creating IRubyArray[]
public void add(int index, Object element) {
insert(new IRubyObject[]{RubyFixnum.newFixnum(getRuntime(), index), JavaUtil.convertJavaToRuby(getRuntime(), element)});
}
public Object remove(int index) {
return JavaUtil.convertRubyToJava(delete_at(index), Object.class);
}
public int indexOf(Object element) {
int begin = this.begin;
if (element != null) {
IRubyObject convertedElement = JavaUtil.convertJavaToRuby(getRuntime(), element);
for (int i = begin; i < begin + realLength; i++) {
if (convertedElement.equals(values[i])) {
return i;
}
}
}
return -1;
}
public int lastIndexOf(Object element) {
int begin = this.begin;
if (element != null) {
IRubyObject convertedElement = JavaUtil.convertJavaToRuby(getRuntime(), element);
for (int i = begin + realLength - 1; i >= begin; i--) {
if (convertedElement.equals(values[i])) {
return i;
}
}
}
return -1;
}
public class RubyArrayConversionIterator implements Iterator {
protected int index = 0;
protected int last = -1;
public boolean hasNext() {
return index < realLength;
}
public Object next() {
IRubyObject element = elt(index);
last = index++;
return JavaUtil.convertRubyToJava(element, Object.class);
}
public void remove() {
if (last == -1) throw new IllegalStateException();
delete_at(last);
if (last < index) index--;
last = -1;
}
}
public Iterator iterator() {
return new RubyArrayConversionIterator();
}
final class RubyArrayConversionListIterator extends RubyArrayConversionIterator implements ListIterator {
public RubyArrayConversionListIterator() {
}
public RubyArrayConversionListIterator(int index) {
this.index = index;
}
public boolean hasPrevious() {
return index >= 0;
}
public Object previous() {
return JavaUtil.convertRubyToJava((IRubyObject) elt(last = --index), Object.class);
}
public int nextIndex() {
return index;
}
public int previousIndex() {
return index - 1;
}
public void set(Object obj) {
if (last == -1) throw new IllegalStateException();
store(last, JavaUtil.convertJavaToRuby(getRuntime(), obj));
}
public void add(Object obj) {
insert(new IRubyObject[] { RubyFixnum.newFixnum(getRuntime(), index++), JavaUtil.convertJavaToRuby(getRuntime(), obj) });
last = -1;
}
}
public ListIterator listIterator() {
return new RubyArrayConversionListIterator();
}
public ListIterator listIterator(int index) {
return new RubyArrayConversionListIterator(index);
}
// TODO: list.subList(from, to).clear() is supposed to clear the sublist from the list.
// How can we support this operation?
public List subList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > size() || fromIndex > toIndex) {
throw new IndexOutOfBoundsException();
}
IRubyObject subList = subseq(fromIndex, toIndex - fromIndex + 1);
return subList.isNil() ? null : (List) subList;
}
public void clear() {
rb_clear();
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyConstant;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
@JRubyClass(name="BigDecimal", parent="Numeric")
public class RubyBigDecimal extends RubyNumeric {
private static final ObjectAllocator BIGDECIMAL_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyBigDecimal(runtime, klass);
}
};
@JRubyConstant
public final static int ROUND_DOWN = BigDecimal.ROUND_DOWN;
@JRubyConstant
public final static int ROUND_CEILING = BigDecimal.ROUND_CEILING;
@JRubyConstant
public final static int ROUND_UP = BigDecimal.ROUND_UP;
@JRubyConstant
public final static int ROUND_HALF_DOWN = BigDecimal.ROUND_HALF_DOWN;
@JRubyConstant
public final static int ROUND_HALF_EVEN = BigDecimal.ROUND_HALF_EVEN;
@JRubyConstant
public final static int ROUND_HALF_UP = BigDecimal.ROUND_HALF_UP;
@JRubyConstant
public final static int ROUND_FLOOR = BigDecimal.ROUND_FLOOR;
@JRubyConstant
public final static int SIGN_POSITIVE_INFINITE=3;
@JRubyConstant
public final static int EXCEPTION_OVERFLOW=1;
@JRubyConstant
public final static int SIGN_POSITIVE_ZERO=1;
@JRubyConstant
public final static int EXCEPTION_ALL=255;
@JRubyConstant
public final static int SIGN_NEGATIVE_FINITE=-2;
@JRubyConstant
public final static int EXCEPTION_UNDERFLOW=4;
@JRubyConstant
public final static int SIGN_NaN=0;
@JRubyConstant
public final static int BASE=10000;
@JRubyConstant
public final static int ROUND_MODE=256;
@JRubyConstant
public final static int SIGN_POSITIVE_FINITE=2;
@JRubyConstant
public final static int EXCEPTION_INFINITY=1;
@JRubyConstant
public final static int SIGN_NEGATIVE_INFINITE=-3;
@JRubyConstant
public final static int EXCEPTION_ZERODIVIDE=1;
@JRubyConstant
public final static int SIGN_NEGATIVE_ZERO=-1;
@JRubyConstant
public final static int EXCEPTION_NaN=2;
// Static constants
private static final BigDecimal TWO = new BigDecimal(2);
private static final double SQRT_10 = 3.162277660168379332;
public static RubyClass createBigDecimal(Ruby runtime) {
RubyClass result = runtime.defineClass("BigDecimal",runtime.getNumeric(), BIGDECIMAL_ALLOCATOR);
CallbackFactory callbackFactory = runtime.callbackFactory(RubyBigDecimal.class);
runtime.getKernel().defineAnnotatedMethods(BigDecimalKernelMethods.class);
result.setInternalModuleVariable("vpPrecLimit", RubyFixnum.zero(runtime));
result.setInternalModuleVariable("vpExceptionMode", RubyFixnum.zero(runtime));
result.setInternalModuleVariable("vpRoundingMode", runtime.newFixnum(ROUND_HALF_UP));
result.defineAnnotatedMethods(RubyBigDecimal.class);
result.defineAnnotatedConstants(RubyBigDecimal.class);
return result;
}
private boolean isNaN = false;
private int infinitySign = 0;
private int zeroSign = 0;
private BigDecimal value;
public BigDecimal getValue() {
return value;
}
public RubyBigDecimal(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
public RubyBigDecimal(Ruby runtime, BigDecimal value) {
super(runtime, runtime.fastGetClass("BigDecimal"));
this.value = value;
}
public static class BigDecimalKernelMethods {
@JRubyMethod(name = "BigDecimal", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject newBigDecimal(IRubyObject recv, IRubyObject[] args) {
return RubyBigDecimal.newBigDecimal(recv, args, Block.NULL_BLOCK);
}
}
public static RubyBigDecimal newBigDecimal(IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
return newInstance(recv.getRuntime().fastGetClass("BigDecimal"), args);
}
@JRubyMethod(name = "ver", meta = true)
public static IRubyObject ver(IRubyObject recv) {
return recv.getRuntime().newString("1.0.1");
}
@JRubyMethod(name = "_dump", optional = 1, frame = true)
public IRubyObject dump(IRubyObject[] args, Block unusedBlock) {
RubyString precision = RubyString.newUnicodeString(args[0].getRuntime(), "0:");
RubyString str = this.asString();
return precision.append(str);
}
@JRubyMethod(name = "_load", required = 1, frame = true, meta = true)
public static RubyBigDecimal load(IRubyObject recv, IRubyObject from, Block block) {
RubyBigDecimal rubyBigDecimal = (RubyBigDecimal) (((RubyClass)recv).allocate());
String precisionAndValue = from.convertToString().asJavaString();
String value = precisionAndValue.substring(precisionAndValue.indexOf(":")+1);
rubyBigDecimal.value = new BigDecimal(value);
return rubyBigDecimal;
}
@JRubyMethod(name = "double_fig", meta = true)
public static IRubyObject double_fig(IRubyObject recv) {
return recv.getRuntime().newFixnum(20);
}
@JRubyMethod(name = "limit", optional = 1, meta = true)
public static IRubyObject limit(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
RubyModule c = (RubyModule)recv;
IRubyObject nCur = c.searchInternalModuleVariable("vpPrecLimit");
if (args.length > 0) {
IRubyObject arg = args[0];
if (!arg.isNil()) {
if (!(arg instanceof RubyFixnum)) {
throw runtime.newTypeError(arg, runtime.getFixnum());
}
if (0 > ((RubyFixnum)arg).getLongValue()) {
throw runtime.newArgumentError("argument must be positive");
}
c.setInternalModuleVariable("vpPrecLimit", arg);
}
}
return nCur;
}
@JRubyMethod(name = "mode", required = 1, optional = 1, meta = true)
public static IRubyObject mode(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
// FIXME: I doubt any of the constants referenced in this method
// are ever redefined -- should compare to the known values, rather
// than do an expensive constant lookup.
Ruby runtime = recv.getRuntime();
RubyClass clazz = runtime.fastGetClass("BigDecimal");
RubyModule c = (RubyModule)recv;
args = Arity.scanArgs(runtime, args, 1, 1);
IRubyObject mode = args[0];
IRubyObject value = args[1];
if (!(mode instanceof RubyFixnum)) {
throw runtime.newTypeError("wrong argument type " + mode.getMetaClass() + " (expected Fixnum)");
}
long longMode = ((RubyFixnum)mode).getLongValue();
long EXCEPTION_ALL = ((RubyFixnum)clazz.fastGetConstant("EXCEPTION_ALL")).getLongValue();
if ((longMode & EXCEPTION_ALL) != 0) {
if (value.isNil()) {
return c.searchInternalModuleVariable("vpExceptionMode");
}
if (!(value.isNil()) && !(value instanceof RubyBoolean)) {
throw runtime.newTypeError("second argument must be true or false");
}
RubyFixnum currentExceptionMode = (RubyFixnum)c.searchInternalModuleVariable("vpExceptionMode");
RubyFixnum newExceptionMode = new RubyFixnum(runtime, currentExceptionMode.getLongValue());
RubyFixnum EXCEPTION_INFINITY = (RubyFixnum)clazz.fastGetConstant("EXCEPTION_INFINITY");
if ((longMode & EXCEPTION_INFINITY.getLongValue()) != 0) {
newExceptionMode = (value.isTrue()) ? (RubyFixnum)currentExceptionMode.callCoerced(context, "|", EXCEPTION_INFINITY)
: (RubyFixnum)currentExceptionMode.callCoerced(context, "&", new RubyFixnum(runtime, ~(EXCEPTION_INFINITY).getLongValue()));
}
RubyFixnum EXCEPTION_NaN = (RubyFixnum)clazz.fastGetConstant("EXCEPTION_NaN");
if ((longMode & EXCEPTION_NaN.getLongValue()) != 0) {
newExceptionMode = (value.isTrue()) ? (RubyFixnum)currentExceptionMode.callCoerced(context, "|", EXCEPTION_NaN)
: (RubyFixnum)currentExceptionMode.callCoerced(context, "&", new RubyFixnum(runtime, ~(EXCEPTION_NaN).getLongValue()));
}
c.setInternalModuleVariable("vpExceptionMode", newExceptionMode);
return newExceptionMode;
}
long ROUND_MODE = ((RubyFixnum)clazz.fastGetConstant("ROUND_MODE")).getLongValue();
if (longMode == ROUND_MODE) {
if (value.isNil()) {
return c.searchInternalModuleVariable("vpRoundingMode");
}
if (!(value instanceof RubyFixnum)) {
throw runtime.newTypeError("wrong argument type " + mode.getMetaClass() + " (expected Fixnum)");
}
RubyFixnum roundingMode = (RubyFixnum)value;
if (roundingMode == clazz.fastGetConstant("ROUND_UP") ||
roundingMode == clazz.fastGetConstant("ROUND_DOWN") ||
roundingMode == clazz.fastGetConstant("ROUND_FLOOR") ||
roundingMode == clazz.fastGetConstant("ROUND_CEILING") ||
roundingMode == clazz.fastGetConstant("ROUND_HALF_UP") ||
roundingMode == clazz.fastGetConstant("ROUND_HALF_DOWN") ||
roundingMode == clazz.fastGetConstant("ROUND_HALF_EVEN")) {
c.setInternalModuleVariable("vpRoundingMode", roundingMode);
} else {
throw runtime.newTypeError("invalid rounding mode");
}
return c.searchInternalModuleVariable("vpRoundingMode");
}
throw runtime.newTypeError("first argument for BigDecimal#mode invalid");
}
private RoundingMode getRoundingMode(Ruby runtime) {
RubyFixnum roundingMode = (RubyFixnum)runtime.fastGetClass("BigDecimal")
.searchInternalModuleVariable("vpRoundingMode");
return RoundingMode.valueOf((int)roundingMode.getLongValue());
}
private RubyBigDecimal getVpValue(IRubyObject v, boolean must) {
if(v instanceof RubyBigDecimal) {
return (RubyBigDecimal)v;
} else if(v instanceof RubyFixnum || v instanceof RubyBignum) {
String s = v.toString();
return newInstance(getRuntime().fastGetClass("BigDecimal"),new IRubyObject[]{getRuntime().newString(s)});
}
if(must) {
String err;
if (isImmediate()) {
ThreadContext context = getRuntime().getCurrentContext();
err = inspect(context, this).toString();
} else {
err = getMetaClass().getBaseName();
}
throw getRuntime().newTypeError(err + " can't be coerced into BigDecimal");
}
return null;
}
private final static Pattern INFINITY_PATTERN = Pattern.compile("^([+-])?Infinity$");
private final static Pattern NUMBER_PATTERN
= Pattern.compile("^([+-]?\\d*\\.?\\d*([eE][+-]?)?\\d*).*");
@JRubyMethod(name = "new", required = 1, optional = 1, meta = true)
public static RubyBigDecimal newInstance(IRubyObject recv, IRubyObject[] args) {
BigDecimal decimal;
if (args.length == 0) {
decimal = new BigDecimal(0);
} else {
String strValue = args[0].convertToString().toString();
strValue = strValue.trim();
if ("NaN".equals(strValue)) {
return newNaN(recv.getRuntime());
}
Matcher m = INFINITY_PATTERN.matcher(strValue);
if (m.matches()) {
int sign = 1;
String signGroup = m.group(1);
if ("-".equals(signGroup)) {
sign = -1;
}
return newInfinity(recv.getRuntime(), sign);
}
// Clean-up string representation so that it could be understood
// by Java's BigDecimal. Not terribly efficient for now.
// 1. MRI allows d and D as exponent separators
strValue = strValue.replaceFirst("[dD]", "E");
// 2. MRI allows underscores anywhere
strValue = strValue.replaceAll("_", "");
// 3. MRI ignores the trailing junk
strValue = NUMBER_PATTERN.matcher(strValue).replaceFirst("$1");
try {
decimal = new BigDecimal(strValue);
} catch(NumberFormatException e) {
decimal = new BigDecimal(0);
}
if (decimal.signum() == 0) {
// MRI behavior: -0 and +0 are two different things
if (strValue.matches("^\\s*-.*")) {
return newZero(recv.getRuntime(), -1);
} else {
return newZero(recv.getRuntime(), 1);
}
}
}
return new RubyBigDecimal(recv.getRuntime(), decimal);
}
private static RubyBigDecimal newZero(Ruby runtime, int sign) {
RubyBigDecimal rbd = new RubyBigDecimal(runtime, BigDecimal.ZERO);
if (sign < 0) {
rbd.zeroSign = -1;
} else {
rbd.zeroSign = 1;
}
return rbd;
}
private static RubyBigDecimal newNaN(Ruby runtime) {
RubyBigDecimal rbd = new RubyBigDecimal(runtime, BigDecimal.ZERO);
rbd.isNaN = true;
return rbd;
}
private static RubyBigDecimal newInfinity(Ruby runtime, int sign) {
RubyBigDecimal rbd = new RubyBigDecimal(runtime, BigDecimal.ZERO);
if (sign < 0) {
rbd.infinitySign = -1;
} else {
rbd.infinitySign = 1;
}
return rbd;
}
private RubyBigDecimal setResult() {
return setResult(0);
}
private RubyBigDecimal setResult(int scale) {
int prec = RubyFixnum.fix2int(getRuntime().fastGetClass("BigDecimal").searchInternalModuleVariable("vpPrecLimit"));
int prec2 = Math.max(scale,prec);
if(prec2 > 0 && this.value.scale() > (prec2-getExponent())) {
this.value = this.value.setScale(prec2-getExponent(),BigDecimal.ROUND_HALF_UP);
}
return this;
}
@JRubyMethod(name = "hash")
public RubyFixnum hash() {
return getRuntime().newFixnum(value.hashCode());
}
@JRubyMethod(name = {"%", "modulo"}, required = 1)
public IRubyObject op_mod(ThreadContext context, IRubyObject arg) {
// TODO: full-precision remainder is 1000x slower than MRI!
Ruby runtime = context.getRuntime();
if (isInfinity() || isNaN()) {
return newNaN(runtime);
}
RubyBigDecimal val = getVpValue(arg, false);
if (val == null) {
return callCoerced(context, "%", arg, true);
}
if (val.isInfinity() || val.isNaN() || val.isZero()) {
return newNaN(runtime);
}
// Java and MRI definitions of modulo are different.
BigDecimal modulo = value.remainder(val.value);
if (modulo.signum() * val.value.signum() < 0) {
modulo = modulo.add(val.value);
}
return new RubyBigDecimal(runtime, modulo).setResult();
}
@JRubyMethod(name = "remainder", required = 1)
public IRubyObject remainder(ThreadContext context, IRubyObject arg) {
// TODO: full-precision remainder is 1000x slower than MRI!
Ruby runtime = context.getRuntime();
if (isInfinity() || isNaN()) {
return newNaN(runtime);
}
RubyBigDecimal val = getVpValue(arg,false);
if (val == null) {
return callCoerced(context, "remainder", arg, true);
}
if (val.isInfinity() || val.isNaN() || val.isZero()) {
return newNaN(runtime);
}
// Java and MRI definitions of remainder are the same.
return new RubyBigDecimal(runtime, value.remainder(val.value)).setResult();
}
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_mul(ThreadContext context, IRubyObject arg) {
return mult2(context, arg, RubyFixnum.zero(context.getRuntime()));
}
@JRubyMethod(name = "mult", required = 2)
public IRubyObject mult2(ThreadContext context, IRubyObject b, IRubyObject n) {
Ruby runtime = context.getRuntime();
RubyBigDecimal val = getVpValue(b,false);
if(val == null) {
// TODO: what about n arg?
return callCoerced(context, "*", b);
}
int digits = RubyNumeric.fix2int(n);
if (isNaN() || val.isNaN()) {
return newNaN(runtime);
}
if ((isInfinity() && val.isZero()) || (isZero() && val.isInfinity())) {
return newNaN(runtime);
}
if (isZero() || val.isZero()) {
int sign1 = isZero()? zeroSign : value.signum();
int sign2 = val.isZero() ? val.zeroSign : val.value.signum();
return newZero(runtime, sign1 * sign2);
}
if (isInfinity() || val.isInfinity()) {
int sign1 = isInfinity() ? infinitySign : value.signum();
int sign2 = val.isInfinity() ? val.infinitySign : val.value.signum();
return newInfinity(runtime, sign1 * sign2);
}
BigDecimal res = value.multiply(val.value);
if (res.precision() > digits) {
// TODO: rounding mode should not be hard-coded. See #mode.
res = res.round(new MathContext(digits, RoundingMode.HALF_UP));
}
return new RubyBigDecimal(runtime, res).setResult();
}
@JRubyMethod(name = {"**", "power"}, required = 1)
public IRubyObject op_pow(IRubyObject arg) {
if (!(arg instanceof RubyFixnum)) {
throw getRuntime().newTypeError("wrong argument type " + arg.getMetaClass() + " (expected Fixnum)");
}
if (isNaN() || isInfinity()) {
return newNaN(getRuntime());
}
int times = RubyNumeric.fix2int(arg.convertToInteger());
if (times < 0) {
if (isZero()) {
return newInfinity(getRuntime(), value.signum());
}
// Note: MRI has a very non-trivial way of calculating the precision,
// so we use very simple approximation here:
int precision = (-times + 4) * (getAllDigits().length() + 4);
return new RubyBigDecimal(getRuntime(),
value.pow(times, new MathContext(precision, RoundingMode.HALF_UP)));
} else {
return new RubyBigDecimal(getRuntime(), value.pow(times));
}
}
@JRubyMethod(name = "+", required = 1, frame=true)
public IRubyObject op_plus(ThreadContext context, IRubyObject b) {
return addInternal(context, b, "add", RubyFixnum.zero(context.getRuntime()));
}
@JRubyMethod(name = "add", required = 2, frame=true)
public IRubyObject add2(ThreadContext context, IRubyObject b, IRubyObject digits) {
return addInternal(context, b, "add", digits);
}
private IRubyObject addInternal(ThreadContext context, IRubyObject b, String op, IRubyObject digits) {
Ruby runtime = context.getRuntime();
int prec = getPositiveInt(context, digits);
RubyBigDecimal val = getVpValue(b, false);
if (val == null) {
// TODO:
// MRI behavior: Call "+" or "add", depending on the call.
// But this leads to exceptions when Floats are added. See:
// http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/17374
// return callCoerced(context, op, b, true); -- this is MRI behavior.
// We'll use ours for now, thus providing an ability to add Floats.
return callCoerced(context, "+", b, true);
}
IRubyObject res = handleAddSpecialValues(val);
if (res != null) {
return res;
}
RoundingMode roundMode = getRoundingMode(runtime);
return new RubyBigDecimal(runtime, value.add(
val.value, new MathContext(prec, roundMode))); // TODO: why this: .setResult();
}
private int getPositiveInt(ThreadContext context, IRubyObject arg) {
Ruby runtime = context.getRuntime();
if (arg instanceof RubyFixnum) {
int value = RubyNumeric.fix2int(arg);
if (value < 0) {
throw runtime.newArgumentError("argument must be positive");
}
return value;
} else {
throw runtime.newTypeError(arg, runtime.getFixnum());
}
}
private IRubyObject handleAddSpecialValues(RubyBigDecimal val) {
if (isNaN() || val.isNaN) {
return newNaN(getRuntime());
}
// TODO: don't calculate the same value 3 times
if (infinitySign * val.infinitySign > 0) {
return isInfinity() ? this : val;
}
if (infinitySign * val.infinitySign < 0) {
return newNaN(getRuntime());
}
if (infinitySign * val.infinitySign == 0) {
int sign = infinitySign + val.infinitySign;
if (sign != 0) {
return newInfinity(getRuntime(), sign);
}
}
return null;
}
@JRubyMethod(name = "+@")
public IRubyObject op_uplus() {
return this;
}
@JRubyMethod(name = "-", required = 1)
public IRubyObject op_minus(ThreadContext context, IRubyObject arg) {
RubyBigDecimal val = getVpValue(arg, false);
if(val == null) {
return callCoerced(context, "-", arg);
}
RubyBigDecimal res = handleMinusSpecialValues(val);
if (res != null) {
return res;
}
return new RubyBigDecimal(getRuntime(),value.subtract(val.value)).setResult();
}
@JRubyMethod(name = "sub", required = 2)
public IRubyObject sub2(ThreadContext context, IRubyObject b, IRubyObject n) {
RubyBigDecimal val = getVpValue(b, false);
if(val == null) {
return callCoerced(context, "-", b);
}
RubyBigDecimal res = handleMinusSpecialValues(val);
if (res != null) {
return res;
}
return new RubyBigDecimal(getRuntime(),value.subtract(val.value)).setResult();
}
private RubyBigDecimal handleMinusSpecialValues(RubyBigDecimal val) {
if (isNaN() || val.isNaN()) {
return newNaN(getRuntime());
}
// TODO: 3 times calculate the same value below
if (infinitySign * val.infinitySign > 0) {
return newNaN(getRuntime());
}
if (infinitySign * val.infinitySign < 0) {
return this;
}
if (infinitySign * val.infinitySign == 0) {
if (isInfinity()) {
return this;
}
if (val.isInfinity()) {
return newInfinity(getRuntime(), val.infinitySign * -1);
}
int sign = infinitySign + val.infinitySign;
if (sign != 0) {
return newInfinity(getRuntime(), sign);
}
}
return null;
}
@JRubyMethod(name = "-@")
public IRubyObject op_uminus() {
Ruby runtime = getRuntime();
if (isNaN()) {
return newNaN(runtime);
}
if (isInfinity()) {
return newInfinity(runtime, -infinitySign);
}
if (isZero()) {
return newZero(runtime, -zeroSign);
}
return new RubyBigDecimal(getRuntime(), value.negate());
}
@JRubyMethod(name = {"/", "quo"})
public IRubyObject op_quo(ThreadContext context, IRubyObject other) {
// regular division with some default precision
// TODO: proper algorithm to set the precision
return op_div(context, other, getRuntime().newFixnum(200));
}
@JRubyMethod(name = "div")
public IRubyObject op_div(ThreadContext context, IRubyObject other) {
// integer division
RubyBigDecimal val = getVpValue(other, false);
if (val == null) {
return callCoerced(context, "div", other);
}
if (isNaN() || val.isZero() || val.isNaN()) {
return newNaN(getRuntime());
}
if (isInfinity() || val.isInfinity()) {
return newNaN(getRuntime());
}
return new RubyBigDecimal(getRuntime(),
this.value.divideToIntegralValue(val.value)).setResult();
}
@JRubyMethod(name = "div")
public IRubyObject op_div(ThreadContext context, IRubyObject other, IRubyObject digits) {
// TODO: take BigDecimal.mode into account.
int scale = RubyNumeric.fix2int(digits);
RubyBigDecimal val = getVpValue(other, false);
if (val == null) {
return callCoerced(context, "/", other);
}
if (isNaN() || (isZero() && val.isZero()) || val.isNaN()) {
return newNaN(getRuntime());
}
if (val.isZero()) {
int sign1 = isInfinity() ? infinitySign : value.signum();
return newInfinity(getRuntime(), sign1 * val.zeroSign);
}
if (isInfinity() && !val.isInfinity()) {
return newInfinity(getRuntime(), infinitySign * val.value.signum());
}
if (!isInfinity() && val.isInfinity()) {
return newZero(getRuntime(), value.signum() * val.infinitySign);
}
if (isInfinity() && val.isInfinity()) {
return newNaN(getRuntime());
}
if (scale == 0) {
// MRI behavior: "If digits is 0, the result is the same as the / operator."
return op_quo(context, other);
} else {
// TODO: better algorithm to set precision needed
int prec = Math.max(200, scale);
return new RubyBigDecimal(getRuntime(),
value.divide(val.value, new MathContext(prec, RoundingMode.HALF_UP))).setResult(scale);
}
}
private IRubyObject cmp(ThreadContext context, IRubyObject r, char op) {
int e = 0;
RubyBigDecimal rb = getVpValue(r,false);
if(rb == null) {
IRubyObject ee = callCoerced(context, "<=>",r);
if(ee.isNil()) {
return getRuntime().getNil();
}
e = RubyNumeric.fix2int(ee);
} else {
if (isNaN() | rb.isNaN()) {
return getRuntime().getNil();
}
if (infinitySign != 0 || rb.infinitySign != 0) {
e = infinitySign - rb.infinitySign;
} else {
e = value.compareTo(rb.value);
}
}
switch(op) {
case '*': return getRuntime().newFixnum(e);
case '=': return (e==0)?getRuntime().getTrue():getRuntime().getFalse();
case '!': return (e!=0)?getRuntime().getTrue():getRuntime().getFalse();
case 'G': return (e>=0)?getRuntime().getTrue():getRuntime().getFalse();
case '>': return (e> 0)?getRuntime().getTrue():getRuntime().getFalse();
case 'L': return (e<=0)?getRuntime().getTrue():getRuntime().getFalse();
case '<': return (e< 0)?getRuntime().getTrue():getRuntime().getFalse();
}
return getRuntime().getNil();
}
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(ThreadContext context, IRubyObject arg) {
return cmp(context, arg,'*');
}
@JRubyMethod(name = {"eql?", "==", "==="}, required = 1)
public IRubyObject eql_p(ThreadContext context, IRubyObject arg) {
return cmp(context, arg,'=');
}
@JRubyMethod(name = "<", required = 1)
public IRubyObject op_lt(ThreadContext context, IRubyObject arg) {
return cmp(context, arg,'<');
}
@JRubyMethod(name = "<=", required = 1)
public IRubyObject op_le(ThreadContext context, IRubyObject arg) {
return cmp(context, arg,'L');
}
@JRubyMethod(name = ">", required = 1)
public IRubyObject op_gt(ThreadContext context, IRubyObject arg) {
return cmp(context, arg,'>');
}
@JRubyMethod(name = ">=", required = 1)
public IRubyObject op_ge(ThreadContext context, IRubyObject arg) {
return cmp(context, arg,'G');
}
@JRubyMethod(name = "abs")
public IRubyObject abs() {
Ruby runtime = getRuntime();
if (isNaN) {
return newNaN(runtime);
}
if (isInfinity()) {
return newInfinity(runtime, 1);
}
return new RubyBigDecimal(getRuntime(), value.abs()).setResult();
}
@JRubyMethod(name = "ceil", optional = 1)
public IRubyObject ceil(IRubyObject[] args) {
if (isNaN) {
return newNaN(getRuntime());
}
if (isInfinity()) {
return newInfinity(getRuntime(), infinitySign);
}
int n = 0;
if (args.length > 0) {
n = RubyNumeric.fix2int(args[0]);
}
if (value.scale() > n) { // rounding neccessary
return new RubyBigDecimal(getRuntime(),
value.setScale(n, RoundingMode.CEILING));
} else {
return this;
}
}
@JRubyMethod(name = "coerce", required = 1)
public IRubyObject coerce(IRubyObject other) {
IRubyObject obj;
if(other instanceof RubyFloat) {
obj = getRuntime().newArray(other,to_f());
} else {
obj = getRuntime().newArray(getVpValue(other, true),this);
}
return obj;
}
public double getDoubleValue() { return value.doubleValue(); }
public long getLongValue() { return value.longValue(); }
public RubyNumeric multiplyWith(ThreadContext context, RubyInteger value) {
return (RubyNumeric)op_mul(context, value);
}
public RubyNumeric multiplyWith(ThreadContext context, RubyFloat value) {
return (RubyNumeric)op_mul(context, value);
}
public RubyNumeric multiplyWith(ThreadContext context, RubyBignum value) {
return (RubyNumeric)op_mul(context, value);
}
@JRubyMethod(name = "divmod", required = 1)
public IRubyObject divmod(ThreadContext context, IRubyObject other) {
// TODO: full-precision divmod is 1000x slower than MRI!
Ruby runtime = context.getRuntime();
if (isInfinity() || isNaN()) {
return RubyArray.newArray(runtime, newNaN(runtime), newNaN(runtime));
}
RubyBigDecimal val = getVpValue(other, false);
if (val == null) {
return callCoerced(context, "divmod", other, true);
}
if (val.isInfinity() || val.isNaN() || val.isZero()) {
return RubyArray.newArray(runtime, newNaN(runtime), newNaN(runtime));
}
// Java and MRI definitions of divmod are different.
BigDecimal[] divmod = value.divideAndRemainder(val.value);
BigDecimal div = divmod[0];
BigDecimal mod = divmod[1];
if (mod.signum() * val.value.signum() < 0) {
div = div.subtract(BigDecimal.ONE);
mod = mod.add(val.value);
}
return RubyArray.newArray(runtime,
new RubyBigDecimal(runtime, div),
new RubyBigDecimal(runtime, mod));
}
@JRubyMethod(name = "exponent")
public IRubyObject exponent() {
return getRuntime().newFixnum(getExponent());
}
@JRubyMethod(name = "finite?")
public IRubyObject finite_p() {
if (isNaN()) {
return getRuntime().getFalse();
}
return getRuntime().newBoolean(!isInfinity());
}
@JRubyMethod(name = "floor", optional = 1)
public IRubyObject floor(IRubyObject[]args) {
if (isNaN) {
return newNaN(getRuntime());
}
if (isInfinity()) {
return newInfinity(getRuntime(), infinitySign);
}
int n = 0;
if (args.length > 0) {
n = RubyNumeric.fix2int(args[0]);
}
if (value.scale() > n) { // rounding neccessary
return new RubyBigDecimal(getRuntime(),
value.setScale(n, RoundingMode.FLOOR));
} else {
return this;
}
}
@JRubyMethod(name = "frac")
public IRubyObject frac() {
if (isNaN) {
return newNaN(getRuntime());
}
if (isInfinity()) {
return newInfinity(getRuntime(), infinitySign);
}
if (value.scale() > 0 && value.precision() < value.scale()) {
return new RubyBigDecimal(getRuntime(), value);
}
BigDecimal val = value.subtract(((RubyBigDecimal)fix()).value);
return new RubyBigDecimal(getRuntime(), val);
}
@JRubyMethod(name = "infinite?")
public IRubyObject infinite_p() {
if (infinitySign == 0) {
return getRuntime().getNil();
}
return getRuntime().newFixnum(infinitySign);
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect(ThreadContext context) {
StringBuilder val = new StringBuilder("#<BigDecimal:").append(Integer.toHexString(System.identityHashCode(this))).append(",");
val.append("'").append(this.callMethod(context, MethodIndex.TO_S, "to_s")).append("'").append(",");
val.append(getSignificantDigits().length()).append("(");
int len = getAllDigits().length();
int pow = len / 4;
val.append((pow + 1) * 4).append(")").append(">");
return getRuntime().newString(val.toString());
}
@JRubyMethod(name = "nan?")
public IRubyObject nan_p() {
return getRuntime().newBoolean(isNaN);
}
@JRubyMethod(name = "nonzero?")
public IRubyObject nonzero_p() {
return isZero() ? getRuntime().getNil() : this;
}
@JRubyMethod(name = "precs")
public IRubyObject precs() {
final Ruby runtime = getRuntime();
final IRubyObject[] array = new IRubyObject[2];
array[0] = runtime.newFixnum(getSignificantDigits().length());
int len = getAllDigits().length();
int pow = len / 4;
array[1] = runtime.newFixnum((pow + 1) * 4);
return RubyArray.newArray(runtime, array);
}
@JRubyMethod(name = "round", optional = 2)
public IRubyObject round(IRubyObject[] args) {
int scale = args.length > 0 ? num2int(args[0]) : 0;
int mode = (args.length > 1) ? javaRoundingModeFromRubyRoundingMode(args[1]) : BigDecimal.ROUND_HALF_UP;
// JRUBY-914: Java 1.4 BigDecimal does not allow a negative scale, so we have to simulate it
if (scale < 0) {
// shift the decimal point just to the right of the digit to be rounded to (divide by 10**(abs(scale)))
// -1 -> 10's digit, -2 -> 100's digit, etc.
BigDecimal normalized = value.movePointRight(scale);
// ...round to that digit
BigDecimal rounded = normalized.setScale(0,mode);
// ...and shift the result back to the left (multiply by 10**(abs(scale)))
return new RubyBigDecimal(getRuntime(), rounded.movePointLeft(scale));
} else {
return new RubyBigDecimal(getRuntime(), value.setScale(scale, mode));
}
}
//this relies on the Ruby rounding enumerations == Java ones, which they (currently) all are
private int javaRoundingModeFromRubyRoundingMode(IRubyObject arg) {
return num2int(arg);
}
@JRubyMethod(name = "sign")
public IRubyObject sign() {
if (isNaN()) {
return getMetaClass().fastGetConstant("SIGN_NaN");
}
if (isInfinity()) {
if (infinitySign < 0) {
return getMetaClass().fastGetConstant("SIGN_NEGATIVE_INFINITE");
} else {
return getMetaClass().fastGetConstant("SIGN_POSITIVE_INFINITE");
}
}
if (isZero()) {
if (zeroSign < 0) {
return getMetaClass().fastGetConstant("SIGN_NEGATIVE_ZERO");
} else {
return getMetaClass().fastGetConstant("SIGN_POSITIVE_ZERO");
}
}
if (value.signum() < 0) {
return getMetaClass().fastGetConstant("SIGN_NEGATIVE_FINITE");
} else {
return getMetaClass().fastGetConstant("SIGN_POSITIVE_FINITE");
}
}
@JRubyMethod(name = "split")
public RubyArray split() {
final Ruby runtime = getRuntime();
final IRubyObject[] array = new IRubyObject[4];
// sign
final RubyFixnum sign;
if (isNaN) {
sign = RubyFixnum.zero(runtime);
} else if (isInfinity()) {
sign = runtime.newFixnum(infinitySign);
} else if (isZero()){
sign = runtime.newFixnum(zeroSign);
} else {
sign = runtime.newFixnum(value.signum());
}
array[0] = sign;
// significant digits and exponent
final RubyString digits;
final RubyFixnum exp;
if (isNaN()) {
digits = runtime.newString("NaN");
exp = RubyFixnum.zero(runtime);
} else if (isInfinity()) {
digits = runtime.newString("Infinity");
exp = RubyFixnum.zero(runtime);
} else if (isZero()){
digits = runtime.newString("0");
exp = RubyFixnum.zero(runtime);
} else {
// normalize the value
digits = runtime.newString(getSignificantDigits());
exp = runtime.newFixnum(getExponent());
}
array[1] = digits;
array[3] = exp;
// base
array[2] = runtime.newFixnum(10);
return RubyArray.newArray(runtime, array);
}
// it doesn't handle special cases
private String getSignificantDigits() {
// TODO: no need to calculate every time.
BigDecimal val = value.abs().stripTrailingZeros();
return val.unscaledValue().toString();
}
private String getAllDigits() {
// TODO: no need to calculate every time.
BigDecimal val = value.abs();
return val.unscaledValue().toString();
}
// it doesn't handle special cases
private int getExponent() {
// TODO: no need to calculate every time.
if (isZero()) {
return 0;
}
BigDecimal val = value.abs().stripTrailingZeros();
return val.precision() - val.scale();
}
@JRubyMethod(name = "sqrt", required = 1)
public IRubyObject sqrt(IRubyObject arg) {
Ruby runtime = getRuntime();
if (isNaN()) {
throw runtime.newFloatDomainError("(VpSqrt) SQRT(NaN value)");
}
if ((isInfinity() && infinitySign < 0) || value.signum() < 0) {
throw runtime.newFloatDomainError("(VpSqrt) SQRT(negative value)");
}
if (isInfinity() && infinitySign > 0) {
return newInfinity(runtime, 1);
}
// NOTE: MRI's sqrt precision is limited by 100,
// but we allow values more than 100.
int n = RubyNumeric.fix2int(arg);
if (n < 0) {
throw runtime.newArgumentError("argument must be positive");
}
n += 4; // just in case, add a bit of extra precision
return new RubyBigDecimal(getRuntime(),
bigSqrt(this.value, new MathContext(n, RoundingMode.HALF_UP))).setResult();
}
@JRubyMethod(name = "to_f")
public IRubyObject to_f() {
if (isNaN()) {
return RubyFloat.newFloat(getRuntime(), Double.NaN);
}
if (isInfinity()) {
return RubyFloat.newFloat(getRuntime(),
infinitySign < 0 ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY);
}
if (isZero()) {
return RubyFloat.newFloat(getRuntime(),
zeroSign < 0 ? -0.0 : 0.0);
}
return RubyFloat.newFloat(getRuntime(), value.doubleValue());
}
@JRubyMethod(name = {"to_i", "to_int"})
public IRubyObject to_int() {
if (isNaN() || infinitySign != 0) {
return getRuntime().getNil();
}
try {
return RubyNumeric.int2fix(getRuntime(), value.longValueExact());
} catch (ArithmeticException ae) {
return RubyBignum.bignorm(getRuntime(), value.toBigInteger());
}
}
private String removeTrailingZeroes(String in) {
while(in.length() > 0 && in.charAt(in.length()-1)=='0') {
in = in.substring(0,in.length()-1);
}
return in;
}
public static boolean formatHasLeadingPlus(String format) {
return format.startsWith("+");
}
public static boolean formatHasLeadingSpace(String format) {
return format.startsWith(" ");
}
public static boolean formatHasFloatingPointNotation(String format) {
return format.endsWith("F");
}
public static int formatFractionalDigitGroups(String format) {
int groups = 0;
Pattern p = Pattern.compile("(\\+| )?(\\d+)(E|F)?");
Matcher m = p.matcher(format);
if (m.matches()) {
groups = Integer.parseInt(m.group(2));
}
return groups;
}
private boolean hasArg(IRubyObject[] args) {
return args.length != 0 && !args[0].isNil();
}
private String format(IRubyObject[] args) {
return args[0].toString();
}
private String firstArgument(IRubyObject[] args) {
if (hasArg(args)) {
return format(args);
}
return null;
}
private boolean posSpace(String arg) {
if (null != arg) {
return formatHasLeadingSpace(arg);
}
return false;
}
private boolean posSign(String arg) {
if (null != arg) {
return formatHasLeadingPlus(arg) || posSpace(arg);
}
return false;
}
private boolean asEngineering(String arg) {
if (null != arg) {
return !formatHasFloatingPointNotation(arg);
}
return true;
}
private int groups(String arg) {
if (null != arg) {
return formatFractionalDigitGroups(arg);
}
return 0;
}
private boolean isZero() {
return !isNaN() && !isInfinity() && (value.signum() == 0);
}
private boolean isNaN() {
return isNaN;
}
private boolean isInfinity() {
return infinitySign != 0;
}
private String unscaledValue() {
return value.abs().unscaledValue().toString();
}
private IRubyObject engineeringValue(String arg) {
int exponent = getExponent();
int signum = value.signum();
StringBuilder build = new StringBuilder();
build.append(signum == -1 ? "-" : (signum == 1 ? (posSign(arg) ? (posSpace(arg) ? " " : "+") : "") : ""));
build.append("0.");
if (0 == groups(arg)) {
String s = removeTrailingZeroes(unscaledValue());
if ("".equals(s)) {
build.append("0");
} else {
build.append(s);
}
} else {
int index = 0;
String sep = "";
while (index < unscaledValue().length()) {
int next = index + groups(arg);
if (next > unscaledValue().length()) {
next = unscaledValue().length();
}
build.append(sep).append(unscaledValue().substring(index, next));
sep = " ";
index += groups(arg);
}
}
build.append("E").append(exponent);
return getRuntime().newString(build.toString());
}
private IRubyObject floatingPointValue(String arg) {
String values[] = value.abs().stripTrailingZeros().toPlainString().split("\\.");
String whole = "0";
if (values.length > 0) {
whole = values[0];
}
String after = "0";
if (values.length > 1) {
after = values[1];
}
int signum = value.signum();
StringBuilder build = new StringBuilder();
build.append(signum == -1 ? "-" : (signum == 1 ? (posSign(arg) ? (posSpace(arg) ? " " : "+") : "") : ""));
if (groups(arg) == 0) {
build.append(whole);
if (null != after) {
build.append(".").append(after);
}
} else {
int index = 0;
String sep = "";
while (index < whole.length()) {
int next = index + groups(arg);
if (next > whole.length()) {
next = whole.length();
}
build.append(sep).append(whole.substring(index, next));
sep = " ";
index += groups(arg);
}
if (null != after) {
build.append(".");
index = 0;
sep = "";
while (index < after.length()) {
int next = index + groups(arg);
if (next > after.length()) {
next = after.length();
}
build.append(sep).append(after.substring(index, next));
sep = " ";
index += groups(arg);
}
}
}
return getRuntime().newString(build.toString());
}
@JRubyMethod(name = "to_s", optional = 1)
public IRubyObject to_s(IRubyObject[] args) {
String arg = firstArgument(args);
if (isNaN()) {
return getRuntime().newString("NaN");
}
if (infinitySign != 0) {
if (infinitySign == -1) {
return getRuntime().newString("-Infinity");
} else {
return getRuntime().newString("Infinity");
}
}
if (isZero()) {
String zero = "0.0";
if (zeroSign < 0) {
zero = "-" + zero;
}
return getRuntime().newString(zero);
}
if(asEngineering(arg)) {
return engineeringValue(arg);
} else {
return floatingPointValue(arg);
}
}
// Note: #fix has only no-arg form, but truncate allows optional parameter.
@JRubyMethod
public IRubyObject fix() {
return truncate(RubyFixnum.zero(getRuntime()));
}
@JRubyMethod
public IRubyObject truncate() {
return truncate(RubyFixnum.zero(getRuntime()));
}
@JRubyMethod
public IRubyObject truncate(IRubyObject arg) {
if (isNaN) {
return newNaN(getRuntime());
}
if (isInfinity()) {
return newInfinity(getRuntime(), infinitySign);
}
int n = RubyNumeric.fix2int(arg);
int precision = value.precision() - value.scale() + n;
if (precision > 0) {
return new RubyBigDecimal(getRuntime(),
value.round(new MathContext(precision, RoundingMode.DOWN)));
} else {
// TODO: proper sign
return new RubyBigDecimal(getRuntime(), BigDecimal.ZERO);
}
}
@JRubyMethod(name = "zero?")
public IRubyObject zero_p() {
return getRuntime().newBoolean(isZero());
}
/**
* Returns the correctly rounded square root of a positive
* BigDecimal. This method performs the fast <i>Square Root by
* Coupled Newton Iteration</i> algorithm by Timm Ahrendt, from
* the book "Pi, unleashed" by Jörg Arndt in a neat loop.
* <p>
* The code is based on Frans Lelieveld's code , used here with
* permission.
*
* @param squarD The number to get the root from.
* @param rootMC Precision and rounding mode.
* @return the root of the argument number
* @throws ArithmeticException
* if the argument number is negative
* @throws IllegalArgumentException
* if rootMC has precision 0
*/
public static BigDecimal bigSqrt(BigDecimal squarD, MathContext rootMC) {
// General number and precision checking
int sign = squarD.signum();
if (sign == -1) {
throw new ArithmeticException("Square root of a negative number: " + squarD);
} else if(sign == 0) {
return squarD.round(rootMC);
}
int prec = rootMC.getPrecision(); // the requested precision
if (prec == 0) {
throw new IllegalArgumentException("Most roots won't have infinite precision = 0");
}
// Initial precision is that of double numbers 2^63/2 ~ 4E18
int BITS = 62; // 63-1 an even number of number bits
int nInit = 16; // precision seems 16 to 18 digits
MathContext nMC = new MathContext(18, RoundingMode.HALF_DOWN);
// Iteration variables, for the square root x and the reciprocal v
BigDecimal x = null, e = null; // initial x: x0 ~ sqrt()
BigDecimal v = null, g = null; // initial v: v0 = 1/(2*x)
// Estimate the square root with the foremost 62 bits of squarD
BigInteger bi = squarD.unscaledValue(); // bi and scale are a tandem
int biLen = bi.bitLength();
int shift = Math.max(0, biLen - BITS + (biLen%2 == 0 ? 0 : 1)); // even shift..
bi = bi.shiftRight(shift); // ..floors to 62 or 63 bit BigInteger
double root = Math.sqrt(bi.doubleValue());
BigDecimal halfBack = new BigDecimal(BigInteger.ONE.shiftLeft(shift/2));
int scale = squarD.scale();
if (scale % 2 == 1) {
root *= SQRT_10; // 5 -> 2, -5 -> -3 need half a scale more..
}
scale = (int) Math.floor(scale/2.); // ..where 100 -> 10 shifts the scale
// Initial x - use double root - multiply by halfBack to unshift - set new scale
x = new BigDecimal(root, nMC);
x = x.multiply(halfBack, nMC); // x0 ~ sqrt()
if (scale != 0) {
x = x.movePointLeft(scale);
}
if (prec < nInit) { // for prec 15 root x0 must surely be OK
return x.round(rootMC); // return small prec roots without iterations
}
// Initial v - the reciprocal
v = BigDecimal.ONE.divide(TWO.multiply(x), nMC); // v0 = 1/(2*x)
// Collect iteration precisions beforehand
List<Integer> nPrecs = new ArrayList<Integer>();
assert nInit > 3 : "Never ending loop!"; // assume nInit = 16 <= prec
// Let m be the exact digits precision in an earlier! loop
for (int m = prec + 1; m > nInit; m = m/2 + (m > 100 ? 1 : 2)) {
nPrecs.add(m);
}
// The loop of "Square Root by Coupled Newton Iteration"
for (int i = nPrecs.size() - 1; i > -1; i--) {
// Increase precision - next iteration supplies n exact digits
nMC = new MathContext(nPrecs.get(i), (i%2 == 1) ? RoundingMode.HALF_UP :
RoundingMode.HALF_DOWN);
// Next x // e = d - x^2
e = squarD.subtract(x.multiply(x, nMC), nMC);
if (i != 0) {
x = x.add(e.multiply(v, nMC)); // x += e*v ~ sqrt()
} else {
x = x.add(e.multiply(v, rootMC), rootMC); // root x is ready!
break;
}
// Next v // g = 1 - 2*x*v
g = BigDecimal.ONE.subtract(TWO.multiply(x).multiply(v, nMC));
v = v.add(g.multiply(v, nMC)); // v += g*v ~ 1/2/sqrt()
}
return x; // return sqrt(squarD) with precision of rootMC
}
}// RubyBigdecimal
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Bignum", parent="Integer")
public class RubyBignum extends RubyInteger {
public static RubyClass createBignumClass(Ruby runtime) {
RubyClass bignum = runtime.defineClass("Bignum", runtime.getInteger(),
ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setBignum(bignum);
bignum.index = ClassIndex.BIGNUM;
bignum.defineAnnotatedMethods(RubyBignum.class);
return bignum;
}
private static final int BIT_SIZE = 64;
private static final long MAX = (1L << (BIT_SIZE - 1)) - 1;
private static final BigInteger LONG_MAX = BigInteger.valueOf(MAX);
private static final BigInteger LONG_MIN = BigInteger.valueOf(-MAX - 1);
private final BigInteger value;
public RubyBignum(Ruby runtime, BigInteger value) {
super(runtime, runtime.getBignum());
this.value = value;
}
public int getNativeTypeIndex() {
return ClassIndex.BIGNUM;
}
public Class<?> getJavaClass() {
return BigInteger.class;
}
public static RubyBignum newBignum(Ruby runtime, long value) {
return newBignum(runtime, BigInteger.valueOf(value));
}
public static RubyBignum newBignum(Ruby runtime, double value) {
return newBignum(runtime, new BigDecimal(value).toBigInteger());
}
public static RubyBignum newBignum(Ruby runtime, BigInteger value) {
return new RubyBignum(runtime, value);
}
public static RubyBignum newBignum(Ruby runtime, String value) {
return new RubyBignum(runtime, new BigInteger(value));
}
public double getDoubleValue() {
return big2dbl(this);
}
public long getLongValue() {
return big2long(this);
}
/** Getter for property value.
* @return Value of property value.
*/
public BigInteger getValue() {
return value;
}
/* ================
* Utility Methods
* ================
*/
/* If the value will fit in a Fixnum, return one of those. */
/** rb_big_norm
*
*/
public static RubyInteger bignorm(Ruby runtime, BigInteger bi) {
if (bi.compareTo(LONG_MIN) < 0 || bi.compareTo(LONG_MAX) > 0) {
return newBignum(runtime, bi);
}
return runtime.newFixnum(bi.longValue());
}
/** rb_big2long
*
*/
public static long big2long(RubyBignum value) {
BigInteger big = value.getValue();
if (big.compareTo(LONG_MIN) < 0 || big.compareTo(LONG_MAX) > 0) {
throw value.getRuntime().newRangeError("bignum too big to convert into `long'");
}
return big.longValue();
}
/** rb_big2dbl
*
*/
public static double big2dbl(RubyBignum value) {
BigInteger big = value.getValue();
double dbl = convertToDouble(big);
if (dbl == Double.NEGATIVE_INFINITY || dbl == Double.POSITIVE_INFINITY) {
value.getRuntime().getWarnings().warn(ID.BIGNUM_FROM_FLOAT_RANGE, "Bignum out of Float range");
}
return dbl;
}
private IRubyObject checkShiftDown(RubyBignum other) {
if (other.value.signum() == 0) return RubyFixnum.zero(getRuntime());
if (value.compareTo(LONG_MIN) < 0 || value.compareTo(LONG_MAX) > 0) {
return other.value.signum() >= 0 ? RubyFixnum.zero(getRuntime()) : RubyFixnum.minus_one(getRuntime());
}
return getRuntime().getNil();
}
/**
* BigInteger#doubleValue is _really_ slow currently.
* This is faster, and mostly correct (?)
*/
static double convertToDouble(BigInteger bigint) {
byte[] arr = bigint.toByteArray();
double res = 0;
double acc = 1;
for (int i = arr.length - 1; i > 0 ; i--)
{
res += (double) (arr[i] & 0xff) * acc;
acc *= 256;
}
res += (double) arr[0] * acc; // final byte sign is significant
return res;
}
/** rb_int2big
*
*/
public static BigInteger fix2big(RubyFixnum arg) {
return BigInteger.valueOf(arg.getLongValue());
}
/* ================
* Instance Methods
* ================
*/
/** rb_big_to_s
*
*/
@JRubyMethod(name = "to_s", optional = 1)
public IRubyObject to_s(IRubyObject[] args) {
int base = args.length == 0 ? 10 : num2int(args[0]);
if (base < 2 || base > 36) {
throw getRuntime().newArgumentError("illegal radix " + base);
}
return getRuntime().newString(getValue().toString(base));
}
/** rb_big_coerce
*
*/
@JRubyMethod(name = "coerce", required = 1)
public IRubyObject coerce(IRubyObject other) {
if (other instanceof RubyFixnum) {
return getRuntime().newArray(newBignum(getRuntime(), ((RubyFixnum) other).getLongValue()), this);
} else if (other instanceof RubyBignum) {
return getRuntime().newArray(newBignum(getRuntime(), ((RubyBignum) other).getValue()), this);
}
throw getRuntime().newTypeError("Can't coerce " + other.getMetaClass().getName() + " to Bignum");
}
/** rb_big_uminus
*
*/
@JRubyMethod(name = "-@")
public IRubyObject op_uminus() {
return bignorm(getRuntime(), value.negate());
}
/** rb_big_plus
*
*/
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return addFixnum((RubyFixnum)other);
} else if (other instanceof RubyBignum) {
return addBignum((RubyBignum)other);
} else if (other instanceof RubyFloat) {
return addFloat((RubyFloat)other);
}
return addOther(context, other);
}
private IRubyObject addFixnum(RubyFixnum other) {
return bignorm(getRuntime(), value.add(fix2big(other)));
}
private IRubyObject addBignum(RubyBignum other) {
return bignorm(getRuntime(), value.add(other.value));
}
private IRubyObject addFloat(RubyFloat other) {
return RubyFloat.newFloat(getRuntime(), big2dbl(this) + other.getDoubleValue());
}
private IRubyObject addOther(ThreadContext context, IRubyObject other) {
return coerceBin(context, "+", other);
}
/** rb_big_minus
*
*/
@JRubyMethod(name = "-", required = 1)
public IRubyObject op_minus(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return subtractFixnum((RubyFixnum)other);
} else if (other instanceof RubyBignum) {
return subtractBignum((RubyBignum)other);
} else if (other instanceof RubyFloat) {
return subtractFloat((RubyFloat)other);
}
return subtractOther(context, other);
}
private IRubyObject subtractFixnum(RubyFixnum other) {
return bignorm(getRuntime(), value.subtract(fix2big(((RubyFixnum) other))));
}
private IRubyObject subtractBignum(RubyBignum other) {
return bignorm(getRuntime(), value.subtract(((RubyBignum) other).value));
}
private IRubyObject subtractFloat(RubyFloat other) {
return RubyFloat.newFloat(getRuntime(), big2dbl(this) - ((RubyFloat) other).getDoubleValue());
}
private IRubyObject subtractOther(ThreadContext context, IRubyObject other) {
return coerceBin(context, "-", other);
}
/** rb_big_mul
*
*/
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_mul(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return bignorm(getRuntime(), value.multiply(fix2big(((RubyFixnum) other))));
}
if (other instanceof RubyBignum) {
return bignorm(getRuntime(), value.multiply(((RubyBignum) other).value));
} else if (other instanceof RubyFloat) {
return RubyFloat.newFloat(getRuntime(), big2dbl(this) * ((RubyFloat) other).getDoubleValue());
}
return coerceBin(context, "*", other);
}
/**
* rb_big_divide. Shared part for both "/" and "div" operations.
*/
private IRubyObject op_divide(ThreadContext context, IRubyObject other, String op) {
assert ("/".equals(op) || "div".equals(op));
final BigInteger otherValue;
if (other instanceof RubyFixnum) {
otherValue = fix2big((RubyFixnum) other);
} else if (other instanceof RubyBignum) {
otherValue = ((RubyBignum) other).value;
} else if (other instanceof RubyFloat) {
double div = big2dbl(this) / ((RubyFloat) other).getDoubleValue();
if ("/".equals(op)) {
return RubyFloat.newFloat(getRuntime(),
big2dbl(this) / ((RubyFloat) other).getDoubleValue());
} else {
return RubyNumeric.dbl2num(getRuntime(), div);
}
} else {
return coerceBin(context, op, other);
}
if (otherValue.equals(BigInteger.ZERO)) {
throw getRuntime().newZeroDivisionError();
}
BigInteger[] results = value.divideAndRemainder(otherValue);
if ((value.signum() * otherValue.signum()) == -1 && results[1].signum() != 0) {
return bignorm(getRuntime(), results[0].subtract(BigInteger.ONE));
}
return bignorm(getRuntime(), results[0]);
}
/** rb_big_div
*
*/
@JRubyMethod(name = {"/"}, required = 1)
public IRubyObject op_div(ThreadContext context, IRubyObject other) {
return op_divide(context, other, "/");
}
/** rb_big_idiv
*
*/
@JRubyMethod(name = {"div"}, required = 1)
public IRubyObject op_idiv(ThreadContext context, IRubyObject other) {
return op_divide(context, other, "div");
}
/** rb_big_divmod
*
*/
@JRubyMethod(name = "divmod", required = 1)
public IRubyObject divmod(ThreadContext context, IRubyObject other) {
final BigInteger otherValue;
if (other instanceof RubyFixnum) {
otherValue = fix2big((RubyFixnum) other);
} else if (other instanceof RubyBignum) {
otherValue = ((RubyBignum) other).value;
} else {
return coerceBin(context, "divmod", other);
}
if (otherValue.equals(BigInteger.ZERO)) {
throw getRuntime().newZeroDivisionError();
}
BigInteger[] results = value.divideAndRemainder(otherValue);
if ((value.signum() * otherValue.signum()) == -1 && results[1].signum() != 0) {
results[0] = results[0].subtract(BigInteger.ONE);
results[1] = otherValue.add(results[1]);
}
final Ruby runtime = getRuntime();
return RubyArray.newArray(getRuntime(), bignorm(runtime, results[0]), bignorm(runtime, results[1]));
}
/** rb_big_modulo
*
*/
@JRubyMethod(name = {"%", "modulo"}, required = 1)
public IRubyObject op_mod(ThreadContext context, IRubyObject other) {
final BigInteger otherValue;
if (other instanceof RubyFixnum) {
otherValue = fix2big((RubyFixnum) other);
} else if (other instanceof RubyBignum) {
otherValue = ((RubyBignum) other).value;
} else {
return coerceBin(context, "%", other);
}
if (otherValue.equals(BigInteger.ZERO)) {
throw getRuntime().newZeroDivisionError();
}
BigInteger result = value.mod(otherValue.abs());
if (otherValue.signum() == -1 && result.signum() != 0) {
result = otherValue.add(result);
}
return bignorm(getRuntime(), result);
}
/** rb_big_remainder
*
*/
@JRubyMethod(name = "remainder", required = 1)
public IRubyObject remainder(ThreadContext context, IRubyObject other) {
final BigInteger otherValue;
if (other instanceof RubyFixnum) {
otherValue = fix2big(((RubyFixnum) other));
} else if (other instanceof RubyBignum) {
otherValue = ((RubyBignum) other).value;
} else {
return coerceBin(context, "remainder", other);
}
if (otherValue.equals(BigInteger.ZERO)) {
throw getRuntime().newZeroDivisionError();
}
return bignorm(getRuntime(), value.remainder(otherValue));
}
/** rb_big_quo
*
*/
@JRubyMethod(name = "quo", required = 1)
public IRubyObject quo(ThreadContext context, IRubyObject other) {
if (other instanceof RubyNumeric) {
return RubyFloat.newFloat(getRuntime(), big2dbl(this) / ((RubyNumeric) other).getDoubleValue());
} else {
return coerceBin(context, "quo", other);
}
}
/** rb_big_pow
*
*/
@JRubyMethod(name = {"**", "power"}, required = 1)
public IRubyObject op_pow(ThreadContext context, IRubyObject other) {
double d;
if (other instanceof RubyFixnum) {
RubyFixnum fix = (RubyFixnum) other;
long fixValue = fix.getLongValue();
// MRI issuses warning here on (RBIGNUM(x)->len * SIZEOF_BDIGITS * yy > 1024*1024)
if (((value.bitLength() + 7) / 8) * 4 * Math.abs(fixValue) > 1024 * 1024) {
getRuntime().getWarnings().warn(ID.MAY_BE_TOO_BIG, "in a**b, b may be too big", fixValue);
}
if (fixValue >= 0) {
return bignorm(getRuntime(), value.pow((int) fixValue)); // num2int is also implemented
} else {
return RubyFloat.newFloat(getRuntime(), Math.pow(big2dbl(this), (double)fixValue));
}
} else if (other instanceof RubyBignum) {
d = ((RubyBignum) other).getDoubleValue();
getRuntime().getWarnings().warn(ID.MAY_BE_TOO_BIG, "in a**b, b may be too big", d);
} else if (other instanceof RubyFloat) {
d = ((RubyFloat) other).getDoubleValue();
} else {
return coerceBin(context, "**", other);
}
return RubyFloat.newFloat(getRuntime(), Math.pow(big2dbl(this), d));
}
/** rb_big_pow
*
*/
@JRubyMethod(name = {"**", "power"}, required = 1, compat = CompatVersion.RUBY1_9)
public IRubyObject op_pow_19(ThreadContext context, IRubyObject other) {
Ruby runtime = context.getRuntime();
if (other == RubyFixnum.zero(runtime)) return RubyFixnum.one(runtime);
double d;
if (other instanceof RubyFixnum) {
RubyFixnum fix = (RubyFixnum) other;
long fixValue = fix.getLongValue();
if (fixValue < 0) {
return RubyRational.newRationalRaw(runtime, this).callMethod(context, "**", other);
}
// MRI issuses warning here on (RBIGNUM(x)->len * SIZEOF_BDIGITS * yy > 1024*1024)
if (((value.bitLength() + 7) / 8) * 4 * Math.abs(fixValue) > 1024 * 1024) {
getRuntime().getWarnings().warn(ID.MAY_BE_TOO_BIG, "in a**b, b may be too big", fixValue);
}
if (fixValue >= 0) {
return bignorm(runtime, value.pow((int) fixValue)); // num2int is also implemented
} else {
return RubyFloat.newFloat(runtime, Math.pow(big2dbl(this), (double)fixValue));
}
} else if (other instanceof RubyBignum) {
if (other.callMethod(context, "<", RubyFixnum.zero(runtime)).isTrue()) {
return RubyRational.newRationalRaw(runtime, this).callMethod(context, "**", other);
}
d = ((RubyBignum) other).getDoubleValue();
getRuntime().getWarnings().warn(ID.MAY_BE_TOO_BIG, "in a**b, b may be too big", d);
} else if (other instanceof RubyFloat) {
d = ((RubyFloat) other).getDoubleValue();
} else {
return coerceBin(context, "**", other);
}
return RubyNumeric.dbl2num(runtime, Math.pow(big2dbl(this), d));
}
/** rb_big_and
*
*/
@JRubyMethod(name = "&", required = 1)
public IRubyObject op_and(ThreadContext context, IRubyObject other) {
other = other.convertToInteger();
if (other instanceof RubyBignum) {
return bignorm(getRuntime(), value.and(((RubyBignum) other).value));
} else if(other instanceof RubyFixnum) {
return bignorm(getRuntime(), value.and(fix2big((RubyFixnum)other)));
}
return coerceBin(context, "&", other);
}
/** rb_big_or
*
*/
@JRubyMethod(name = "|", required = 1)
public IRubyObject op_or(ThreadContext context, IRubyObject other) {
other = other.convertToInteger();
if (other instanceof RubyBignum) {
return bignorm(getRuntime(), value.or(((RubyBignum) other).value));
}
if (other instanceof RubyFixnum) { // no bignorm here needed
return bignorm(getRuntime(), value.or(fix2big((RubyFixnum)other)));
}
return coerceBin(context, "|", other);
}
/** rb_big_xor
*
*/
@JRubyMethod(name = "^", required = 1)
public IRubyObject op_xor(ThreadContext context, IRubyObject other) {
other = other.convertToInteger();
if (other instanceof RubyBignum) {
return bignorm(getRuntime(), value.xor(((RubyBignum) other).value));
}
if (other instanceof RubyFixnum) {
return bignorm(getRuntime(), value.xor(BigInteger.valueOf(((RubyFixnum) other).getLongValue())));
}
return coerceBin(context, "^", other);
}
/** rb_big_neg
*
*/
@JRubyMethod(name = "~")
public IRubyObject op_neg() {
return RubyBignum.newBignum(getRuntime(), value.not());
}
/** rb_big_lshift
*
*/
@JRubyMethod(name = "<<", required = 1)
public IRubyObject op_lshift(IRubyObject other) {
long shift;
boolean neg = false;
for (;;) {
if (other instanceof RubyFixnum) {
shift = ((RubyFixnum)other).getLongValue();
if (shift < 0) {
neg = true;
shift = -shift;
}
break;
} else if (other instanceof RubyBignum) {
RubyBignum otherBignum = (RubyBignum)other;
if (otherBignum.value.signum() < 0) {
IRubyObject tmp = otherBignum.checkShiftDown(this);
if (!tmp.isNil()) return tmp;
neg = true;
}
shift = big2long(otherBignum);
break;
}
other = other.convertToInteger();
}
return bignorm(getRuntime(), neg ? value.shiftRight((int)shift) : value.shiftLeft((int)shift));
}
/** rb_big_rshift
*
*/
@JRubyMethod(name = ">>", required = 1)
public IRubyObject op_rshift(IRubyObject other) {
long shift;
boolean neg = false;
for (;;) {
if (other instanceof RubyFixnum) {
shift = ((RubyFixnum)other).getLongValue();
if (shift < 0) {
neg = true;
shift = -shift;
}
break;
} else if (other instanceof RubyBignum) {
RubyBignum otherBignum = (RubyBignum)other;
if (otherBignum.value.signum() >= 0) {
IRubyObject tmp = otherBignum.checkShiftDown(this);
if (!tmp.isNil()) return tmp;
} else {
neg = true;
}
shift = big2long(otherBignum);
break;
}
other = other.convertToInteger();
}
return bignorm(getRuntime(), neg ? value.shiftLeft((int)shift) : value.shiftRight((int)shift));
}
/** rb_big_aref
*
*/
@JRubyMethod(name = "[]", required = 1)
public RubyFixnum op_aref(IRubyObject other) {
if (other instanceof RubyBignum) {
if (((RubyBignum) other).value.signum() >= 0 || value.signum() == -1) {
return RubyFixnum.zero(getRuntime());
}
return RubyFixnum.one(getRuntime());
}
long position = num2long(other);
if (position < 0 || position > Integer.MAX_VALUE) {
return RubyFixnum.zero(getRuntime());
}
return value.testBit((int)position) ? RubyFixnum.one(getRuntime()) : RubyFixnum.zero(getRuntime());
}
/** rb_big_cmp
*
*/
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
final BigInteger otherValue;
if (other instanceof RubyFixnum) {
otherValue = fix2big((RubyFixnum) other);
} else if (other instanceof RubyBignum) {
otherValue = ((RubyBignum) other).value;
} else if (other instanceof RubyFloat) {
return dbl_cmp(getRuntime(), big2dbl(this), ((RubyFloat) other).getDoubleValue());
} else {
return coerceCmp(context, "<=>", other);
}
// wow, the only time we can use the java protocol ;)
return RubyFixnum.newFixnum(getRuntime(), value.compareTo(otherValue));
}
/** rb_big_eq
*
*/
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(IRubyObject other) {
final BigInteger otherValue;
if (other instanceof RubyFixnum) {
otherValue = fix2big((RubyFixnum) other);
} else if (other instanceof RubyBignum) {
otherValue = ((RubyBignum) other).value;
} else if (other instanceof RubyFloat) {
double a = ((RubyFloat) other).getDoubleValue();
if (Double.isNaN(a)) {
return getRuntime().getFalse();
}
return RubyBoolean.newBoolean(getRuntime(), a == big2dbl(this));
} else {
return other.op_eqq(getRuntime().getCurrentContext(), this);
}
return RubyBoolean.newBoolean(getRuntime(), value.compareTo(otherValue) == 0);
}
/** rb_big_eql
*
*/
@JRubyMethod(name = {"eql?", "==="}, required = 1)
public IRubyObject eql_p(IRubyObject other) {
if (other instanceof RubyBignum) {
return value.compareTo(((RubyBignum)other).value) == 0 ? getRuntime().getTrue() : getRuntime().getFalse();
}
return getRuntime().getFalse();
}
/** rb_big_hash
*
*/
@JRubyMethod(name = "hash")
public RubyFixnum hash() {
return getRuntime().newFixnum(value.hashCode());
}
/** rb_big_to_f
*
*/
@JRubyMethod(name = "to_f")
public IRubyObject to_f() {
return RubyFloat.newFloat(getRuntime(), getDoubleValue());
}
/** rb_big_abs
*
*/
@JRubyMethod(name = "abs")
public IRubyObject abs() {
return RubyBignum.newBignum(getRuntime(), value.abs());
}
/** rb_big_size
*
*/
@JRubyMethod(name = "size")
public IRubyObject size() {
return getRuntime().newFixnum((value.bitLength() + 7) / 8);
}
public static void marshalTo(RubyBignum bignum, MarshalStream output) throws IOException {
output.registerLinkTarget(bignum);
output.write(bignum.value.signum() >= 0 ? '+' : '-');
BigInteger absValue = bignum.value.abs();
byte[] digits = absValue.toByteArray();
boolean oddLengthNonzeroStart = (digits.length % 2 != 0 && digits[0] != 0);
int shortLength = digits.length / 2;
if (oddLengthNonzeroStart) {
shortLength++;
}
output.writeInt(shortLength);
for (int i = 1; i <= shortLength * 2 && i <= digits.length; i++) {
output.write(digits[digits.length - i]);
}
if (oddLengthNonzeroStart) {
// Pad with a 0
output.write(0);
}
}
public static RubyNumeric unmarshalFrom(UnmarshalStream input) throws IOException {
boolean positive = input.readUnsignedByte() == '+';
int shortLength = input.unmarshalInt();
// BigInteger required a sign byte in incoming array
byte[] digits = new byte[shortLength * 2 + 1];
for (int i = digits.length - 1; i >= 1; i--) {
digits[i] = input.readSignedByte();
}
BigInteger value = new BigInteger(digits);
if (!positive) {
value = value.negate();
}
RubyNumeric result = bignorm(input.getRuntime(), value);
input.registerLinkTarget(result);
return result;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Binding;
import org.jruby.runtime.Frame;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
/**
* @author jpetersen
*/
@JRubyClass(name="Binding")
public class RubyBinding extends RubyObject {
private Binding binding;
public RubyBinding(Ruby runtime, RubyClass rubyClass, Binding binding) {
super(runtime, rubyClass);
this.binding = binding;
}
private RubyBinding(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass);
}
private static ObjectAllocator BINDING_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyBinding instance = new RubyBinding(runtime, klass);
return instance;
}
};
public static RubyClass createBindingClass(Ruby runtime) {
RubyClass bindingClass = runtime.defineClass("Binding", runtime.getObject(), BINDING_ALLOCATOR);
runtime.setBinding(bindingClass);
bindingClass.defineAnnotatedMethods(RubyBinding.class);
return bindingClass;
}
public Binding getBinding() {
return binding;
}
// Proc class
public static RubyBinding newBinding(Ruby runtime, Binding binding) {
return new RubyBinding(runtime, runtime.getBinding(), binding);
}
public static RubyBinding newBinding(Ruby runtime) {
ThreadContext context = runtime.getCurrentContext();
// FIXME: We should be cloning, not reusing: frame, scope, dynvars, and potentially iter/block info
Frame frame = context.getCurrentFrame();
Binding binding = new Binding(frame, context.getBindingRubyClass(), context.getCurrentScope());
return new RubyBinding(runtime, runtime.getBinding(), binding);
}
/**
* Create a binding appropriate for a bare "eval", by using the previous (caller's) frame and current
* scope.
*/
public static RubyBinding newBindingForEval(ThreadContext context) {
// This requires some explaining. We use Frame values when executing blocks to fill in
// various values in ThreadContext and EvalState.eval like rubyClass, cref, and self.
// Largely, for an eval that is using the logical binding at a place where the eval is
// called we mostly want to use the current frames value for this. Most importantly,
// we need that self (JRUBY-858) at this point. We also need to make sure that returns
// jump to the right place (which happens to be the previous frame). Lastly, we do not
// want the current frames klazz since that will be the klazz represented of self. We
// want the class right before the eval (well we could use cref class for this too I think).
// Once we end up having Frames created earlier I think the logic of stuff like this will
// be better since we won't be worried about setting Frame to setup other variables/stacks
// but just making sure Frame itself is correct...
Frame previousFrame = context.getPreviousFrame();
Frame currentFrame = context.getCurrentFrame();
currentFrame.setKlazz(previousFrame.getKlazz());
// Set jump target to whatever the previousTarget thinks is good.
// currentFrame.setJumpTarget(previousFrame.getJumpTarget() != null ? previousFrame.getJumpTarget() : previousFrame);
Binding binding = new Binding(previousFrame, context.getBindingRubyClass(), context.getCurrentScope());
Ruby runtime = context.getRuntime();
return new RubyBinding(runtime, runtime.getBinding(), binding);
}
@JRubyMethod(name = "initialize", visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context) {
// FIXME: We should be cloning, not reusing: frame, scope, dynvars, and potentially iter/block info
Frame frame = context.getCurrentFrame();
binding = new Binding(frame, context.getBindingRubyClass(), context.getCurrentScope());
return this;
}
@JRubyMethod(name = "initialize_copy", required = 1, visibility = Visibility.PRIVATE)
@Override
public IRubyObject initialize_copy(IRubyObject other) {
RubyBinding otherBinding = (RubyBinding)other;
binding = otherBinding.binding;
return this;
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
/**
*
* @author jpetersen
*/
@JRubyClass(name={"TrueClass", "FalseClass"})
public class RubyBoolean extends RubyObject {
public RubyBoolean(Ruby runtime, boolean value) {
super(runtime, (value ? runtime.getTrueClass() : runtime.getFalseClass()), // Don't initialize with class
false); // Don't put in object space
if (!value) flags = FALSE_F;
}
@Override
public int getNativeTypeIndex() {
return (flags & FALSE_F) == 0 ? ClassIndex.TRUE : ClassIndex.FALSE;
}
@Override
public boolean isImmediate() {
return true;
}
@Override
public RubyClass getSingletonClass() {
return metaClass;
}
@Override
public Class<?> getJavaClass() {
return boolean.class;
}
public static RubyClass createFalseClass(Ruby runtime) {
RubyClass falseClass = runtime.defineClass("FalseClass", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setFalseClass(falseClass);
falseClass.index = ClassIndex.FALSE;
falseClass.defineAnnotatedMethods(False.class);
falseClass.getMetaClass().undefineMethod("new");
return falseClass;
}
public static RubyClass createTrueClass(Ruby runtime) {
RubyClass trueClass = runtime.defineClass("TrueClass", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setTrueClass(trueClass);
trueClass.index = ClassIndex.TRUE;
trueClass.defineAnnotatedMethods(True.class);
trueClass.getMetaClass().undefineMethod("new");
return trueClass;
}
public static RubyBoolean newBoolean(Ruby runtime, boolean value) {
return value ? runtime.getTrue() : runtime.getFalse();
}
public static class False {
@JRubyMethod(name = "&")
public static IRubyObject false_and(IRubyObject f, IRubyObject oth) {
return f;
}
@JRubyMethod(name = "|")
public static IRubyObject false_or(IRubyObject f, IRubyObject oth) {
return oth.isTrue() ? f.getRuntime().getTrue() : f;
}
@JRubyMethod(name = "^")
public static IRubyObject false_xor(IRubyObject f, IRubyObject oth) {
return oth.isTrue() ? f.getRuntime().getTrue() : f;
}
@JRubyMethod(name = "to_s")
public static IRubyObject false_to_s(IRubyObject f) {
return f.getRuntime().newString("false");
}
}
public static class True {
@JRubyMethod(name = "&")
public static IRubyObject true_and(IRubyObject t, IRubyObject oth) {
return oth.isTrue() ? t : t.getRuntime().getFalse();
}
@JRubyMethod(name = "|")
public static IRubyObject true_or(IRubyObject t, IRubyObject oth) {
return t;
}
@JRubyMethod(name = "^")
public static IRubyObject true_xor(IRubyObject t, IRubyObject oth) {
return oth.isTrue() ? t.getRuntime().getFalse() : t;
}
@JRubyMethod(name = "to_s")
public static IRubyObject true_to_s(IRubyObject t) {
return t.getRuntime().newString("true");
}
}
@Override
public RubyFixnum id() {
if ((flags & FALSE_F) == 0) {
return RubyFixnum.newFixnum(getRuntime(), 2);
} else {
return RubyFixnum.zero(getRuntime());
}
}
@Override
public IRubyObject taint(ThreadContext context) {
return this;
}
@Override
public IRubyObject freeze(ThreadContext context) {
return this;
}
public void marshalTo(MarshalStream output) throws java.io.IOException {
output.write(isTrue() ? 'T' : 'F');
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.internal.runtime.methods.JavaMethod;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.CallSite.InlineCachingCallSite;
import org.jruby.runtime.CallType;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ObjectMarshal;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.collections.WeakHashSet;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Class", parent="Module")
public class RubyClass extends RubyModule {
public static final int CS_IDX_INITIALIZE = 0;
public static final String[] CS_NAMES = {
"initialize"
};
private final CallSite[] baseCallSites = new CallSite[CS_NAMES.length];
{
for(int i = 0; i < CS_NAMES.length; i++) {
baseCallSites[i] = new InlineCachingCallSite(CS_NAMES[i], CallType.FUNCTIONAL);
}
}
private CallSite[] extraCallSites;
public static void createClassClass(Ruby runtime, RubyClass classClass) {
classClass.index = ClassIndex.CLASS;
classClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyClass;
}
};
classClass.undefineMethod("module_function");
classClass.undefineMethod("append_features");
classClass.undefineMethod("extend_object");
classClass.defineAnnotatedMethods(RubyClass.class);
classClass.addMethod("new", new SpecificArityNew(classClass, Visibility.PUBLIC));
// This is a non-standard method; have we decided to start extending Ruby?
//classClass.defineFastMethod("subclasses", callbackFactory.getFastOptMethod("subclasses"));
// FIXME: for some reason this dispatcher causes a VerifyError...
//classClass.dispatcher = callbackFactory.createDispatcher(classClass);
}
public static final ObjectAllocator CLASS_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyClass clazz = new RubyClass(runtime);
clazz.allocator = ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR; // Class.allocate object is not allocatable before it is initialized
return clazz;
}
};
public ObjectAllocator getAllocator() {
return allocator;
}
public void setAllocator(ObjectAllocator allocator) {
this.allocator = allocator;
}
@JRubyMethod(name = "allocate")
public IRubyObject allocate() {
if (superClass == null) throw runtime.newTypeError("can't instantiate uninitialized class");
IRubyObject obj = allocator.allocate(runtime, this);
if (obj.getMetaClass().getRealClass() != getRealClass()) throw runtime.newTypeError("wrong instance allocation");
return obj;
}
public CallSite[] getBaseCallSites() {
return baseCallSites;
}
public CallSite[] getExtraCallSites() {
return extraCallSites;
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.CLASS;
}
@Override
public boolean isModule() {
return false;
}
@Override
public boolean isClass() {
return true;
}
@Override
public boolean isSingleton() {
return false;
}
/** boot_defclass
* Create an initial Object meta class before Module and Kernel dependencies have
* squirreled themselves together.
*
* @param runtime we need it
* @return a half-baked meta class for object
*/
public static RubyClass createBootstrapClass(Ruby runtime, String name, RubyClass superClass, ObjectAllocator allocator) {
RubyClass obj;
if (superClass == null ) { // boot the Object class
obj = new RubyClass(runtime);
obj.marshal = DEFAULT_OBJECT_MARSHAL;
} else { // boot the Module and Class classes
obj = new RubyClass(runtime, superClass);
}
obj.setAllocator(allocator);
obj.setBaseName(name);
return obj;
}
private final Ruby runtime;
private ObjectAllocator allocator; // the default allocator
protected ObjectMarshal marshal;
private Set<RubyClass> subclasses;
/** separate path for MetaClass and IncludedModuleWrapper construction
* (rb_class_boot version for MetaClasses)
* no marshal, allocator initialization and addSubclass(this) here!
*/
protected RubyClass(Ruby runtime, RubyClass superClass, boolean objectSpace) {
super(runtime, runtime.getClassClass(), objectSpace);
this.runtime = runtime;
this.superClass = superClass; // this is the only case it might be null here (in MetaClass construction)
}
/** used by CLASS_ALLOCATOR (any Class' class will be a Class!)
* also used to bootstrap Object class
*/
protected RubyClass(Ruby runtime) {
super(runtime, runtime.getClassClass());
this.runtime = runtime;
index = ClassIndex.CLASS;
}
/** rb_class_boot (for plain Classes)
* also used to bootstrap Module and Class classes
*/
protected RubyClass(Ruby runtime, RubyClass superClazz) {
this(runtime);
superClass = superClazz;
marshal = superClazz.marshal; // use parent's marshal
superClazz.addSubclass(this);
infectBy(superClass);
}
/**
* A constructor which allows passing in an array of supplementary call sites.
*/
protected RubyClass(Ruby runtime, RubyClass superClazz, CallSite[] extraCallSites) {
this(runtime);
this.superClass = superClazz;
this.marshal = superClazz.marshal; // use parent's marshal
superClazz.addSubclass(this);
this.extraCallSites = extraCallSites;
infectBy(superClass);
}
/**
* Construct a new class with the given name scoped under Object (global)
* and with Object as its immediate superclass.
* Corresponds to rb_class_new in MRI.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass) {
if (superClass == runtime.getClassClass()) throw runtime.newTypeError("can't make subclass of Class");
if (superClass.isSingleton()) throw runtime.newTypeError("can't make subclass of virtual class");
return new RubyClass(runtime, superClass);
}
/**
* A variation on newClass that allow passing in an array of supplementary
* call sites to improve dynamic invocation.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass, CallSite[] extraCallSites) {
if (superClass == runtime.getClassClass()) throw runtime.newTypeError("can't make subclass of Class");
if (superClass.isSingleton()) throw runtime.newTypeError("can't make subclass of virtual class");
return new RubyClass(runtime, superClass, extraCallSites);
}
/**
* Construct a new class with the given name, allocator, parent class,
* and containing class. If setParent is true, the class's parent will be
* explicitly set to the provided parent (rather than the new class just
* being assigned to a constant in that parent).
* Corresponds to rb_class_new/rb_define_class_id/rb_name_class/rb_set_class_path
* in MRI.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass, String name, ObjectAllocator allocator, RubyModule parent, boolean setParent) {
RubyClass clazz = newClass(runtime, superClass);
clazz.setBaseName(name);
clazz.setAllocator(allocator);
clazz.makeMetaClass(superClass.getMetaClass());
if (setParent) clazz.setParent(parent);
parent.setConstant(name, clazz);
clazz.inherit(superClass);
return clazz;
}
/**
* A variation on newClass that allows passing in an array of supplementary
* call sites to improve dynamic invocation performance.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass, String name, ObjectAllocator allocator, RubyModule parent, boolean setParent, CallSite[] extraCallSites) {
RubyClass clazz = newClass(runtime, superClass, extraCallSites);
clazz.setBaseName(name);
clazz.setAllocator(allocator);
clazz.makeMetaClass(superClass.getMetaClass());
if (setParent) clazz.setParent(parent);
parent.setConstant(name, clazz);
clazz.inherit(superClass);
return clazz;
}
/** rb_make_metaclass
*
*/
@Override
public RubyClass makeMetaClass(RubyClass superClass) {
if (isSingleton()) { // could be pulled down to RubyClass in future
MetaClass klass = new MetaClass(getRuntime(), superClass); // rb_class_boot
setMetaClass(klass);
klass.setAttached(this);
klass.setMetaClass(klass);
klass.setSuperClass(getSuperClass().getRealClass().getMetaClass());
return klass;
} else {
return super.makeMetaClass(superClass);
}
}
@Deprecated
public IRubyObject invoke(ThreadContext context, IRubyObject self, int methodIndex, String name, IRubyObject[] args, CallType callType, Block block) {
return invoke(context, self, name, args, callType, block);
}
public boolean notVisibleAndNotMethodMissing(DynamicMethod method, String name, IRubyObject caller, CallType callType) {
return !method.isCallableFrom(caller, callType) && !name.equals("method_missing");
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
CallType callType, Block block) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, caller, callType, block);
}
return method.call(context, self, this, name, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name, Block block) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, context.getFrameSelf(), CallType.FUNCTIONAL, block);
}
return method.call(context, self, this, name, block);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject[] args, CallType callType, Block block) {
assert args != null;
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, args, caller, callType, block);
}
return method.call(context, self, this, name, args, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject[] args, Block block) {
assert args != null;
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, args, context.getFrameSelf(), CallType.FUNCTIONAL, block);
}
return method.call(context, self, this, name, args, block);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg, CallType callType, Block block) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg, caller, callType, block);
}
return method.call(context, self, this, name, arg, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg, Block block) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg, context.getFrameSelf(), CallType.FUNCTIONAL, block);
}
return method.call(context, self, this, name, arg, block);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, CallType callType, Block block) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, caller, callType, block);
}
return method.call(context, self, this, name, arg0, arg1, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, Block block) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, context.getFrameSelf(), CallType.FUNCTIONAL, block);
}
return method.call(context, self, this, name, arg0, arg1, block);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, CallType callType, Block block) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, arg2, caller, callType, block);
}
return method.call(context, self, this, name, arg0, arg1, arg2, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, arg2, context.getFrameSelf(), CallType.FUNCTIONAL, block);
}
return method.call(context, self, this, name, arg0, arg1, arg2, block);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
CallType callType) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, caller, callType, Block.NULL_BLOCK);
}
return method.call(context, self, this, name);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, context.getFrameSelf(), CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, this, name);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject[] args, CallType callType) {
assert args != null;
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, args, caller, callType, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, args);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject[] args) {
assert args != null;
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, args, context.getFrameSelf(), CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, args);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg, CallType callType) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg, caller, callType, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, arg);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg, context.getFrameSelf(), CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, arg);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, CallType callType) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, caller, callType, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, arg0, arg1);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, context.getFrameSelf(), CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, arg0, arg1);
}
public IRubyObject invoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, CallType callType) {
DynamicMethod method = searchMethod(name);
IRubyObject caller = context.getFrameSelf();
if (shouldCallMethodMissing(method, name, caller, callType)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, arg2, caller, callType, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, arg0, arg1, arg2);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
DynamicMethod method = searchMethod(name);
if (shouldCallMethodMissing(method)) {
return RuntimeHelpers.callMethodMissing(context, self, method, name, arg0, arg1, arg2, context.getFrameSelf(), CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, this, name, arg0, arg1, arg2);
}
private boolean shouldCallMethodMissing(DynamicMethod method) {
return method.isUndefined();
}
private boolean shouldCallMethodMissing(DynamicMethod method, String name, IRubyObject caller, CallType callType) {
return method.isUndefined() || notVisibleAndNotMethodMissing(method, name, caller, callType);
}
public IRubyObject invokeInherited(ThreadContext context, IRubyObject self, IRubyObject subclass) {
DynamicMethod method = getMetaClass().searchMethod("inherited");
if (method.isUndefined()) {
return RuntimeHelpers.callMethodMissing(context, self, method, "inherited", subclass, context.getFrameSelf(), CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, getMetaClass(), "inherited", subclass, Block.NULL_BLOCK);
}
/** rb_class_new_instance
*
*/
public IRubyObject newInstance(ThreadContext context, IRubyObject[] args, Block block) {
IRubyObject obj = allocate();
baseCallSites[CS_IDX_INITIALIZE].call(context, obj, args, block);
return obj;
}
// TODO: replace this with a smarter generated invoker that can handle 0-N args
public static class SpecificArityNew extends JavaMethod {
public SpecificArityNew(RubyModule implClass, Visibility visibility) {
super(implClass, visibility);
}
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
RubyClass cls = (RubyClass)self;
IRubyObject obj = cls.allocate();
cls.baseCallSites[CS_IDX_INITIALIZE].call(context, obj, args, block);
return obj;
}
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, Block block) {
RubyClass cls = (RubyClass)self;
IRubyObject obj = cls.allocate();
cls.baseCallSites[CS_IDX_INITIALIZE].call(context, obj, block);
return obj;
}
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, Block block) {
RubyClass cls = (RubyClass)self;
IRubyObject obj = cls.allocate();
cls.baseCallSites[CS_IDX_INITIALIZE].call(context, obj, arg0, block);
return obj;
}
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block) {
RubyClass cls = (RubyClass)self;
IRubyObject obj = cls.allocate();
cls.baseCallSites[CS_IDX_INITIALIZE].call(context, obj, arg0, arg1, block);
return obj;
}
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
RubyClass cls = (RubyClass)self;
IRubyObject obj = cls.allocate();
cls.baseCallSites[CS_IDX_INITIALIZE].call(context, obj, arg0, arg1, arg2, block);
return obj;
}
}
/** rb_class_initialize
*
*/
@JRubyMethod(name = "initialize", optional = 1, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block block) {
if (superClass != null) {
throw getRuntime().newTypeError("already initialized class");
}
IRubyObject superObject;
if (args.length == 0) {
superObject = getRuntime().getObject();
} else {
superObject = args[0];
checkInheritable(superObject);
}
RubyClass superClazz = (RubyClass) superObject;
superClass = superClazz;
allocator = superClazz.allocator;
makeMetaClass(superClazz.getMetaClass());
marshal = superClazz.marshal;
superClazz.addSubclass(this);
super.initialize(block);
inherit(superClazz);
return this;
}
/** rb_class_init_copy
*
*/
@JRubyMethod(name = "initialize_copy", required = 1)
@Override
public IRubyObject initialize_copy(IRubyObject original){
if (superClass != null) throw runtime.newTypeError("already initialized class");
if (original instanceof MetaClass) throw getRuntime().newTypeError("can't copy singleton class");
super.initialize_copy(original);
allocator = ((RubyClass)original).allocator;
return this;
}
// TODO: Someday, enable.
// @JRubyMethod(name = "subclasses", optional = 1)
public IRubyObject subclasses(ThreadContext context, IRubyObject[] args) {
boolean recursive = false;
if (args.length == 1) {
if (args[0] instanceof RubyBoolean) {
recursive = args[0].isTrue();
} else {
context.getRuntime().newTypeError(args[0], context.getRuntime().fastGetClass("Boolean"));
}
}
return RubyArray.newArray(context.getRuntime(), subclasses(recursive)).freeze(context);
}
public Collection subclasses(boolean includeDescendants) {
if (subclasses != null) {
Collection<RubyClass> mine = new ArrayList<RubyClass>(subclasses);
if (includeDescendants) {
for (RubyClass i: subclasses) {
mine.addAll(i.subclasses(includeDescendants));
}
}
return mine;
} else {
return Collections.EMPTY_LIST;
}
}
public synchronized void addSubclass(RubyClass subclass) {
if (subclasses == null) subclasses = new WeakHashSet<RubyClass>();
subclasses.add(subclass);
}
public Ruby getClassRuntime() {
return runtime;
}
public RubyClass getRealClass() {
return this;
}
@JRubyMethod(name = "inherited", required = 1)
public IRubyObject inherited(ThreadContext context, IRubyObject arg) {
return context.getRuntime().getNil();
}
/** rb_class_inherited (reversed semantics!)
*
*/
public void inherit(RubyClass superClazz) {
if (superClazz == null) superClazz = getRuntime().getObject();
superClazz.invokeInherited(getRuntime().getCurrentContext(), superClazz, this);
}
/** Return the real super class of this class.
*
* rb_class_superclass
*
*/
@JRubyMethod(name = "superclass")
public IRubyObject superclass(ThreadContext context) {
RubyClass superClazz = superClass;
if (superClazz == null) throw context.getRuntime().newTypeError("uninitialized class");
if (isSingleton()) superClazz = metaClass;
while (superClazz != null && superClazz.isIncluded()) superClazz = superClazz.superClass;
return superClazz != null ? superClazz : context.getRuntime().getNil();
}
/** rb_check_inheritable
*
*/
public static void checkInheritable(IRubyObject superClass) {
if (!(superClass instanceof RubyClass)) {
throw superClass.getRuntime().newTypeError("superclass must be a Class (" + superClass.getMetaClass() + " given)");
}
if (((RubyClass)superClass).isSingleton()) {
throw superClass.getRuntime().newTypeError("can't make subclass of virtual class");
}
}
public final ObjectMarshal getMarshal() {
return marshal;
}
public final void setMarshal(ObjectMarshal marshal) {
this.marshal = marshal;
}
public final void marshal(Object obj, MarshalStream marshalStream) throws IOException {
getMarshal().marshalTo(getRuntime(), obj, this, marshalStream);
}
public final Object unmarshal(UnmarshalStream unmarshalStream) throws IOException {
return getMarshal().unmarshalFrom(getRuntime(), this, unmarshalStream);
}
public static void marshalTo(RubyClass clazz, MarshalStream output) throws java.io.IOException {
output.registerLinkTarget(clazz);
output.writeString(MarshalStream.getPathFromClass(clazz));
}
public static RubyClass unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
String name = RubyString.byteListToString(input.unmarshalString());
RubyClass result = UnmarshalStream.getClassFromPath(input.getRuntime(), name);
input.registerLinkTarget(result);
return result;
}
protected static final ObjectMarshal DEFAULT_OBJECT_MARSHAL = new ObjectMarshal() {
public void marshalTo(Ruby runtime, Object obj, RubyClass type,
MarshalStream marshalStream) throws IOException {
IRubyObject object = (IRubyObject)obj;
marshalStream.registerLinkTarget(object);
marshalStream.dumpVariables(object.getVariableList());
}
public Object unmarshalFrom(Ruby runtime, RubyClass type,
UnmarshalStream unmarshalStream) throws IOException {
IRubyObject result = type.allocate();
unmarshalStream.registerLinkTarget(result);
unmarshalStream.defaultVariablesUnmarshal(result);
return result;
}
};
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
public class RubyClassPathVariable extends RubyObject {
public static void createClassPathVariable(Ruby runtime) {
RubyClassPathVariable self = new RubyClassPathVariable(runtime);
runtime.getEnumerable().extend_object(self);
runtime.defineReadonlyVariable("$CLASSPATH", self);
self.getMetaClass().defineAnnotatedMethods(RubyClassPathVariable.class);
}
private RubyClassPathVariable(Ruby runtime) {
super(runtime, runtime.getObject());
}
@JRubyMethod(name = {"append", "<<"}, required = 1)
public IRubyObject append(IRubyObject obj) throws Exception {
String ss = obj.convertToString().toString();
URL url = getURL(ss);
getRuntime().getJRubyClassLoader().addURL(url);
return this;
}
private URL getURL(String target) throws MalformedURLException {
if(target.indexOf("://") == -1) {
return new File(target).toURI().toURL();
} else {
return new URL(target);
}
}
@JRubyMethod(name = {"size", "length"})
public IRubyObject size() {
return getRuntime().newFixnum(getRuntime().getJRubyClassLoader().getURLs().length);
}
@JRubyMethod(name = "each", frame = true)
public IRubyObject each(Block block) {
URL[] urls = getRuntime().getJRubyClassLoader().getURLs();
ThreadContext ctx = getRuntime().getCurrentContext();
for(int i=0,j=urls.length;i<j;i++) {
block.yield(ctx, getRuntime().newString(urls[i].toString()));
}
return getRuntime().getNil();
}
@JRubyMethod(name = "to_s")
public IRubyObject to_s() {
return callMethod(getRuntime().getCurrentContext(), "to_a").callMethod(getRuntime().getCurrentContext(), "to_s");
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
return callMethod(getRuntime().getCurrentContext(), "to_a").callMethod(getRuntime().getCurrentContext(), "inspect");
}
}// RubyClassPathVariable
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2006 Thomas E Enebo <enebo@acm.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/** Implementation of the Comparable module.
*
*/
@JRubyModule(name="Comparable")
public class RubyComparable {
public static RubyModule createComparable(Ruby runtime) {
RubyModule comparableModule = runtime.defineModule("Comparable");
runtime.setComparable(comparableModule);
comparableModule.defineAnnotatedMethods(RubyComparable.class);
return comparableModule;
}
/* ================
* Utility Methods
* ================
*/
/** rb_cmpint
*
*/
public static int cmpint(ThreadContext context, IRubyObject val, IRubyObject a, IRubyObject b) {
if (val.isNil()) cmperr(a, b);
if (val instanceof RubyFixnum) return RubyNumeric.fix2int((RubyFixnum) val);
if (val instanceof RubyBignum) return ((RubyBignum) val).getValue().signum() == -1 ? 1 : -1;
RubyFixnum zero = RubyFixnum.zero(context.getRuntime());
if (val.callMethod(context, MethodIndex.OP_GT, ">", zero).isTrue()) return 1;
if (val.callMethod(context, MethodIndex.OP_LT, "<", zero).isTrue()) return -1;
return 0;
}
/** rb_cmperr
*
*/
public static IRubyObject cmperr(IRubyObject recv, IRubyObject other) {
IRubyObject target;
if (other.isImmediate() || !(other.isNil() || other.isTrue() || other == recv.getRuntime().getFalse())) {
target = other.inspect();
} else {
target = other.getType();
}
throw recv.getRuntime().newArgumentError("comparison of " + recv.getType() + " with " + target + " failed");
}
/* ================
* Module Methods
* ================
*/
/** cmp_equal (cmp_eq inlined here)
*
*/
@JRubyMethod(name = "==", required = 1)
public static IRubyObject op_equal(ThreadContext context, IRubyObject recv, IRubyObject other) {
Ruby runtime = context.getRuntime();
if (recv == other) return runtime.getTrue();
try {
IRubyObject result = recv.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", other);
return RubyBoolean.newBoolean(runtime, cmpint(context, result, recv, other) == 0);
} catch (RaiseException e) {
if (e.getException().kind_of_p(context, runtime.getStandardError()).isTrue()) {
return runtime.getNil();
} else {
throw e;
}
}
}
/** cmp_gt
*
*/
// <=> may return nil in many circumstances, e.g. 3 <=> NaN
@JRubyMethod(name = ">", required = 1)
public static RubyBoolean op_gt(ThreadContext context, IRubyObject recv, IRubyObject other) {
IRubyObject result = recv.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", other);
if (result.isNil()) cmperr(recv, other);
return RubyBoolean.newBoolean(context.getRuntime(), cmpint(context, result, recv, other) > 0);
}
/** cmp_ge
*
*/
@JRubyMethod(name = ">=", required = 1)
public static RubyBoolean op_ge(ThreadContext context, IRubyObject recv, IRubyObject other) {
IRubyObject result = recv.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", other);
if (result.isNil()) cmperr(recv, other);
return RubyBoolean.newBoolean(context.getRuntime(), cmpint(context, result, recv, other) >= 0);
}
/** cmp_lt
*
*/
@JRubyMethod(name = "<", required = 1)
public static RubyBoolean op_lt(ThreadContext context, IRubyObject recv, IRubyObject other) {
IRubyObject result = recv.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", other);
if (result.isNil()) cmperr(recv, other);
return RubyBoolean.newBoolean(context.getRuntime(), cmpint(context, result, recv, other) < 0);
}
/** cmp_le
*
*/
@JRubyMethod(name = "<=", required = 1)
public static RubyBoolean op_le(ThreadContext context, IRubyObject recv, IRubyObject other) {
IRubyObject result = recv.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", other);
if (result.isNil()) cmperr(recv, other);
return RubyBoolean.newBoolean(context.getRuntime(), cmpint(context, result, recv, other) <= 0);
}
/** cmp_between
*
*/
@JRubyMethod(name = "between?", required = 2)
public static RubyBoolean between_p(ThreadContext context, IRubyObject recv, IRubyObject first, IRubyObject second) {
return context.getRuntime().newBoolean(op_lt(context, recv, first).isFalse() && op_gt(context, recv, second).isFalse());
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.util.Numeric.f_abs;
import static org.jruby.util.Numeric.f_abs2;
import static org.jruby.util.Numeric.f_add;
import static org.jruby.util.Numeric.f_arg;
import static org.jruby.util.Numeric.f_conjugate;
import static org.jruby.util.Numeric.f_denominator;
import static org.jruby.util.Numeric.f_div;
import static org.jruby.util.Numeric.f_divmod;
import static org.jruby.util.Numeric.f_equal_p;
import static org.jruby.util.Numeric.f_exact_p;
import static org.jruby.util.Numeric.f_expt;
import static org.jruby.util.Numeric.f_gt_p;
import static org.jruby.util.Numeric.f_inspect;
import static org.jruby.util.Numeric.f_lcm;
import static org.jruby.util.Numeric.f_mul;
import static org.jruby.util.Numeric.f_negate;
import static org.jruby.util.Numeric.f_negative_p;
import static org.jruby.util.Numeric.f_numerator;
import static org.jruby.util.Numeric.f_one_p;
import static org.jruby.util.Numeric.f_polar;
import static org.jruby.util.Numeric.f_quo;
import static org.jruby.util.Numeric.f_scalar_p;
import static org.jruby.util.Numeric.f_sub;
import static org.jruby.util.Numeric.f_to_f;
import static org.jruby.util.Numeric.f_to_i;
import static org.jruby.util.Numeric.f_to_r;
import static org.jruby.util.Numeric.f_to_s;
import static org.jruby.util.Numeric.f_xor;
import static org.jruby.util.Numeric.f_zero_p;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Arity;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.Frame;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.Numeric;
/**
* 1.9 complex.c as of revision: 18876
*/
@JRubyClass(name = "Complex", parent = "Numeric")
public class RubyComplex extends RubyNumeric {
public static RubyClass createComplexClass(Ruby runtime) {
RubyClass complexc = runtime.defineClass("Complex", runtime.getNumeric(), COMPLEX_ALLOCATOR); // because one can Complex.send(:allocate)
runtime.setComplex(complexc);
complexc.index = ClassIndex.COMPLEX;
complexc.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyComplex;
}
};
ThreadContext context = runtime.getCurrentContext();
complexc.callMethod(context, "private_class_method", runtime.newSymbol("allocate"));
complexc.defineAnnotatedMethods(RubyComplex.class);
String[]undefined = {"<", "<=", "<=>", ">", ">=", "between?", "divmod",
"floor", "ceil", "modulo", "round", "step", "truncate"};
for (String undef : undefined) {
complexc.undefineMethod(undef);
}
complexc.defineConstant("I", RubyComplex.newComplexConvert(context, RubyFixnum.zero(runtime), RubyFixnum.one(runtime)));
return complexc;
}
private static ObjectAllocator COMPLEX_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyComplex(runtime, klass, RubyFixnum.zero(runtime), RubyFixnum.zero(runtime));
}
};
/** internal
*
*/
private RubyComplex(Ruby runtime, IRubyObject clazz, IRubyObject real, IRubyObject image) {
super(runtime, (RubyClass)clazz);
this.real = real;
this.image = image;
}
/** rb_complex_raw
*
*/
static RubyComplex newComplexRaw(Ruby runtime, IRubyObject x, RubyObject y) {
return new RubyComplex(runtime, runtime.getComplex(), x, y);
}
/** rb_complex_raw1
*
*/
static RubyComplex newComplexRaw(Ruby runtime, IRubyObject x) {
return new RubyComplex(runtime, runtime.getComplex(), x, RubyFixnum.zero(runtime));
}
/** rb_complex_new1
*
*/
public static IRubyObject newComplexCanonicalize(ThreadContext context, IRubyObject x) {
return newComplexCanonicalize(context, x, RubyFixnum.zero(context.getRuntime()));
}
/** rb_complex_new
*
*/
public static IRubyObject newComplexCanonicalize(ThreadContext context, IRubyObject x, IRubyObject y) {
return canonicalizeInternal(context, context.getRuntime().getComplex(), x, y);
}
/** rb_complex_polar
*
*/
static IRubyObject newComplexPolar(ThreadContext context, IRubyObject x, IRubyObject y) {
return polar(context, context.getRuntime().getComplex(), x, y);
}
/** f_complex_new1
*
*/
static IRubyObject newComplex(ThreadContext context, IRubyObject clazz, IRubyObject x) {
return newComplex(context, clazz, x, RubyFixnum.zero(context.getRuntime()));
}
/** f_complex_new2
*
*/
static IRubyObject newComplex(ThreadContext context, IRubyObject clazz, IRubyObject x, IRubyObject y) {
assert !(x instanceof RubyComplex);
return canonicalizeInternal(context, clazz, x, y);
}
/** f_complex_new_bang2
*
*/
static RubyComplex newComplexBang(ThreadContext context, IRubyObject clazz, IRubyObject x, IRubyObject y) {
assert x instanceof RubyComplex && y instanceof RubyComplex;
return new RubyComplex(context.getRuntime(), clazz, x, y);
}
/** f_complex_new_bang1
*
*/
public static RubyComplex newComplexBang(ThreadContext context, IRubyObject clazz, IRubyObject x) {
assert x instanceof RubyComplex;
return newComplexBang(context, clazz, x, RubyFixnum.zero(context.getRuntime()));
}
private IRubyObject real;
private IRubyObject image;
IRubyObject getImage() {
return image;
}
IRubyObject getReal() {
return real;
}
/** m_cos
*
*/
private static IRubyObject m_cos(ThreadContext context, IRubyObject x) {
if (f_scalar_p(context, x).isTrue()) return RubyMath.cos(x, x);
RubyComplex complex = (RubyComplex)x;
return newComplex(context, context.getRuntime().getComplex(),
f_mul(context, RubyMath.cos(x, complex.real), RubyMath.cosh(x, complex.image)),
f_mul(context, f_negate(context, RubyMath.sin(x, complex.real)), RubyMath.sinh(x, complex.image)));
}
/** m_sin
*
*/
private static IRubyObject m_sin(ThreadContext context, IRubyObject x) {
if (f_scalar_p(context, x).isTrue()) return RubyMath.sin(x, x);
RubyComplex complex = (RubyComplex)x;
return newComplex(context, context.getRuntime().getComplex(),
f_mul(context, RubyMath.sin(x, complex.real), RubyMath.cosh(x, complex.image)),
f_mul(context, RubyMath.cos(x, complex.real), RubyMath.sinh(x, complex.image)));
}
/** m_sqrt
*
*/
private static IRubyObject m_sqrt(ThreadContext context, IRubyObject x) {
if (f_scalar_p(context, x).isTrue()) {
if (!f_negative_p(context, x)) return RubyMath.sqrt(x, x);
return newComplex(context, context.getRuntime().getComplex(),
RubyFixnum.zero(context.getRuntime()),
RubyMath.sqrt(x, f_negate(context, x)));
} else {
RubyComplex complex = (RubyComplex)x;
if (f_negative_p(context, complex.image)) {
return f_conjugate(context, m_sqrt(context, f_conjugate(context, x)));
} else {
IRubyObject a = f_abs(context, x);
IRubyObject two = RubyFixnum.two(context.getRuntime());
return newComplex(context, context.getRuntime().getComplex(),
RubyMath.sqrt(x, f_div(context, f_add(context, a, complex.real), two)),
RubyMath.sqrt(x, f_div(context, f_sub(context, a, complex.real), two)));
}
}
}
/** nucomp_s_new_bang
*
*/
@Deprecated
public static IRubyObject newInstanceBang(ThreadContext context, IRubyObject recv, IRubyObject[]args) {
switch (args.length) {
case 1: return newInstanceBang(context, recv, args[0]);
case 2: return newInstanceBang(context, recv, args[0], args[1]);
}
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 1);
return null;
}
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject newInstanceBang(ThreadContext context, IRubyObject recv, IRubyObject real) {
if (!(real instanceof RubyNumeric)) real = f_to_i(context, real);
return new RubyComplex(context.getRuntime(), recv, real, RubyFixnum.zero(context.getRuntime()));
}
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject newInstanceBang(ThreadContext context, IRubyObject recv, IRubyObject real, IRubyObject image) {
if (!(real instanceof RubyNumeric)) real = f_to_i(context, real);
if (!(image instanceof RubyNumeric)) image = f_to_i(context, image);
return new RubyComplex(context.getRuntime(), recv, real, image);
}
/** nucomp_real_check (might go to bimorphic)
*
*/
private static void realCheck(ThreadContext context, IRubyObject num) {
switch (num.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
case ClassIndex.RATIONAL:
break;
default:
if (!(num instanceof RubyNumeric ) || !f_scalar_p(context, num).isTrue()) {
throw context.getRuntime().newArgumentError("not a real");
}
}
}
/** nucomp_s_canonicalize_internal
*
*/
private static final boolean CL_CANNON = true;
private static IRubyObject canonicalizeInternal(ThreadContext context, IRubyObject clazz, IRubyObject real, IRubyObject image) {
if (f_zero_p(context, image) &&
((RubyModule)clazz).fastHasConstant("Unify") &&
(!CL_CANNON ||
(!(real instanceof RubyFloat) &&
!(image instanceof RubyFloat)))) {
return real;
} else if (f_scalar_p(context, real).isTrue() &&
f_scalar_p(context, image).isTrue()) {
return new RubyComplex(context.getRuntime(), clazz, real, image);
} else if (f_scalar_p(context, real).isTrue()) {
RubyComplex complex = (RubyComplex)image;
return new RubyComplex(context.getRuntime(), clazz,
f_sub(context, real, complex.image),
f_add(context, RubyFixnum.zero(context.getRuntime()), complex.real));
} else if (f_scalar_p(context, image).isTrue()) {
RubyComplex complex = (RubyComplex)real;
return new RubyComplex(context.getRuntime(), clazz,
complex.real,
f_add(context, complex.image, image));
} else {
RubyComplex complex1 = (RubyComplex)real;
RubyComplex complex2 = (RubyComplex)image;
return new RubyComplex(context.getRuntime(), clazz,
f_sub(context, complex1.real, complex2.image),
f_add(context, complex1.image, complex2.real));
}
}
/** nucomp_s_new
*
*/
@Deprecated
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject[]args) {
switch (args.length) {
case 1: return newInstance(context, recv, args[0]);
case 2: return newInstance(context, recv, args[0], args[1]);
}
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 1);
return null;
}
@JRubyMethod(name = {"new", "rect", "rectangular"}, meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject real) {
realCheck(context, real);
return canonicalizeInternal(context, recv, real, RubyFixnum.zero(context.getRuntime()));
}
@JRubyMethod(name = {"new", "rect", "rectangular"}, meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject real, IRubyObject image) {
realCheck(context, real);
realCheck(context, image);
return canonicalizeInternal(context, recv, real, image);
}
/** f_complex_polar
*
*/
private static IRubyObject f_complex_polar(ThreadContext context, IRubyObject clazz, IRubyObject x, IRubyObject y) {
assert !(x instanceof RubyComplex) && !(y instanceof RubyComplex);
return canonicalizeInternal(context, clazz,
f_mul(context, x, m_cos(context, y)),
f_mul(context, x, m_sin(context, y)));
}
/** nucomp_s_polar
*
*/
@JRubyMethod(name = "polar", meta = true)
public static IRubyObject polar(ThreadContext context, IRubyObject clazz, IRubyObject abs, IRubyObject arg) {
return f_complex_polar(context, clazz, abs, arg);
}
/** rb_Complex1
*
*/
public static IRubyObject newComplexConvert(ThreadContext context, IRubyObject x) {
return newComplexConvert(context, x, RubyFixnum.zero(context.getRuntime()));
}
/** rb_Complex/rb_Complex2
*
*/
public static IRubyObject newComplexConvert(ThreadContext context, IRubyObject x, IRubyObject y) {
return convert(context, context.getRuntime().getComplex(), x, y);
}
@Deprecated
public static IRubyObject convert(ThreadContext context, IRubyObject clazz, IRubyObject[]args) {
switch (args.length) {
case 0: return convert(context, clazz);
case 1: return convert(context, clazz, args[0]);
case 2: return convert(context, clazz, args[0], args[1]);
}
Arity.raiseArgumentError(context.getRuntime(), args.length, 0, 2);
return null;
}
/** nucomp_s_convert
*
*/
@JRubyMethod(name = "convert", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject convert(ThreadContext context, IRubyObject recv) {
IRubyObject nil = context.getRuntime().getNil();
return convertCommon(context, recv, nil, nil);
}
/** nucomp_s_convert
*
*/
@JRubyMethod(name = "convert", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject convert(ThreadContext context, IRubyObject recv, IRubyObject a1) {
return convertCommon(context, recv, a1, context.getRuntime().getNil());
}
/** nucomp_s_convert
*
*/
@JRubyMethod(name = "convert", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject convert(ThreadContext context, IRubyObject recv, IRubyObject a1, IRubyObject a2) {
return convertCommon(context, recv, a1, a2);
}
private static IRubyObject convertCommon(ThreadContext context, IRubyObject recv, IRubyObject a1, IRubyObject a2) {
Frame frame = context.getCurrentFrame();
IRubyObject backref = frame.getBackRef();
if (backref != null && backref instanceof RubyMatchData) ((RubyMatchData)backref).use();
if (a1 instanceof RubyString) a1 = str_to_c_strict(context, a1);
if (a2 instanceof RubyString) a2 = str_to_c_strict(context, a2);
frame.setBackRef(backref);
if (a1 instanceof RubyComplex) {
RubyComplex a1Complex = (RubyComplex)a1;
if (!(a1Complex.image instanceof RubyFloat) && f_zero_p(context, a1Complex.image)) {
a1 = a1Complex.real;
}
}
if (a2 instanceof RubyComplex) {
RubyComplex a2Complex = (RubyComplex)a2;
if (!(a2Complex.image instanceof RubyFloat) && f_zero_p(context, a2Complex.image)) {
a2 = a2Complex.real;
}
}
if (a1 instanceof RubyComplex) {
if (a2.isNil() || f_zero_p(context, a2)) return a1;
}
return a2.isNil() ? newInstance(context, recv, a1) : newInstance(context, recv, a1, a2);
}
/** nucomp_real
*
*/
@JRubyMethod(name = "real")
public IRubyObject real() {
return real;
}
/** nucomp_image
*
*/
@JRubyMethod(name = {"image", "imag"})
public IRubyObject image() {
return image;
}
/** nucomp_add
*
*/
@JRubyMethod(name = "+")
public IRubyObject op_add(ThreadContext context, IRubyObject other) {
if (other instanceof RubyComplex) {
RubyComplex otherComplex = (RubyComplex)other;
return newComplex(context, getMetaClass(),
f_add(context, real, otherComplex.real),
f_add(context, image, otherComplex.image));
} else if (other instanceof RubyNumeric && f_scalar_p(context, other).isTrue()) {
return newComplex(context, getMetaClass(), f_add(context, real, other), image);
}
return coerceBin(context, "+", other);
}
/** nucomp_sub
*
*/
@JRubyMethod(name = "-")
public IRubyObject op_sub(ThreadContext context, IRubyObject other) {
if (other instanceof RubyComplex) {
RubyComplex otherComplex = (RubyComplex)other;
return newComplex(context, getMetaClass(),
f_sub(context, real, otherComplex.real),
f_sub(context, image, otherComplex.image));
} else if (other instanceof RubyNumeric && f_scalar_p(context, other).isTrue()) {
return newComplex(context, getMetaClass(), f_sub(context, real, other), image);
}
return coerceBin(context, "-", other);
}
/** nucomp_mul
*
*/
@JRubyMethod(name = "*")
public IRubyObject op_mul(ThreadContext context, IRubyObject other) {
if (other instanceof RubyComplex) {
RubyComplex otherComplex = (RubyComplex)other;
IRubyObject realp = f_sub(context,
f_mul(context, real, otherComplex.real),
f_mul(context, image, otherComplex.image));
IRubyObject imagep = f_add(context,
f_mul(context, real, otherComplex.image),
f_mul(context, image, otherComplex.real));
return newComplex(context, getMetaClass(), realp, imagep);
} else if (other instanceof RubyNumeric && f_scalar_p(context, other).isTrue()) {
return newComplex(context, getMetaClass(),
f_mul(context, real, other),
f_mul(context, image, other));
}
return coerceBin(context, "*", other);
}
/** nucomp_div
*
*/
@JRubyMethod(name = "/")
public IRubyObject op_div(ThreadContext context, IRubyObject other) {
if (other instanceof RubyComplex) {
RubyComplex otherComplex = (RubyComplex)other;
if (real instanceof RubyFloat || image instanceof RubyFloat ||
otherComplex.real instanceof RubyFloat || otherComplex.image instanceof RubyFloat) {
IRubyObject magn = RubyMath.hypot(this, otherComplex.real, otherComplex.image);
IRubyObject tmp = newComplexBang(context, getMetaClass(),
f_quo(context, otherComplex.real, magn),
f_quo(context, otherComplex.image, magn));
return f_quo(context, f_mul(context, this, f_conjugate(context, tmp)), magn);
}
return f_quo(context, f_mul(context, this, f_conjugate(context, other)), f_abs2(context, other));
} else if (other instanceof RubyNumeric && f_scalar_p(context, other).isTrue()) {
return newComplex(context, getMetaClass(),
f_quo(context, real, other),
f_quo(context, image, other));
}
return coerceBin(context, "/", other);
}
/** nucomp_fdiv / nucomp_quo
*
*/
@JRubyMethod(name = {"fdiv", "quo"})
public IRubyObject fdiv(ThreadContext context, IRubyObject other) {
IRubyObject complex = newComplex(context, getMetaClass(),
f_to_f(context, real),
f_to_f(context, image));
return f_div(context, complex, other);
}
/** nucomp_expt
*
*/
@JRubyMethod(name = "**")
public IRubyObject op_expt(ThreadContext context, IRubyObject other) {
if (f_zero_p(context, other)) {
return newComplexBang(context, getMetaClass(), RubyFixnum.one(context.getRuntime()));
} else if (other instanceof RubyRational && f_one_p(context, f_denominator(context, other))) {
other = f_numerator(context, other);
}
if (other instanceof RubyComplex) {
RubyArray a = f_polar(context, this).convertToArray();
IRubyObject r = a.eltInternal(0);
IRubyObject theta = a.eltInternal(1);
RubyComplex otherComplex = (RubyComplex)other;
IRubyObject nr = RubyMath.exp(this, f_sub(context,
f_mul(context, otherComplex.real, RubyMath.log(this, r)),
f_mul(context, otherComplex.image, theta)));
IRubyObject ntheta = f_add(context,
f_mul(context, theta, otherComplex.real),
f_mul(context, otherComplex.image, RubyMath.log(this, r)));
return polar(context, getMetaClass(), nr, ntheta);
} else if (other instanceof RubyInteger) {
IRubyObject one = RubyFixnum.one(context.getRuntime());
if (f_gt_p(context, other, RubyFixnum.zero(context.getRuntime())).isTrue()) {
IRubyObject x = this;
IRubyObject z = x;
IRubyObject n = f_sub(context, other, one);
IRubyObject two = RubyFixnum.two(context.getRuntime());
while (!f_zero_p(context, n)) {
RubyArray a = f_divmod(context, n, two).convertToArray();
while (f_zero_p(context, a.eltInternal(1))) {
RubyComplex xComplex = (RubyComplex)x;
x = newComplex(context, getMetaClass(),
f_sub(context, f_mul(context, xComplex.real, xComplex.real),
f_mul(context, xComplex.image, xComplex.image)),
f_mul(context, f_mul(context, two, xComplex.real), xComplex.image));
n = a.eltInternal(0);
a = f_divmod(context, n, two).convertToArray();
}
z = f_mul(context, z, x);
n = f_sub(context, n, one);
}
return z;
}
return f_expt(context, f_div(context, f_to_r(context, one), this), f_negate(context, other));
} else if (other instanceof RubyNumeric && f_scalar_p(context, other).isTrue()) {
RubyArray a = f_polar(context, this).convertToArray();
IRubyObject r = a.eltInternal(0);
IRubyObject theta = a.eltInternal(1);
return f_complex_polar(context, getMetaClass(), f_expt(context, r, other), f_mul(context, theta, other));
}
return coerceBin(context, "**", other);
}
/** nucomp_equal_p
*
*/
@JRubyMethod(name = "==")
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
if (other instanceof RubyComplex) {
RubyComplex otherComplex = (RubyComplex)other;
if (f_equal_p(context, real, otherComplex.real) && f_equal_p(context, image, otherComplex.image)) return context.getRuntime().getTrue();
return context.getRuntime().getFalse();
} else if (other instanceof RubyNumeric && f_scalar_p(context, other).isTrue()) {
if (f_equal_p(context, real, other) && f_zero_p(context, image)) return context.getRuntime().getTrue();
return context.getRuntime().getFalse();
}
return f_equal_p(context, other, this) ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
/** nucomp_coerce
*
*/
@JRubyMethod(name = "coerce")
public IRubyObject coerce(ThreadContext context, IRubyObject other) {
if (other instanceof RubyNumeric && f_scalar_p(context, other).isTrue()) {
return context.getRuntime().newArray(newComplexBang(context, getMetaClass(), other), this);
}
throw context.getRuntime().newTypeError(other.getMetaClass().getName() + " can't be coerced into " + getMetaClass().getName());
}
/** nucomp_abs
*
*/
@JRubyMethod(name = {"abs", "magnitude"})
public IRubyObject abs(ThreadContext context) {
return RubyMath.hypot(this, real, image);
}
/** nucomp_abs2
*
*/
@JRubyMethod(name = "abs2")
public IRubyObject abs2(ThreadContext context) {
return f_add(context,
f_mul(context, real, real),
f_mul(context, image, image));
}
/** nucomp_arg
*
*/
@JRubyMethod(name = {"arg", "angle"})
public IRubyObject arg(ThreadContext context) {
return RubyMath.atan2(this, image, real);
}
/** nucomp_polar
*
*/
@JRubyMethod(name = "polar")
public IRubyObject polar(ThreadContext context) {
return context.getRuntime().newArray(f_abs(context, this), f_arg(context, this));
}
/** nucomp_conjugate
*
*/
@JRubyMethod(name = {"conjugate", "conj", "~"})
public IRubyObject conjugate(ThreadContext context) {
return newComplex(context, getMetaClass(), real, f_negate(context, image));
}
/** nucomp_real_p
*
*/
//@JRubyMethod(name = "real?")
public IRubyObject real_p(ThreadContext context) {
return context.getRuntime().getFalse();
}
/** nucomp_complex_p
*
*/
// @JRubyMethod(name = "complex?")
public IRubyObject complex_p(ThreadContext context) {
return context.getRuntime().getTrue();
}
/** nucomp_exact_p
*
*/
// @JRubyMethod(name = "exact?")
public IRubyObject exact_p(ThreadContext context) {
return (f_exact_p(context, real).isTrue() && f_exact_p(context, image).isTrue()) ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
/** nucomp_exact_p
*
*/
// @JRubyMethod(name = "inexact?")
public IRubyObject inexact_p(ThreadContext context) {
return exact_p(context).isTrue() ? context.getRuntime().getFalse() : context.getRuntime().getTrue();
}
/** nucomp_denominator
*
*/
@JRubyMethod(name = "denominator")
public IRubyObject demoninator(ThreadContext context) {
return f_lcm(context, f_denominator(context, real), f_denominator(context, image));
}
/** nucomp_numerator
*
*/
@JRubyMethod(name = "numerator")
public IRubyObject numerator(ThreadContext context) {
IRubyObject cd = callMethod(context, "denominator");
return newComplex(context, getMetaClass(),
f_mul(context,
f_numerator(context, real),
f_div(context, cd, f_denominator(context, real))),
f_mul(context,
f_numerator(context, image),
f_div(context, cd, f_denominator(context, image))));
}
/** nucomp_hash
*
*/
@JRubyMethod(name = "hash")
public IRubyObject hash(ThreadContext context) {
return f_xor(context, real, image);
}
/** f_signbit
*
*/
private static boolean signbit(ThreadContext context, IRubyObject x) {
if (x instanceof RubyFloat) {
return Double.doubleToLongBits(((RubyFloat)x).getDoubleValue()) < 0;
}
return f_negative_p(context, x);
}
/** f_tpositive_p
*
*/
private static boolean tpositive_p(ThreadContext context, IRubyObject x) {
return !signbit(context, x);
}
/** nucomp_to_s
*
*/
@JRubyMethod(name = "to_s")
public IRubyObject to_s(ThreadContext context) {
boolean impos = tpositive_p(context, image);
RubyString str = f_to_s(context, real).convertToString();
str.cat(impos ? (byte)'+' : (byte)'-');
str.cat(f_to_s(context, f_abs(context, image)).convertToString().getByteList());
str.cat((byte)'i');
return str;
}
/** nucomp_inspect
*
*/
@JRubyMethod(name = "inspect")
public IRubyObject inspect(ThreadContext context) {
boolean impos = tpositive_p(context, image);
RubyString str = context.getRuntime().newString();
str.cat((byte)'(');
str.cat(f_inspect(context, real).convertToString().getByteList());
str.cat(impos ? (byte)'+' : (byte)'-');
str.cat(f_inspect(context, f_abs(context, image)).convertToString().getByteList());
str.cat((byte)'i');
str.cat((byte)')');
return str;
}
/** nucomp_marshal_dump
*
*/
@JRubyMethod(name = "marshal_dump")
public IRubyObject marshal_dump(ThreadContext context) {
return context.getRuntime().newArray(real, image);
}
/** nucomp_marshal_load
*
*/
@JRubyMethod(name = "marshal_load")
public IRubyObject marshal_load(ThreadContext context, IRubyObject arg) {
RubyArray a = arg.convertToArray();
real = a.size() > 0 ? a.eltInternal(0) : context.getRuntime().getNil();
image = a.size() > 1 ? a.eltInternal(1) : context.getRuntime().getNil();
return this;
}
/** nucomp_scalar_p
*
*/
@JRubyMethod(name = "scalar?")
public IRubyObject scalar_p(ThreadContext context) {
return context.getRuntime().getFalse();
}
/** nucomp_to_i
*
*/
@JRubyMethod(name = "to_i")
public IRubyObject to_i(ThreadContext context) {
if (image instanceof RubyFloat || !f_zero_p(context, image)) {
throw context.getRuntime().newRangeError("can't convert " + f_to_s(context, this).convertToString() + " into Integer");
}
return f_to_i(context, real);
}
/** nucomp_to_f
*
*/
@JRubyMethod(name = "to_f")
public IRubyObject to_f(ThreadContext context) {
if (image instanceof RubyFloat || !f_zero_p(context, image)) {
throw context.getRuntime().newRangeError("can't convert " + f_to_s(context, this).convertToString() + " into Float");
}
return f_to_f(context, real);
}
/** nucomp_to_f
*
*/
@JRubyMethod(name = "to_r")
public IRubyObject to_r(ThreadContext context) {
if (image instanceof RubyFloat || !f_zero_p(context, image)) {
throw context.getRuntime().newRangeError("can't convert " + f_to_s(context, this).convertToString() + " into Rational");
}
return f_to_r(context, real);
}
static RubyArray str_to_c_internal(ThreadContext context, IRubyObject recv) {
RubyString s = recv.callMethod(context, "strip").convertToString();
ByteList bytes = s.getByteList();
Ruby runtime = context.getRuntime();
if (bytes.realSize == 0) return runtime.newArray(runtime.getNil(), recv);
IRubyObject sr, si, re;
sr = si = re = runtime.getNil();
boolean po = false;
IRubyObject m = RubyRegexp.newRegexp(runtime, Numeric.ComplexPatterns.comp_pat0).callMethod(context, "match", s);
if (!m.isNil()) {
sr = m.callMethod(context, "[]", RubyFixnum.one(runtime));
si = m.callMethod(context, "[]", RubyFixnum.two(runtime));
re = m.callMethod(context, "post_match");
po = true;
}
if (m.isNil()) {
m = RubyRegexp.newRegexp(runtime, Numeric.ComplexPatterns.comp_pat1).callMethod(context, "match", s);
if (!m.isNil()) {
sr = runtime.getNil();
si = m.callMethod(context, "[]", RubyFixnum.one(runtime));
if (si.isNil()) si = runtime.newString();
IRubyObject t = m.callMethod(context, "[]", RubyFixnum.two(runtime));
if (t.isNil()) t = runtime.newString(new ByteList(new byte[]{'1'}));
si.convertToString().cat(t.convertToString().getByteList());
re = m.callMethod(context, "post_match");
po = false;
}
}
if (m.isNil()) {
m = RubyRegexp.newRegexp(runtime, Numeric.ComplexPatterns.comp_pat2).callMethod(context, "match", s);
if (m.isNil()) return runtime.newArray(runtime.getNil(), recv);
sr = m.callMethod(context, "[]", RubyFixnum.one(runtime));
if (m.callMethod(context, "[]", RubyFixnum.two(runtime)).isNil()) {
si = runtime.getNil();
} else {
si = m.callMethod(context, "[]", RubyFixnum.three(runtime));
IRubyObject t = m.callMethod(context, "[]", RubyFixnum.four(runtime));
if (t.isNil()) t = runtime.newString(new ByteList(new byte[]{'1'}));
si.convertToString().cat(t.convertToString().getByteList());
}
re = m.callMethod(context, "post_match");
po = false;
}
IRubyObject r = RubyFixnum.zero(runtime);
IRubyObject i = r;
if (!sr.isNil()) {
if (sr.callMethod(context, "include?", runtime.newString(new ByteList(new byte[]{'/'}))).isTrue()) {
r = f_to_r(context, sr);
} else if (f_gt_p(context, sr.callMethod(context, "count", runtime.newString(".eE")), RubyFixnum.zero(runtime)).isTrue()) {
r = f_to_f(context, sr);
} else {
r = f_to_i(context, sr);
}
}
if (!si.isNil()) {
if (si.callMethod(context, "include?", runtime.newString(new ByteList(new byte[]{'/'}))).isTrue()) {
i = f_to_r(context, si);
} else if (f_gt_p(context, si.callMethod(context, "count", runtime.newString(".eE")), RubyFixnum.zero(runtime)).isTrue()) {
i = f_to_f(context, si);
} else {
i = f_to_i(context, si);
}
}
return runtime.newArray(po ? newComplexPolar(context, r, i) : newComplexCanonicalize(context, r, i), re);
}
private static IRubyObject str_to_c_strict(ThreadContext context, IRubyObject recv) {
RubyArray a = str_to_c_internal(context, recv);
if (a.eltInternal(0).isNil() || a.eltInternal(1).convertToString().getByteList().length() > 0) {
IRubyObject s = recv.callMethod(context, "inspect");
throw context.getRuntime().newArgumentError("invalid value for Complex: " + s.convertToString());
}
return a.eltInternal(0);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Block;
import org.jruby.runtime.builtin.IRubyObject;
/**
* Placeholder until/if we can support this
*
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
@JRubyClass(name="Continuation")
public class RubyContinuation {
public static void createContinuation(Ruby runtime) {
RubyClass cContinuation = runtime.defineClass("Continuation",runtime.getObject(),runtime.getObject().getAllocator());
cContinuation.defineAnnotatedMethods(RubyContinuation.class);
runtime.setContinuation(cContinuation);
}
@JRubyMethod(name = {"call", "[]"}, rest = true, frame = true)
public static IRubyObject call(IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
throw recv.getRuntime().newNotImplementedError("Continuations are not implemented in JRuby and will not work");
}
}// RubyContinuation
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006, 2007 Ola Bini <ola@ologix.com>
* Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
* Copyright (C) 2008 Vladimir Sizikov <vsizikov@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.security.Provider;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callback.Callback;
import org.jruby.util.ByteList;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
@JRubyModule(name="Digest")
public class RubyDigest {
private static Provider provider = null;
public static void createDigest(Ruby runtime) {
try {
provider = (Provider) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider").newInstance();
} catch(Exception e) {
// provider is not available
}
RubyModule mDigest = runtime.defineModule("Digest");
RubyClass cDigestBase = mDigest.defineClassUnder("Base",runtime.getObject(), Base.BASE_ALLOCATOR);
cDigestBase.defineAnnotatedMethods(Base.class);
}
private static MessageDigest createMessageDigest(Ruby runtime, String providerName) throws NoSuchAlgorithmException {
if(provider != null) {
try {
return MessageDigest.getInstance(providerName, provider);
} catch(NoSuchAlgorithmException e) {
// bouncy castle doesn't support algorithm
}
}
// fall back to system JCA providers
return MessageDigest.getInstance(providerName);
}
@JRubyClass(name="Digest::MD5", parent="Digest::Base")
public static class MD5 {}
@JRubyClass(name="Digest::RMD160", parent="Digest::Base")
public static class RMD160 {}
@JRubyClass(name="Digest::SHA1", parent="Digest::Base")
public static class SHA1 {}
@JRubyClass(name="Digest::SHA256", parent="Digest::Base")
public static class SHA256 {}
@JRubyClass(name="Digest::SHA384", parent="Digest::Base")
public static class SHA384 {}
@JRubyClass(name="Digest::SHA512", parent="Digest::Base")
public static class SHA512 {}
public static void createDigestMD5(Ruby runtime) {
runtime.getLoadService().require("digest.so");
RubyModule mDigest = runtime.fastGetModule("Digest");
RubyClass cDigestBase = mDigest.fastGetClass("Base");
RubyClass cDigest_MD5 = mDigest.defineClassUnder("MD5",cDigestBase,cDigestBase.getAllocator());
cDigest_MD5.defineFastMethod("block_length", new Callback() {
public Arity getArity() {
return Arity.NO_ARGUMENTS;
}
public IRubyObject execute(IRubyObject recv, IRubyObject[] args, Block block) {
return RubyFixnum.newFixnum(recv.getRuntime(), 64);
}
});
cDigest_MD5.setInternalModuleVariable("metadata",runtime.newString("MD5"));
}
public static void createDigestRMD160(Ruby runtime) {
runtime.getLoadService().require("digest.so");
if(provider == null) {
throw runtime.newLoadError("RMD160 not supported without BouncyCastle");
}
RubyModule mDigest = runtime.fastGetModule("Digest");
RubyClass cDigestBase = mDigest.fastGetClass("Base");
RubyClass cDigest_RMD160 = mDigest.defineClassUnder("RMD160",cDigestBase,cDigestBase.getAllocator());
cDigest_RMD160.setInternalModuleVariable("metadata",runtime.newString("RIPEMD160"));
}
public static void createDigestSHA1(Ruby runtime) {
runtime.getLoadService().require("digest.so");
RubyModule mDigest = runtime.fastGetModule("Digest");
RubyClass cDigestBase = mDigest.fastGetClass("Base");
RubyClass cDigest_SHA1 = mDigest.defineClassUnder("SHA1",cDigestBase,cDigestBase.getAllocator());
cDigest_SHA1.setInternalModuleVariable("metadata",runtime.newString("SHA1"));
}
public static void createDigestSHA2(Ruby runtime) {
runtime.getLoadService().require("digest.so");
try {
createMessageDigest(runtime, "SHA-256");
} catch(NoSuchAlgorithmException e) {
throw runtime.newLoadError("SHA2 not supported");
}
RubyModule mDigest = runtime.fastGetModule("Digest");
RubyClass cDigestBase = mDigest.fastGetClass("Base");
RubyClass cDigest_SHA2_256 = mDigest.defineClassUnder("SHA256",cDigestBase,cDigestBase.getAllocator());
cDigest_SHA2_256.setInternalModuleVariable("metadata",runtime.newString("SHA-256"));
RubyClass cDigest_SHA2_384 = mDigest.defineClassUnder("SHA384",cDigestBase,cDigestBase.getAllocator());
cDigest_SHA2_384.setInternalModuleVariable("metadata",runtime.newString("SHA-384"));
RubyClass cDigest_SHA2_512 = mDigest.defineClassUnder("SHA512",cDigestBase,cDigestBase.getAllocator());
cDigest_SHA2_512.setInternalModuleVariable("metadata",runtime.newString("SHA-512"));
}
@JRubyClass(name="Digest::Base")
public static class Base extends RubyObject {
protected static final ObjectAllocator BASE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new Base(runtime, klass);
}
};
@JRubyMethod(name = "digest", required = 1, meta = true)
public static IRubyObject s_digest(IRubyObject recv, IRubyObject str) {
Ruby runtime = recv.getRuntime();
String name = ((RubyClass)recv).searchInternalModuleVariable("metadata").toString();
try {
MessageDigest md = createMessageDigest(runtime, name);
return RubyString.newString(runtime, md.digest(str.convertToString().getBytes()));
} catch(NoSuchAlgorithmException e) {
throw recv.getRuntime().newNotImplementedError("Unsupported digest algorithm (" + name + ")");
}
}
@JRubyMethod(name = "hexdigest", required = 1, meta = true)
public static IRubyObject s_hexdigest(IRubyObject recv, IRubyObject str) {
Ruby runtime = recv.getRuntime();
String name = ((RubyClass)recv).searchInternalModuleVariable("metadata").toString();
try {
MessageDigest md = createMessageDigest(runtime, name);
return RubyString.newString(runtime, ByteList.plain(toHex(md.digest(str.convertToString().getBytes()))));
} catch(NoSuchAlgorithmException e) {
throw recv.getRuntime().newNotImplementedError("Unsupported digest algorithm (" + name + ")");
}
}
private MessageDigest algo;
private StringBuffer data;
public Base(Ruby runtime, RubyClass type) {
super(runtime,type);
data = new StringBuffer();
if(type == runtime.fastGetModule("Digest").fastGetClass("Base")) {
throw runtime.newNotImplementedError("Digest::Base is an abstract class");
}
if(!type.hasInternalModuleVariable("metadata")) {
throw runtime.newNotImplementedError("the " + type + "() function is unimplemented on this machine");
}
try {
setAlgorithm(type.searchInternalModuleVariable("metadata"));
} catch(NoSuchAlgorithmException e) {
throw runtime.newNotImplementedError("the " + type + "() function is unimplemented on this machine");
}
}
@JRubyMethod(name = "initialize", optional = 1, frame = true)
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
if(args.length > 0 && !args[0].isNil()) {
update(args[0]);
}
return this;
}
@JRubyMethod(name = "initialize_copy", required = 1)
public IRubyObject initialize_copy(IRubyObject obj) {
if(this == obj) {
return this;
}
((RubyObject)obj).checkFrozen();
data = new StringBuffer(((Base)obj).data.toString());
String name = ((Base)obj).algo.getAlgorithm();
try {
algo = createMessageDigest(getRuntime(), name);
} catch(NoSuchAlgorithmException e) {
throw getRuntime().newNotImplementedError("Unsupported digest algorithm (" + name + ")");
}
return this;
}
@JRubyMethod(name = {"update", "<<"}, required = 1)
public IRubyObject update(IRubyObject obj) {
data.append(obj);
return this;
}
@JRubyMethod(name = "digest", optional = 1)
public IRubyObject digest(IRubyObject[] args) {
if (args.length == 1) {
reset();
data.append(args[0]);
}
IRubyObject digest = getDigest();
if (args.length == 1) {
reset();
}
return digest;
}
private IRubyObject getDigest() {
algo.reset();
return RubyString.newString(getRuntime(), algo.digest(ByteList.plain(data)));
}
@JRubyMethod(name = "digest!")
public IRubyObject digest_bang() {
algo.reset();
byte[] digest = algo.digest(ByteList.plain(data));
reset();
return RubyString.newString(getRuntime(), digest);
}
@JRubyMethod(name = {"hexdigest"}, optional = 1)
public IRubyObject hexdigest(IRubyObject[] args) {
algo.reset();
if (args.length == 1) {
reset();
data.append(args[0]);
}
byte[] digest = ByteList.plain(toHex(algo.digest(ByteList.plain(data))));
if (args.length == 1) {
reset();
}
return RubyString.newString(getRuntime(), digest);
}
@JRubyMethod(name = {"to_s"})
public IRubyObject to_s() {
algo.reset();
return RubyString.newString(getRuntime(), ByteList.plain(toHex(algo.digest(ByteList.plain(data)))));
}
@JRubyMethod(name = {"hexdigest!"})
public IRubyObject hexdigest_bang() {
algo.reset();
byte[] digest = ByteList.plain(toHex(algo.digest(ByteList.plain(data))));
reset();
return RubyString.newString(getRuntime(), digest);
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
algo.reset();
return RubyString.newString(getRuntime(), ByteList.plain("#<" + getMetaClass().getRealClass().getName() + ": " + toHex(algo.digest(ByteList.plain(data))) + ">"));
}
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(IRubyObject oth) {
boolean ret = this == oth;
if(!ret) {
if (oth instanceof Base) {
Base b = (Base)oth;
ret = this.algo.getAlgorithm().equals(b.algo.getAlgorithm()) &&
this.getDigest().equals(b.getDigest());
} else {
IRubyObject str = oth.convertToString();
ret = this.to_s().equals(str);
}
}
return ret ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = {"length", "size", "digest_length"})
public IRubyObject length() {
return RubyFixnum.newFixnum(getRuntime(), algo.getDigestLength());
}
@JRubyMethod(name = {"block_length"})
public IRubyObject block_length() {
throw getRuntime().newRuntimeError(
this.getMetaClass() + " doesn't implement block_length()");
}
@JRubyMethod(name = {"reset"})
public IRubyObject reset() {
algo.reset();
data = new StringBuffer();
return getRuntime().getNil();
}
private void setAlgorithm(IRubyObject algo) throws NoSuchAlgorithmException {
this.algo = createMessageDigest(getRuntime(), algo.toString());
}
private static String toHex(byte[] val) {
StringBuilder out = new StringBuilder();
for(int i=0,j=val.length;i<j;i++) {
String ve = Integer.toString((((int)((char)val[i])) & 0xFF),16);
if(ve.length() == 1) {
ve = "0" + ve;
}
out.append(ve);
}
return out.toString();
}
}
}// RubyDigest
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.ext.posix.util.Platform;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.Dir;
import org.jruby.util.JRubyFile;
import org.jruby.util.ByteList;
/**
* .The Ruby built-in class Dir.
*
* @author jvoegele
*/
@JRubyClass(name="Dir", include="Enumerable")
public class RubyDir extends RubyObject {
// What we passed to the constructor for method 'path'
private RubyString path;
protected JRubyFile dir;
private String[] snapshot; // snapshot of contents of directory
private int pos; // current position in directory
private boolean isOpen = true;
public RubyDir(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private static final ObjectAllocator DIR_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyDir(runtime, klass);
}
};
public static RubyClass createDirClass(Ruby runtime) {
RubyClass dirClass = runtime.defineClass("Dir", runtime.getObject(), DIR_ALLOCATOR);
runtime.setDir(dirClass);
dirClass.includeModule(runtime.getEnumerable());
dirClass.defineAnnotatedMethods(RubyDir.class);
return dirClass;
}
private final void checkDir() {
if (!isTaint() && getRuntime().getSafeLevel() >= 4) throw getRuntime().newSecurityError("Insecure: operation on untainted Dir");
testFrozen("");
if (!isOpen) throw getRuntime().newIOError("closed directory");
}
/**
* Creates a new <code>Dir</code>. This method takes a snapshot of the
* contents of the directory at creation time, so changes to the contents
* of the directory will not be reflected during the lifetime of the
* <code>Dir</code> object returned, so a new <code>Dir</code> instance
* must be created to reflect changes to the underlying file system.
*/
@JRubyMethod(name = "initialize", required = 1, frame = true)
public IRubyObject initialize(IRubyObject _newPath, Block unusedBlock) {
RubyString newPath = _newPath.convertToString();
getRuntime().checkSafeString(newPath);
String adjustedPath = RubyFile.adjustRootPathOnWindows(getRuntime(), newPath.toString(), null);
checkDirIsTwoSlashesOnWindows(getRuntime(), adjustedPath);
dir = JRubyFile.create(getRuntime().getCurrentDirectory(), adjustedPath);
if (!dir.isDirectory()) {
dir = null;
throw getRuntime().newErrnoENOENTError(newPath.toString() + " is not a directory");
}
path = newPath;
List<String> snapshotList = new ArrayList<String>();
snapshotList.add(".");
snapshotList.add("..");
snapshotList.addAll(getContents(dir));
snapshot = (String[]) snapshotList.toArray(new String[snapshotList.size()]);
pos = 0;
return this;
}
// ----- Ruby Class Methods ----------------------------------------------------
private static List<ByteList> dirGlobs(String cwd, IRubyObject[] args, int flags) {
List<ByteList> dirs = new ArrayList<ByteList>();
for (int i = 0; i < args.length; i++) {
ByteList globPattern = args[i].convertToString().getByteList();
dirs.addAll(Dir.push_glob(cwd, globPattern, flags));
}
return dirs;
}
private static IRubyObject asRubyStringList(Ruby runtime, List<ByteList> dirs) {
List<RubyString> allFiles = new ArrayList<RubyString>();
for (ByteList dir: dirs) {
allFiles.add(RubyString.newString(runtime, dir));
}
IRubyObject[] tempFileList = new IRubyObject[allFiles.size()];
allFiles.toArray(tempFileList);
return runtime.newArrayNoCopy(tempFileList);
}
private static String getCWD(Ruby runtime) {
try {
return new org.jruby.util.NormalizedFile(runtime.getCurrentDirectory()).getCanonicalPath();
} catch(Exception e) {
return runtime.getCurrentDirectory();
}
}
@JRubyMethod(name = "[]", required = 1, rest=true, meta = true)
public static IRubyObject aref(IRubyObject recv, IRubyObject[] args) {
List<ByteList> dirs;
if (args.length == 1) {
ByteList globPattern = args[0].convertToString().getByteList();
dirs = Dir.push_glob(getCWD(recv.getRuntime()), globPattern, 0);
} else {
dirs = dirGlobs(getCWD(recv.getRuntime()), args, 0);
}
return asRubyStringList(recv.getRuntime(), dirs);
}
/**
* Returns an array of filenames matching the specified wildcard pattern
* <code>pat</code>. If a block is given, the array is iterated internally
* with each filename is passed to the block in turn. In this case, Nil is
* returned.
*/
@JRubyMethod(name = "glob", required = 1, optional = 1, frame = true, meta = true)
public static IRubyObject glob(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = recv.getRuntime();
int flags = args.length == 2 ? RubyNumeric.num2int(args[1]) : 0;
List<ByteList> dirs;
IRubyObject tmp = args[0].checkArrayType();
if (tmp.isNil()) {
ByteList globPattern = args[0].convertToString().getByteList();
dirs = Dir.push_glob(recv.getRuntime().getCurrentDirectory(), globPattern, flags);
} else {
dirs = dirGlobs(getCWD(runtime), ((RubyArray) tmp).toJavaArray(), flags);
}
if (block.isGiven()) {
for (int i = 0; i < dirs.size(); i++) {
block.yield(context, RubyString.newString(runtime, dirs.get(i)));
}
return recv.getRuntime().getNil();
}
return asRubyStringList(recv.getRuntime(), dirs);
}
/**
* @return all entries for this Dir
*/
@JRubyMethod(name = "entries")
public RubyArray entries() {
return getRuntime().newArrayNoCopy(JavaUtil.convertJavaArrayToRuby(getRuntime(), snapshot));
}
/**
* Returns an array containing all of the filenames in the given directory.
*/
@JRubyMethod(name = "entries", required = 1, meta = true)
public static RubyArray entries(IRubyObject recv, IRubyObject path) {
Ruby runtime = recv.getRuntime();
String adjustedPath = RubyFile.adjustRootPathOnWindows(
runtime, path.convertToString().toString(), null);
checkDirIsTwoSlashesOnWindows(runtime, adjustedPath);
final JRubyFile directory = JRubyFile.create(
recv.getRuntime().getCurrentDirectory(), adjustedPath);
if (!directory.isDirectory()) {
throw recv.getRuntime().newErrnoENOENTError("No such directory");
}
List<String> fileList = getContents(directory);
fileList.add(0, ".");
fileList.add(1, "..");
Object[] files = fileList.toArray();
return recv.getRuntime().newArrayNoCopy(JavaUtil.convertJavaArrayToRuby(recv.getRuntime(), files));
}
// MRI behavior: just plain '//' or '\\\\' are considered illegal on Windows.
private static void checkDirIsTwoSlashesOnWindows(Ruby runtime, String path) {
if (Platform.IS_WINDOWS && ("//".equals(path) || "\\\\".equals(path))) {
throw runtime.newErrnoEINVALError("Invalid argument - " + path);
}
}
/** Changes the current directory to <code>path</code> */
@JRubyMethod(name = "chdir", optional = 1, frame = true, meta = true)
public static IRubyObject chdir(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyString path = args.length == 1 ?
(RubyString) args[0].convertToString() : getHomeDirectoryPath(context);
String adjustedPath = RubyFile.adjustRootPathOnWindows(
recv.getRuntime(), path.toString(), null);
checkDirIsTwoSlashesOnWindows(recv.getRuntime(), adjustedPath);
JRubyFile dir = getDir(recv.getRuntime(), adjustedPath, true);
String realPath = null;
String oldCwd = recv.getRuntime().getCurrentDirectory();
// We get canonical path to try and flatten the path out.
// a dir '/subdir/..' should return as '/'
// cnutter: Do we want to flatten path out?
try {
realPath = dir.getCanonicalPath();
} catch (IOException e) {
realPath = dir.getAbsolutePath();
}
IRubyObject result = null;
if (block.isGiven()) {
// FIXME: Don't allow multiple threads to do this at once
recv.getRuntime().setCurrentDirectory(realPath);
try {
result = block.yield(context, path);
} finally {
dir = getDir(recv.getRuntime(), oldCwd, true);
recv.getRuntime().setCurrentDirectory(oldCwd);
}
} else {
recv.getRuntime().setCurrentDirectory(realPath);
result = recv.getRuntime().newFixnum(0);
}
return result;
}
/**
* Changes the root directory (only allowed by super user). Not available
* on all platforms.
*/
@JRubyMethod(name = "chroot", required = 1, meta = true)
public static IRubyObject chroot(IRubyObject recv, IRubyObject path) {
throw recv.getRuntime().newNotImplementedError("chroot not implemented: chroot is non-portable and is not supported.");
}
/**
* Deletes the directory specified by <code>path</code>. The directory must
* be empty.
*/
@JRubyMethod(name = {"rmdir", "unlink", "delete"}, required = 1, meta = true)
public static IRubyObject rmdir(IRubyObject recv, IRubyObject path) {
JRubyFile directory = getDir(recv.getRuntime(), path.convertToString().toString(), true);
if (!directory.delete()) {
throw recv.getRuntime().newSystemCallError("No such directory");
}
return recv.getRuntime().newFixnum(0);
}
/**
* Executes the block once for each file in the directory specified by
* <code>path</code>.
*/
@JRubyMethod(name = "foreach", required = 1, frame = true, meta = true)
public static IRubyObject foreach(ThreadContext context, IRubyObject recv, IRubyObject _path, Block block) {
RubyString path = _path.convertToString();
recv.getRuntime().checkSafeString(path);
RubyClass dirClass = recv.getRuntime().getDir();
RubyDir dir = (RubyDir) dirClass.newInstance(context, new IRubyObject[] { path }, block);
dir.each(context, block);
return recv.getRuntime().getNil();
}
/** Returns the current directory. */
@JRubyMethod(name = {"getwd", "pwd"}, meta = true)
public static RubyString getwd(IRubyObject recv) {
Ruby ruby = recv.getRuntime();
return RubyString.newUnicodeString(ruby, ruby.getCurrentDirectory());
}
/**
* Creates the directory specified by <code>path</code>. Note that the
* <code>mode</code> parameter is provided only to support existing Ruby
* code, and is ignored.
*/
@JRubyMethod(name = "mkdir", required = 1, optional = 1, meta = true)
public static IRubyObject mkdir(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
runtime.checkSafeString(args[0]);
String path = args[0].toString();
File newDir = getDir(runtime, path, false);
if (File.separatorChar == '\\') {
newDir = new File(newDir.getPath());
}
int mode = args.length == 2 ? ((int) args[1].convertToInteger().getLongValue()) : 0777;
if (runtime.getPosix().mkdir(newDir.getAbsolutePath(), mode) < 0) {
// FIXME: This is a system error based on errno
throw recv.getRuntime().newSystemCallError("mkdir failed");
}
return RubyFixnum.zero(recv.getRuntime());
}
/**
* Returns a new directory object for <code>path</code>. If a block is
* provided, a new directory object is passed to the block, which closes the
* directory object before terminating.
*/
@JRubyMethod(name = "open", required = 1, frame = true, meta = true)
public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject path, Block block) {
RubyDir directory =
(RubyDir) recv.getRuntime().getDir().newInstance(context,
new IRubyObject[] { path }, Block.NULL_BLOCK);
if (!block.isGiven()) return directory;
try {
return block.yield(context, directory);
} finally {
directory.close();
}
}
// ----- Ruby Instance Methods -------------------------------------------------
/**
* Closes the directory stream.
*/
@JRubyMethod(name = "close")
public IRubyObject close() {
// Make sure any read()s after close fail.
checkDir();
isOpen = false;
return getRuntime().getNil();
}
/**
* Executes the block once for each entry in the directory.
*/
@JRubyMethod(name = "each", frame = true)
public IRubyObject each(ThreadContext context, Block block) {
checkDir();
String[] contents = snapshot;
for (int i=0; i<contents.length; i++) {
block.yield(context, getRuntime().newString(contents[i]));
}
return this;
}
/**
* Returns the current position in the directory.
*/
@JRubyMethod(name = {"tell", "pos"})
public RubyInteger tell() {
checkDir();
return getRuntime().newFixnum(pos);
}
/**
* Moves to a position <code>d</code>. <code>pos</code> must be a value
* returned by <code>tell</code> or 0.
*/
@JRubyMethod(name = "seek", required = 1)
public IRubyObject seek(IRubyObject newPos) {
checkDir();
set_pos(newPos);
return this;
}
@JRubyMethod(name = "pos=", required = 1)
public IRubyObject set_pos(IRubyObject newPos) {
this.pos = RubyNumeric.fix2int(newPos);
return newPos;
}
@JRubyMethod(name = "path")
public IRubyObject path(ThreadContext context) {
checkDir();
return path.strDup(context.getRuntime());
}
/** Returns the next entry from this directory. */
@JRubyMethod(name = "read")
public IRubyObject read() {
checkDir();
if (pos >= snapshot.length) {
return getRuntime().getNil();
}
RubyString result = getRuntime().newString(snapshot[pos]);
pos++;
return result;
}
/** Moves position in this directory to the first entry. */
@JRubyMethod(name = "rewind")
public IRubyObject rewind() {
if (!isTaint() && getRuntime().getSafeLevel() >= 4) throw getRuntime().newSecurityError("Insecure: can't close");
checkDir();
pos = 0;
return this;
}
// ----- Helper Methods --------------------------------------------------------
/** Returns a Java <code>File</code> object for the specified path. If
* <code>path</code> is not a directory, throws <code>IOError</code>.
*
* @param path path for which to return the <code>File</code> object.
* @param mustExist is true the directory must exist. If false it must not.
* @throws IOError if <code>path</code> is not a directory.
*/
protected static JRubyFile getDir(final Ruby runtime, final String path, final boolean mustExist) {
JRubyFile result = JRubyFile.create(runtime.getCurrentDirectory(),path);
if (mustExist && !result.exists()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + path);
}
boolean isDirectory = result.isDirectory();
if (mustExist && !isDirectory) {
throw runtime.newErrnoENOTDIRError(path + " is not a directory");
} else if (!mustExist && isDirectory) {
throw runtime.newErrnoEEXISTError("File exists - " + path);
}
return result;
}
/**
* Returns the contents of the specified <code>directory</code> as an
* <code>ArrayList</code> containing the names of the files as Java Strings.
*/
protected static List<String> getContents(File directory) {
String[] contents = directory.list();
List<String> result = new ArrayList<String>();
// If an IO exception occurs (something odd, but possible)
// A directory may return null.
if (contents != null) {
for (int i=0; i<contents.length; i++) {
result.add(contents[i]);
}
}
return result;
}
/**
* Returns the contents of the specified <code>directory</code> as an
* <code>ArrayList</code> containing the names of the files as Ruby Strings.
*/
protected static List<RubyString> getContents(File directory, Ruby runtime) {
List<RubyString> result = new ArrayList<RubyString>();
String[] contents = directory.list();
for (int i = 0; i < contents.length; i++) {
result.add(runtime.newString(contents[i]));
}
return result;
}
/**
* Returns the home directory of the specified <code>user</code> on the
* system. If the home directory of the specified user cannot be found,
* an <code>ArgumentError it thrown</code>.
*/
public static IRubyObject getHomeDirectoryPath(ThreadContext context, String user) {
/*
* TODO: This version is better than the hackish previous one. Windows
* behavior needs to be defined though. I suppose this version
* could be improved more too.
* TODO: /etc/passwd is also inadequate for MacOSX since it does not
* use /etc/passwd for regular user accounts
*/
String passwd = null;
try {
FileInputStream stream = new FileInputStream("/etc/passwd");
int totalBytes = stream.available();
byte[] bytes = new byte[totalBytes];
stream.read(bytes);
stream.close();
passwd = new String(bytes);
} catch (IOException e) {
return context.getRuntime().getNil();
}
String[] rows = passwd.split("\n");
int rowCount = rows.length;
for (int i = 0; i < rowCount; i++) {
String[] fields = rows[i].split(":");
if (fields[0].equals(user)) {
return context.getRuntime().newString(fields[5]);
}
}
throw context.getRuntime().newArgumentError("user " + user + " doesn't exist");
}
public static RubyString getHomeDirectoryPath(ThreadContext context) {
Ruby runtime = context.getRuntime();
RubyHash systemHash = (RubyHash) runtime.getObject().fastGetConstant("ENV_JAVA");
RubyHash envHash = (RubyHash) runtime.getObject().fastGetConstant("ENV");
IRubyObject home = envHash.op_aref(context, runtime.newString("HOME"));
if (home == null || home.isNil()) {
home = systemHash.op_aref(context, runtime.newString("user.home"));
}
if (home == null || home.isNil()) {
home = envHash.op_aref(context, runtime.newString("LOGDIR"));
}
if (home == null || home.isNil()) {
throw runtime.newArgumentError("user.home/LOGDIR not set");
}
return (RubyString) home;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.Comparator;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.exceptions.JumpException;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallBlock;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.TypeConverter;
/**
* The implementation of Ruby's Enumerable module.
*/
@JRubyModule(name="Enumerable")
public class RubyEnumerable {
public static RubyModule createEnumerableModule(Ruby runtime) {
RubyModule enumModule = runtime.defineModule("Enumerable");
runtime.setEnumerable(enumModule);
enumModule.defineAnnotatedMethods(RubyEnumerable.class);
return enumModule;
}
public static IRubyObject callEach(Ruby runtime, ThreadContext context, IRubyObject self,
BlockCallback callback) {
return RuntimeHelpers.invoke(context, self, "each", CallBlock.newCallClosure(self, runtime.getEnumerable(),
Arity.noArguments(), callback, context));
}
private static class ExitIteration extends RuntimeException {
public Throwable fillInStackTrace() {
return this;
}
}
@JRubyMethod(name = "first")
public static IRubyObject first_0(ThreadContext context, IRubyObject self) {
Ruby runtime = self.getRuntime();
final ThreadContext localContext = context;
final IRubyObject[] holder = new IRubyObject[]{runtime.getNil()};
try {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw ctx.getRuntime().newThreadError("Enumerable#first cannot be parallelized");
}
holder[0] = largs[0];
throw new ExitIteration();
}
});
} catch(ExitIteration ei) {}
return holder[0];
}
@JRubyMethod(name = "first")
public static IRubyObject first_1(ThreadContext context, IRubyObject self, final IRubyObject num) {
final Ruby runtime = self.getRuntime();
final RubyArray result = runtime.newArray();
final ThreadContext localContext = context;
if(RubyNumeric.fix2int(num) < 0) {
throw runtime.newArgumentError("negative index");
}
try {
callEach(runtime, context, self, new BlockCallback() {
private int iter = RubyNumeric.fix2int(num);
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#first cannot be parallelized");
}
if(iter-- == 0) {
throw new ExitIteration();
}
result.append(largs[0]);
return runtime.getNil();
}
});
} catch(ExitIteration ei) {}
return result;
}
@JRubyMethod(name = {"to_a", "entries"})
public static IRubyObject to_a(ThreadContext context, IRubyObject self) {
Ruby runtime = self.getRuntime();
RubyArray result = runtime.newArray();
callEach(runtime, context, self, new AppendBlockCallback(runtime, result));
return result;
}
@JRubyMethod(name = "sort", frame = true)
public static IRubyObject sort(ThreadContext context, IRubyObject self, final Block block) {
Ruby runtime = self.getRuntime();
RubyArray result = runtime.newArray();
callEach(runtime, context, self, new AppendBlockCallback(runtime, result));
result.sort_bang(block);
return result;
}
@JRubyMethod(name = "sort_by", frame = true)
public static IRubyObject sort_by(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final ThreadContext localContext = context; // MUST NOT be used across threads
if (self instanceof RubyArray) {
RubyArray selfArray = (RubyArray) self;
final IRubyObject[][] valuesAndCriteria = new IRubyObject[selfArray.size()][2];
callEach(runtime, context, self, new BlockCallback() {
AtomicInteger i = new AtomicInteger(0);
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
IRubyObject[] myVandC = valuesAndCriteria[i.getAndIncrement()];
myVandC[0] = largs[0];
myVandC[1] = block.yield(ctx, largs[0]);
return runtime.getNil();
}
});
Arrays.sort(valuesAndCriteria, new Comparator<IRubyObject[]>() {
public int compare(IRubyObject[] o1, IRubyObject[] o2) {
return RubyFixnum.fix2int(o1[1].callMethod(localContext, MethodIndex.OP_SPACESHIP, "<=>", o2[1]));
}
});
IRubyObject dstArray[] = new IRubyObject[selfArray.size()];
for (int i = 0; i < dstArray.length; i++) {
dstArray[i] = valuesAndCriteria[i][0];
}
return runtime.newArrayNoCopy(dstArray);
} else {
final RubyArray result = runtime.newArray();
callEach(runtime, context, self, new AppendBlockCallback(runtime, result));
final IRubyObject[][] valuesAndCriteria = new IRubyObject[result.size()][2];
for (int i = 0; i < valuesAndCriteria.length; i++) {
IRubyObject val = result.eltInternal(i);
valuesAndCriteria[i][0] = val;
valuesAndCriteria[i][1] = block.yield(context, val);
}
Arrays.sort(valuesAndCriteria, new Comparator<IRubyObject[]>() {
public int compare(IRubyObject[] o1, IRubyObject[] o2) {
return RubyFixnum.fix2int(o1[1].callMethod(localContext, MethodIndex.OP_SPACESHIP, "<=>", o2[1]));
}
});
for (int i = 0; i < valuesAndCriteria.length; i++) {
result.eltInternalSet(i, valuesAndCriteria[i][0]);
}
return result;
}
}
@JRubyMethod(name = "grep", required = 1, frame = true)
public static IRubyObject grep(ThreadContext context, IRubyObject self, final IRubyObject pattern, final Block block) {
final Ruby runtime = self.getRuntime();
final RubyArray result = runtime.newArray();
if (block.isGiven()) {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
ctx.setRubyFrameDelta(ctx.getRubyFrameDelta()+2);
if (pattern.callMethod(ctx, MethodIndex.OP_EQQ, "===", largs[0]).isTrue()) {
IRubyObject value = block.yield(ctx, largs[0]);
synchronized (result) {
result.append(value);
}
}
ctx.setRubyFrameDelta(ctx.getRubyFrameDelta()-2);
return runtime.getNil();
}
});
} else {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (pattern.callMethod(ctx, MethodIndex.OP_EQQ, "===", largs[0]).isTrue()) {
synchronized (result) {
result.append(largs[0]);
}
}
return runtime.getNil();
}
});
}
return result;
}
@JRubyMethod(name = {"detect", "find"}, optional = 1, frame = true)
public static IRubyObject detect(ThreadContext context, IRubyObject self, IRubyObject[] args, final Block block) {
final Ruby runtime = self.getRuntime();
final IRubyObject result[] = new IRubyObject[] { null };
final ThreadContext localContext = context;
IRubyObject ifnone = null;
if (args.length == 1) ifnone = args[0];
try {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#detect/find cannot be parallelized");
}
if (block.yield(ctx, largs[0]).isTrue()) {
result[0] = largs[0];
throw JumpException.SPECIAL_JUMP;
}
return runtime.getNil();
}
});
} catch (JumpException.SpecialJump sj) {
return result[0];
}
return ifnone != null ? ifnone.callMethod(context, "call") : runtime.getNil();
}
@JRubyMethod(name = {"select", "find_all"}, frame = true)
public static IRubyObject select(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final RubyArray result = runtime.newArray();
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (block.yield(ctx, largs[0]).isTrue()) {
synchronized (result) {
result.append(largs[0]);
}
}
return runtime.getNil();
}
});
return result;
}
@JRubyMethod(name = "reject", frame = true)
public static IRubyObject reject(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final RubyArray result = runtime.newArray();
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (!block.yield(ctx, largs[0]).isTrue()) {
synchronized (result) {
result.append(largs[0]);
}
}
return runtime.getNil();
}
});
return result;
}
@JRubyMethod(name = {"collect", "map"}, frame = true)
public static IRubyObject collect(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final RubyArray result = runtime.newArray();
if (block.isGiven()) {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
IRubyObject value = block.yield(ctx, largs[0]);
synchronized (result) {
result.append(value);
}
return runtime.getNil();
}
});
} else {
callEach(runtime, context, self, new AppendBlockCallback(runtime, result));
}
return result;
}
@JRubyMethod(name = "inject", optional = 1, frame = true)
public static IRubyObject inject(ThreadContext context, IRubyObject self, IRubyObject[] args, final Block block) {
final Ruby runtime = self.getRuntime();
final IRubyObject result[] = new IRubyObject[] { null };
final ThreadContext localContext = context;
if (args.length == 1) result[0] = args[0];
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#inject cannot be parallelized");
}
result[0] = result[0] == null ?
largs[0] : block.yield(ctx, runtime.newArray(result[0], largs[0]), null, null, true);
return runtime.getNil();
}
});
return result[0] == null ? runtime.getNil() : result[0];
}
@JRubyMethod(name = "partition", frame = true)
public static IRubyObject partition(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final RubyArray arr_true = runtime.newArray();
final RubyArray arr_false = runtime.newArray();
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (block.yield(ctx, largs[0]).isTrue()) {
synchronized (arr_true) {
arr_true.append(largs[0]);
}
} else {
synchronized (arr_false) {
arr_false.append(largs[0]);
}
}
return runtime.getNil();
}
});
return runtime.newArray(arr_true, arr_false);
}
private static class EachWithIndex implements BlockCallback {
private int index = 0;
private final Block block;
private final Ruby runtime;
public EachWithIndex(ThreadContext ctx, Block block) {
this.block = block;
this.runtime = ctx.getRuntime();
}
public IRubyObject call(ThreadContext context, IRubyObject[] iargs, Block block) {
this.block.call(context, new IRubyObject[] { runtime.newArray(iargs[0], runtime.newFixnum(index++)) });
return runtime.getNil();
}
}
@JRubyMethod(name = "each_with_index", frame = true)
public static IRubyObject each_with_index(ThreadContext context, IRubyObject self, Block block) {
RuntimeHelpers.invoke(context, self, "each", CallBlock.newCallClosure(self, self.getRuntime().getEnumerable(),
Arity.noArguments(), new EachWithIndex(context, block), context));
return self;
}
@JRubyMethod(name = {"include?", "member?"}, required = 1, frame = true)
public static IRubyObject include_p(ThreadContext context, IRubyObject self, final IRubyObject arg) {
final Ruby runtime = context.getRuntime();
final ThreadContext localContext = context;
try {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#include?/member? cannot be parallelized");
}
if (RubyObject.equalInternal(ctx, largs[0], arg)) {
throw JumpException.SPECIAL_JUMP;
}
return runtime.getNil();
}
});
} catch (JumpException.SpecialJump sj) {
return runtime.getTrue();
}
return runtime.getFalse();
}
@JRubyMethod(name = "max", frame = true)
public static IRubyObject max(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final IRubyObject result[] = new IRubyObject[] { null };
final ThreadContext localContext = context;
if (block.isGiven()) {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#max{} cannot be parallelized");
}
if (result[0] == null || RubyComparable.cmpint(ctx, block.yield(ctx,
runtime.newArray(largs[0], result[0])), largs[0], result[0]) > 0) {
result[0] = largs[0];
}
return runtime.getNil();
}
});
} else {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
synchronized (result) {
if (result[0] == null || RubyComparable.cmpint(ctx, largs[0].callMethod(ctx,
MethodIndex.OP_SPACESHIP, "<=>", result[0]), largs[0], result[0]) > 0) {
result[0] = largs[0];
}
}
return runtime.getNil();
}
});
}
return result[0] == null ? runtime.getNil() : result[0];
}
@JRubyMethod(name = "min", frame = true)
public static IRubyObject min(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final IRubyObject result[] = new IRubyObject[] { null };
final ThreadContext localContext = context;
if (block.isGiven()) {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#min{} cannot be parallelized");
}
if (result[0] == null || RubyComparable.cmpint(ctx, block.yield(ctx,
runtime.newArray(largs[0], result[0])), largs[0], result[0]) < 0) {
result[0] = largs[0];
}
return runtime.getNil();
}
});
} else {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
synchronized (result) {
if (result[0] == null || RubyComparable.cmpint(ctx, largs[0].callMethod(ctx,
MethodIndex.OP_SPACESHIP, "<=>", result[0]), largs[0], result[0]) < 0) {
result[0] = largs[0];
}
}
return runtime.getNil();
}
});
}
return result[0] == null ? runtime.getNil() : result[0];
}
@JRubyMethod(name = "all?", frame = true)
public static IRubyObject all_p(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final ThreadContext localContext = context;
try {
if (block.isGiven()) {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#all? cannot be parallelized");
}
if (!block.yield(ctx, largs[0]).isTrue()) {
throw JumpException.SPECIAL_JUMP;
}
return runtime.getNil();
}
});
} else {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#all? cannot be parallelized");
}
if (!largs[0].isTrue()) {
throw JumpException.SPECIAL_JUMP;
}
return runtime.getNil();
}
});
}
} catch (JumpException.SpecialJump sj) {
return runtime.getFalse();
}
return runtime.getTrue();
}
@JRubyMethod(name = "any?", frame = true)
public static IRubyObject any_p(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final ThreadContext localContext = context;
try {
if (block.isGiven()) {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#any? cannot be parallelized");
}
if (block.yield(ctx, largs[0]).isTrue()) {
throw JumpException.SPECIAL_JUMP;
}
return runtime.getNil();
}
});
} else {
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (localContext != ctx) {
throw runtime.newThreadError("Enumerable#any? cannot be parallelized");
}
if (largs[0].isTrue()) {
throw JumpException.SPECIAL_JUMP;
}
return runtime.getNil();
}
});
}
} catch (JumpException.SpecialJump sj) {
return runtime.getTrue();
}
return runtime.getFalse();
}
@JRubyMethod(name = "zip", rest = true, frame = true)
public static IRubyObject zip(ThreadContext context, IRubyObject self, final IRubyObject[] args, final Block block) {
final Ruby runtime = self.getRuntime();
for (int i = 0; i < args.length; i++) {
args[i] = TypeConverter.convertToType(args[i], runtime.getArray(), MethodIndex.TO_A, "to_a");
}
final int aLen = args.length + 1;
if (block.isGiven()) {
callEach(runtime, context, self, new BlockCallback() {
AtomicInteger ix = new AtomicInteger(0);
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
RubyArray array = runtime.newArray(aLen);
int myIx = ix.getAndIncrement();
array.append(largs[0]);
for (int i = 0, j = args.length; i < j; i++) {
array.append(((RubyArray) args[i]).entry(myIx));
}
block.yield(ctx, array);
return runtime.getNil();
}
});
return runtime.getNil();
} else {
final RubyArray zip = runtime.newArray();
callEach(runtime, context, self, new BlockCallback() {
AtomicInteger ix = new AtomicInteger(0);
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
RubyArray array = runtime.newArray(aLen);
array.append(largs[0]);
int myIx = ix.getAndIncrement();
for (int i = 0, j = args.length; i < j; i++) {
array.append(((RubyArray) args[i]).entry(myIx));
}
synchronized (zip) {
zip.append(array);
}
return runtime.getNil();
}
});
return zip;
}
}
@JRubyMethod(name = "group_by", frame = true)
public static IRubyObject group_by(ThreadContext context, IRubyObject self, final Block block) {
final Ruby runtime = self.getRuntime();
final RubyHash result = new RubyHash(runtime);
callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
IRubyObject key = block.yield(ctx, largs[0]);
synchronized (result) {
IRubyObject curr = result.fastARef(key);
if (curr == null) {
curr = runtime.newArray();
result.fastASet(key, curr);
}
curr.callMethod(ctx, MethodIndex.OP_LSHIFT, "<<", largs[0]);
}
return runtime.getNil();
}
});
return result;
}
public static final class AppendBlockCallback implements BlockCallback {
private Ruby runtime;
private RubyArray result;
public AppendBlockCallback(Ruby runtime, RubyArray result) {
this.runtime = runtime;
this.result = result;
}
public IRubyObject call(ThreadContext context, IRubyObject[] largs, Block blk) {
result.append(largs[0]);
return runtime.getNil();
}
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Michael Studman <me@michaelstudman.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
/**
* Implementation of Ruby's Enumerator module.
*/
@JRubyModule(name="Enumerable::Enumerator", include="Enumerable")
public class RubyEnumerator extends RubyObject {
/** target for each operation */
private IRubyObject object;
/** method to invoke for each operation */
private IRubyObject method;
/** args to each method */
private IRubyObject[] methodArgs;
private static ObjectAllocator ENUMERATOR_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyEnumerator(runtime, klass);
}
};
public static void defineEnumerator(Ruby runtime) {
RubyModule kernel = runtime.getKernel();
kernel.defineAnnotatedMethod(RubyEnumerator.class, "obj_to_enum");
RubyModule enm = runtime.getClassFromPath("Enumerable");
enm.defineAnnotatedMethod(RubyEnumerator.class, "each_with_index");
enm.defineAnnotatedMethod(RubyEnumerator.class, "each_slice");
enm.defineAnnotatedMethod(RubyEnumerator.class, "enum_slice");
enm.defineAnnotatedMethod(RubyEnumerator.class, "each_cons");
enm.defineAnnotatedMethod(RubyEnumerator.class, "enum_cons");
RubyClass enmr = enm.defineClassUnder("Enumerator", runtime.getObject(), ENUMERATOR_ALLOCATOR);
enmr.includeModule(enm);
enmr.defineAnnotatedMethod(RubyEnumerator.class, "initialize");
enmr.defineAnnotatedMethod(RubyEnumerator.class, "each");
runtime.setEnumerator(enmr);
}
@JRubyMethod(name = {"to_enum", "enum_for"}, optional = 1, rest = true, frame = true)
public static IRubyObject obj_to_enum(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) {
IRubyObject[] newArgs = new IRubyObject[args.length + 1];
newArgs[0] = self;
System.arraycopy(args, 0, newArgs, 1, args.length);
return self.getRuntime().getEnumerator().callMethod(context, "new", newArgs);
}
private RubyEnumerator(Ruby runtime, RubyClass type) {
super(runtime, type);
object = method = runtime.getNil();
}
@JRubyMethod(name = "initialize", required = 1, rest = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args) {
object = args[0];
method = args.length > 1 ? args[1] : getRuntime().fastNewSymbol("each");
if (args.length > 2) {
methodArgs = new IRubyObject[Math.max(0, args.length - 2)];
System.arraycopy(args, 2, methodArgs, 0, args.length - 2);
} else {
methodArgs = new IRubyObject[0];
}
return this;
}
/**
* Send current block and supplied args to method on target. According to MRI
* Block may not be given and "each" should just ignore it and call on through to
* underlying method.
*/
@JRubyMethod(name = "each", frame = true)
public IRubyObject each(ThreadContext context, Block block) {
return object.callMethod(context, method.asJavaString(), methodArgs, block);
}
@JRubyMethod(name = "enum_with_index")
public static IRubyObject each_with_index(ThreadContext context, IRubyObject self) {
IRubyObject enumerator = self.getRuntime().getEnumerator();
return RuntimeHelpers.invoke(context, enumerator, "new", self, self.getRuntime().fastNewSymbol("each_with_index"));
}
@JRubyMethod(name = "each_slice", required = 1, frame = true)
public static IRubyObject each_slice(ThreadContext context, IRubyObject self, IRubyObject arg, final Block block) {
final int size = (int)RubyNumeric.num2long(arg);
if (size <= 0) throw self.getRuntime().newArgumentError("invalid slice size");
final Ruby runtime = self.getRuntime();
final RubyArray result[] = new RubyArray[]{runtime.newArray(size)};
RubyEnumerable.callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
result[0].append(largs[0]);
if (result[0].size() == size) {
block.yield(ctx, result[0]);
result[0] = runtime.newArray(size);
}
return runtime.getNil();
}
});
if (result[0].size() > 0) block.yield(context, result[0]);
return self.getRuntime().getNil();
}
@JRubyMethod(name = "each_cons", required = 1, frame = true)
public static IRubyObject each_cons(ThreadContext context, IRubyObject self, IRubyObject arg, final Block block) {
final int size = (int)RubyNumeric.num2long(arg);
if (size <= 0) throw self.getRuntime().newArgumentError("invalid size");
final Ruby runtime = self.getRuntime();
final RubyArray result = runtime.newArray(size);
RubyEnumerable.callEach(runtime, context, self, new BlockCallback() {
public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
if (result.size() == size) result.shift();
result.append(largs[0]);
if (result.size() == size) block.yield(ctx, result.aryDup());
return runtime.getNil();
}
});
return runtime.getNil();
}
@JRubyMethod(name = "enum_slice", required = 1)
public static IRubyObject enum_slice(ThreadContext context, IRubyObject self, IRubyObject arg) {
IRubyObject enumerator = self.getRuntime().getEnumerator();
return RuntimeHelpers.invoke(context, enumerator, "new", self, self.getRuntime().fastNewSymbol("each_slice"), arg);
}
@JRubyMethod(name = "enum_cons", required = 1)
public static IRubyObject enum_cons(ThreadContext context, IRubyObject self, IRubyObject arg) {
IRubyObject enumerator = self.getRuntime().getEnumerator();
return RuntimeHelpers.invoke(context, enumerator, "new", self, self.getRuntime().fastNewSymbol("each_cons"), arg);
}
}
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.ext.posix.Passwd;
import org.jruby.ext.posix.Group;
import org.jruby.ext.posix.POSIX;
import org.jruby.ext.posix.util.Platform;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyModule(name="Etc")
public class RubyEtc {
public static RubyModule createEtcModule(Ruby runtime) {
RubyModule etcModule = runtime.defineModule("Etc");
runtime.setEtc(etcModule);
etcModule.defineAnnotatedMethods(RubyEtc.class);
definePasswdStruct(runtime);
defineGroupStruct(runtime);
return etcModule;
}
private static void definePasswdStruct(Ruby runtime) {
IRubyObject[] args = new IRubyObject[] {
runtime.newString("Passwd"),
runtime.newSymbol("name"),
runtime.newSymbol("passwd"),
runtime.newSymbol("uid"),
runtime.newSymbol("gid"),
runtime.newSymbol("gecos"),
runtime.newSymbol("dir"),
runtime.newSymbol("shell"),
runtime.newSymbol("change"),
runtime.newSymbol("uclass"),
runtime.newSymbol("expire")
};
runtime.setPasswdStruct(RubyStruct.newInstance(runtime.getStructClass(), args, Block.NULL_BLOCK));
}
private static void defineGroupStruct(Ruby runtime) {
IRubyObject[] args = new IRubyObject[] {
runtime.newString("Group"),
runtime.newSymbol("name"),
runtime.newSymbol("passwd"),
runtime.newSymbol("gid"),
runtime.newSymbol("mem")
};
runtime.setGroupStruct(RubyStruct.newInstance(runtime.getStructClass(), args, Block.NULL_BLOCK));
}
private static IRubyObject setupPasswd(Ruby runtime, Passwd passwd) {
IRubyObject[] args = new IRubyObject[] {
runtime.newString(passwd.getLoginName()),
runtime.newString(passwd.getPassword()),
runtime.newFixnum(passwd.getUID()),
runtime.newFixnum(passwd.getGID()),
runtime.newString(passwd.getGECOS()),
runtime.newString(passwd.getHome()),
runtime.newString(passwd.getShell()),
runtime.newFixnum(passwd.getPasswdChangeTime()),
runtime.newString(passwd.getAccessClass()),
runtime.newFixnum(passwd.getExpire())
};
return RubyStruct.newStruct(runtime.getPasswdStruct(), args, Block.NULL_BLOCK);
}
private static IRubyObject setupGroup(Ruby runtime, Group group) {
IRubyObject[] args = new IRubyObject[] {
runtime.newString(group.getName()),
runtime.newString(group.getPassword()),
runtime.newFixnum(group.getGID()),
intoStringArray(runtime, group.getMembers())
};
return RubyStruct.newStruct(runtime.getGroupStruct(), args, Block.NULL_BLOCK);
}
private static IRubyObject intoStringArray(Ruby runtime, String[] members) {
IRubyObject[] arr = new IRubyObject[members.length];
for(int i = 0; i<arr.length; i++) {
arr[i] = runtime.newString(members[i]);
}
return runtime.newArrayNoCopy(arr);
}
@JRubyMethod(name = "getpwuid", optional=1, module = true)
public static IRubyObject getpwuid(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
POSIX posix = runtime.getPosix();
int uid = args.length == 0 ? posix.getuid() : RubyNumeric.fix2int(args[0]);
Passwd pwd = posix.getpwuid(uid);
if(pwd == null) {
if (Platform.IS_WINDOWS) { // MRI behavior
return recv.getRuntime().getNil();
}
throw runtime.newArgumentError("can't find user for " + uid);
}
return setupPasswd(runtime, pwd);
}
@JRubyMethod(name = "getpwnam", required=1, module = true)
public static IRubyObject getpwnam(IRubyObject recv, IRubyObject name) {
String nam = name.convertToString().toString();
Passwd pwd = recv.getRuntime().getPosix().getpwnam(nam);
if(pwd == null) {
if (Platform.IS_WINDOWS) { // MRI behavior
return recv.getRuntime().getNil();
}
throw recv.getRuntime().newArgumentError("can't find user for " + nam);
}
return setupPasswd(recv.getRuntime(), pwd);
}
@JRubyMethod(name = "passwd", module = true, frame=true)
public static IRubyObject passwd(IRubyObject recv, Block block) {
Ruby runtime = recv.getRuntime();
POSIX posix = runtime.getPosix();
if(block.isGiven()) {
ThreadContext context = runtime.getCurrentContext();
posix.setpwent();
Passwd pw;
while((pw = posix.getpwent()) != null) {
block.yield(context, setupPasswd(runtime, pw));
}
posix.endpwent();
}
Passwd pw = posix.getpwent();
if (pw != null) {
return setupPasswd(runtime, pw);
} else {
return runtime.getNil();
}
}
@JRubyMethod(name = "getlogin", module = true)
public static IRubyObject getlogin(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
String login = runtime.getPosix().getlogin();
if (login != null) {
return runtime.newString(login);
} else {
return runtime.getNil();
}
}
@JRubyMethod(name = "endpwent", module = true)
public static IRubyObject endpwent(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
runtime.getPosix().endpwent();
return runtime.getNil();
}
@JRubyMethod(name = "setpwent", module = true)
public static IRubyObject setpwent(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
runtime.getPosix().setpwent();
return runtime.getNil();
}
@JRubyMethod(name = "getpwent", module = true)
public static IRubyObject getpwent(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
Passwd passwd = runtime.getPosix().getpwent();
if (passwd != null) {
return setupPasswd(recv.getRuntime(), passwd);
} else {
return runtime.getNil();
}
}
@JRubyMethod(name = "getgrnam", required=1, module = true)
public static IRubyObject getgrnam(IRubyObject recv, IRubyObject name) {
String nam = name.convertToString().toString();
Group grp = recv.getRuntime().getPosix().getgrnam(nam);
if(grp == null) {
if (Platform.IS_WINDOWS) { // MRI behavior
return recv.getRuntime().getNil();
}
throw recv.getRuntime().newArgumentError("can't find group for " + nam);
}
return setupGroup(recv.getRuntime(), grp);
}
@JRubyMethod(name = "getgrgid", optional=1, module = true)
public static IRubyObject getgrgid(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
POSIX posix = runtime.getPosix();
int gid = args.length == 0 ? posix.getgid() : RubyNumeric.fix2int(args[0]);
Group gr = posix.getgrgid(gid);
if(gr == null) {
if (Platform.IS_WINDOWS) { // MRI behavior
return runtime.getNil();
}
throw runtime.newArgumentError("can't find group for " + gid);
}
return setupGroup(runtime, gr);
}
@JRubyMethod(name = "endgrent", module = true)
public static IRubyObject endgrent(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
runtime.getPosix().endgrent();
return runtime.getNil();
}
@JRubyMethod(name = "setgrent", module = true)
public static IRubyObject setgrent(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
runtime.getPosix().setgrent();
return runtime.getNil();
}
@JRubyMethod(name = "group", module = true, frame=true)
public static IRubyObject group(IRubyObject recv, Block block) {
Ruby runtime = recv.getRuntime();
POSIX posix = runtime.getPosix();
if(block.isGiven()) {
ThreadContext context = runtime.getCurrentContext();
posix.setgrent();
Group gr;
while((gr = posix.getgrent()) != null) {
block.yield(context, setupGroup(runtime, gr));
}
posix.endgrent();
}
Group gr = posix.getgrent();
if (gr != null) {
return setupGroup(runtime, gr);
} else {
return runtime.getNil();
}
}
@JRubyMethod(name = "getgrent", module = true)
public static IRubyObject getgrent(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
Group gr = runtime.getPosix().getgrent();
if (gr != null) {
return setupGroup(recv.getRuntime(), gr);
} else {
return runtime.getNil();
}
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Joey Gibson <joey@joeygibson.com>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 David Corbin <dcorbin@users.sf.net>
* Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.Frame;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ObjectMarshal;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.SafePropertyAccessor;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Exception")
public class RubyException extends RubyObject {
private StackTraceElement[] backtraceFrames;
private StackTraceElement[] javaStackTrace;
private IRubyObject backtrace;
public IRubyObject message;
public static final int TRACE_HEAD = 8;
public static final int TRACE_TAIL = 4;
public static final int TRACE_MAX = TRACE_HEAD + TRACE_TAIL + 6;
protected RubyException(Ruby runtime, RubyClass rubyClass) {
this(runtime, rubyClass, null);
}
public RubyException(Ruby runtime, RubyClass rubyClass, String message) {
super(runtime, rubyClass);
this.message = message == null ? runtime.getNil() : runtime.newString(message);
}
private static ObjectAllocator EXCEPTION_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyException instance = new RubyException(runtime, klass);
// for future compatibility as constructors move toward not accepting metaclass?
instance.setMetaClass(klass);
return instance;
}
};
private static final ObjectMarshal EXCEPTION_MARSHAL = new ObjectMarshal() {
public void marshalTo(Ruby runtime, Object obj, RubyClass type,
MarshalStream marshalStream) throws IOException {
RubyException exc = (RubyException)obj;
marshalStream.registerLinkTarget(exc);
List<Variable<IRubyObject>> attrs = exc.getVariableList();
attrs.add(new VariableEntry<IRubyObject>(
"mesg", exc.message == null ? runtime.getNil() : exc.message));
attrs.add(new VariableEntry<IRubyObject>("bt", exc.getBacktrace()));
marshalStream.dumpVariables(attrs);
}
public Object unmarshalFrom(Ruby runtime, RubyClass type,
UnmarshalStream unmarshalStream) throws IOException {
RubyException exc = (RubyException)type.allocate();
unmarshalStream.registerLinkTarget(exc);
unmarshalStream.defaultVariablesUnmarshal(exc);
exc.message = exc.removeInternalVariable("mesg");
exc.set_backtrace(exc.removeInternalVariable("bt"));
return exc;
}
};
public static RubyClass createExceptionClass(Ruby runtime) {
RubyClass exceptionClass = runtime.defineClass("Exception", runtime.getObject(), EXCEPTION_ALLOCATOR);
runtime.setException(exceptionClass);
exceptionClass.setMarshal(EXCEPTION_MARSHAL);
exceptionClass.defineAnnotatedMethods(RubyException.class);
return exceptionClass;
}
public static RubyException newException(Ruby runtime, RubyClass excptnClass, String msg) {
return new RubyException(runtime, excptnClass, msg);
}
public void setBacktraceFrames(StackTraceElement[] backtraceFrames) {
this.backtraceFrames = backtraceFrames;
if (TRACE_TYPE == RAW ||
TRACE_TYPE == RAW_FILTERED ||
TRACE_TYPE == RUBY_COMPILED ||
TRACE_TYPE == RUBY_HYBRID) {
javaStackTrace = Thread.currentThread().getStackTrace();
}
}
public static final int RAW = 0;
public static final int RAW_FILTERED = 1;
public static final int RUBY_FRAMED = 2;
public static final int RUBY_COMPILED = 3;
public static final int RUBY_HYBRID = 4;
public static final int TRACE_TYPE;
static {
String style = SafePropertyAccessor.getProperty("jruby.backtrace.style", "ruby_framed").toLowerCase();
if (style.equals("raw")) TRACE_TYPE = RAW;
else if (style.equals("raw_filtered")) TRACE_TYPE = RAW_FILTERED;
else if (style.equals("ruby_framed")) TRACE_TYPE = RUBY_FRAMED;
else if (style.equals("ruby_compiled")) TRACE_TYPE = RUBY_COMPILED;
else if (style.equals("ruby_hybrid")) TRACE_TYPE = RUBY_HYBRID;
else TRACE_TYPE = RUBY_FRAMED;
}
public IRubyObject getBacktrace() {
if (backtrace == null) {
initBacktrace();
}
return backtrace;
}
public void initBacktrace() {
switch (TRACE_TYPE) {
case RAW:
backtrace = ThreadContext.createRawBacktrace(getRuntime(), javaStackTrace, false);
break;
case RAW_FILTERED:
backtrace = ThreadContext.createRawBacktrace(getRuntime(), javaStackTrace, true);
break;
case RUBY_FRAMED:
backtrace = backtraceFrames == null ? getRuntime().getNil() : ThreadContext.createBacktraceFromFrames(getRuntime(), backtraceFrames);
break;
case RUBY_COMPILED:
backtrace = ThreadContext.createRubyCompiledBacktrace(getRuntime(), javaStackTrace);
break;
case RUBY_HYBRID:
backtrace = ThreadContext.createRubyHybridBacktrace(getRuntime(), backtraceFrames, javaStackTrace, getRuntime().getDebug().isTrue());
break;
}
}
@JRubyMethod(optional = 2, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block block) {
if (args.length == 1) message = args[0];
return this;
}
@JRubyMethod
public IRubyObject backtrace() {
return getBacktrace();
}
@JRubyMethod(required = 1)
public IRubyObject set_backtrace(IRubyObject obj) {
if (obj.isNil()) {
backtrace = null;
} else if (!isArrayOfStrings(obj)) {
throw getRuntime().newTypeError("backtrace must be Array of String");
} else {
backtrace = (RubyArray) obj;
}
return backtrace();
}
@JRubyMethod(name = "exception", optional = 1, rest = true, meta = true)
public static IRubyObject exception(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return ((RubyClass) recv).newInstance(context, args, block);
}
@JRubyMethod(optional = 1)
public RubyException exception(IRubyObject[] args) {
switch (args.length) {
case 0 :
return this;
case 1 :
if(args[0] == this) {
return this;
}
RubyException ret = (RubyException)rbClone();
ret.initialize(args, Block.NULL_BLOCK); // This looks wrong, but it's the way MRI does it.
return ret;
default :
throw getRuntime().newArgumentError("Wrong argument count");
}
}
@JRubyMethod
public IRubyObject to_s() {
if (message.isNil()) return getRuntime().newString(getMetaClass().getName());
message.setTaint(isTaint());
return message;
}
@JRubyMethod(name = {"to_str", "message"})
public IRubyObject to_str(ThreadContext context) {
return callMethod(context, MethodIndex.TO_S, "to_s");
}
/** inspects an object and return a kind of debug information
*
*@return A RubyString containing the debug information.
*/
@JRubyMethod
public IRubyObject inspect(ThreadContext context) {
RubyModule rubyClass = getMetaClass();
RubyString exception = RubyString.objAsString(context, this);
if (exception.getByteList().realSize == 0) return getRuntime().newString(rubyClass.getName());
StringBuilder sb = new StringBuilder("#<");
sb.append(rubyClass.getName()).append(": ").append(exception.getByteList()).append(">");
return getRuntime().newString(sb.toString());
}
public void printBacktrace(PrintStream errorStream) {
IRubyObject backtrace = callMethod(getRuntime().getCurrentContext(), "backtrace");
boolean debug = getRuntime().getDebug().isTrue();
if (!backtrace.isNil() && backtrace instanceof RubyArray) {
IRubyObject[] elements = backtrace.convertToArray().toJavaArray();
for (int i = 1; i < elements.length; i++) {
IRubyObject stackTraceLine = elements[i];
if (stackTraceLine instanceof RubyString) {
printStackTraceLine(errorStream, stackTraceLine);
}
if (!debug && i == RubyException.TRACE_HEAD && elements.length > RubyException.TRACE_MAX) {
int hiddenLevels = elements.length - RubyException.TRACE_HEAD - RubyException.TRACE_TAIL;
errorStream.print("\t ... " + hiddenLevels + " levels...\n");
i = elements.length - RubyException.TRACE_TAIL;
}
}
}
}
private void printStackTraceLine(PrintStream errorStream, IRubyObject stackTraceLine) {
errorStream.print("\tfrom " + stackTraceLine + '\n');
}
private boolean isArrayOfStrings(IRubyObject backtrace) {
if (!(backtrace instanceof RubyArray)) return false;
IRubyObject[] elements = ((RubyArray) backtrace).toJavaArray();
for (int i = 0 ; i < elements.length ; i++) {
if (!(elements[i] instanceof RubyString)) return false;
}
return true;
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2003 Joey Gibson <joey@joeygibson.com>
* Copyright (C) 2004-2007 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2007 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.util.io.OpenFile;
import org.jruby.util.io.ChannelDescriptor;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.ext.posix.util.Platform;
import org.jruby.runtime.Block;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.io.DirectoryAsFileException;
import org.jruby.util.io.Stream;
import org.jruby.util.io.ChannelStream;
import org.jruby.util.io.ModeFlags;
import org.jruby.util.JRubyFile;
import org.jruby.util.TypeConverter;
import org.jruby.util.io.BadDescriptorException;
import org.jruby.util.io.FileExistsException;
import org.jruby.util.io.InvalidValueException;
import org.jruby.util.io.PipeException;
/**
* Ruby File class equivalent in java.
**/
@JRubyClass(name="File", parent="IO", include="FileTest")
public class RubyFile extends RubyIO {
private static final long serialVersionUID = 1L;
public static final int LOCK_SH = 1;
public static final int LOCK_EX = 2;
public static final int LOCK_NB = 4;
public static final int LOCK_UN = 8;
private static final int FNM_NOESCAPE = 1;
private static final int FNM_PATHNAME = 2;
private static final int FNM_DOTMATCH = 4;
private static final int FNM_CASEFOLD = 8;
private static final int FNM_SYSCASE;
static {
if (Platform.IS_WINDOWS) {
FNM_SYSCASE = FNM_CASEFOLD;
} else {
FNM_SYSCASE = 0;
}
}
private static boolean startsWithDriveLetterOnWindows(String path) {
return (path != null)
&& Platform.IS_WINDOWS &&
((path.length()>1 && path.charAt(0) == '/') ?
(path.length() > 2
&& isWindowsDriveLetter(path.charAt(1))
&& path.charAt(2) == ':') :
(path.length() > 1
&& isWindowsDriveLetter(path.charAt(0))
&& path.charAt(1) == ':'));
}
// adjusts paths started with '/' or '\\', on windows.
static String adjustRootPathOnWindows(Ruby runtime, String path, String dir) {
if (path == null) return path;
if (Platform.IS_WINDOWS) {
// MRI behavior on Windows: it treats '/' as a root of
// a current drive (but only if SINGLE slash is present!):
// E.g., if current work directory is
// 'D:/home/directory', then '/' means 'D:/'.
//
// Basically, '/path' is treated as a *RELATIVE* path,
// relative to the current drive. '//path' is treated
// as absolute one.
if ((path.startsWith("/") && !(path.length()>2 && path.charAt(2) == ':')) || path.startsWith("\\")) {
if (path.length() > 1 && (path.charAt(1) == '/' || path.charAt(1) == '\\')) {
return path;
}
// First try to use drive letter from supplied dir value,
// then try current work dir.
if (!startsWithDriveLetterOnWindows(dir)) {
dir = runtime.getCurrentDirectory();
}
if (dir.length() >= 2) {
path = dir.substring(0, 2) + path;
}
} else if (startsWithDriveLetterOnWindows(path) && path.length() == 2) {
// compensate for missing slash after drive letter on windows
path += "/";
}
}
return path;
}
protected String path;
private FileLock currentLock;
public RubyFile(Ruby runtime, RubyClass type) {
super(runtime, type);
}
// XXX This constructor is a hack to implement the __END__ syntax.
// Converting a reader back into an InputStream doesn't generally work.
public RubyFile(Ruby runtime, String path, final Reader reader) {
this(runtime, path, new InputStream() {
public int read() throws IOException {
return reader.read();
}
});
}
public RubyFile(Ruby runtime, String path, InputStream in) {
super(runtime, runtime.getFile());
this.path = path;
try {
this.openFile.setMainStream(new ChannelStream(runtime, new ChannelDescriptor(Channels.newChannel(in), getNewFileno(), new FileDescriptor())));
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
}
this.openFile.setMode(openFile.getMainStream().getModes().getOpenFileFlags());
registerDescriptor(openFile.getMainStream().getDescriptor());
}
private static ObjectAllocator FILE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyFile instance = new RubyFile(runtime, klass);
instance.setMetaClass(klass);
return instance;
}
};
@JRubyModule(name="File::Constants")
public static class Constants {}
public static RubyClass createFileClass(Ruby runtime) {
RubyClass fileClass = runtime.defineClass("File", runtime.getIO(), FILE_ALLOCATOR);
runtime.setFile(fileClass);
RubyString separator = runtime.newString("/");
ThreadContext context = runtime.getCurrentContext();
fileClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyFile;
}
};
separator.freeze(context);
fileClass.defineConstant("SEPARATOR", separator);
fileClass.defineConstant("Separator", separator);
if (File.separatorChar == '\\') {
RubyString altSeparator = runtime.newString("\\");
altSeparator.freeze(context);
fileClass.defineConstant("ALT_SEPARATOR", altSeparator);
} else {
fileClass.defineConstant("ALT_SEPARATOR", runtime.getNil());
}
RubyString pathSeparator = runtime.newString(File.pathSeparator);
pathSeparator.freeze(context);
fileClass.defineConstant("PATH_SEPARATOR", pathSeparator);
// TODO: why are we duplicating the constants here, and then in
// File::Constants below? File::Constants is included in IO.
// TODO: These were missing, so we're not handling them elsewhere?
// FIXME: The old value, 32786, didn't match what IOModes expected, so I reference
// the constant here. THIS MAY NOT BE THE CORRECT VALUE.
fileClass.fastSetConstant("BINARY", runtime.newFixnum(ModeFlags.BINARY));
fileClass.fastSetConstant("FNM_NOESCAPE", runtime.newFixnum(FNM_NOESCAPE));
fileClass.fastSetConstant("FNM_CASEFOLD", runtime.newFixnum(FNM_CASEFOLD));
fileClass.fastSetConstant("FNM_SYSCASE", runtime.newFixnum(FNM_SYSCASE));
fileClass.fastSetConstant("FNM_DOTMATCH", runtime.newFixnum(FNM_DOTMATCH));
fileClass.fastSetConstant("FNM_PATHNAME", runtime.newFixnum(FNM_PATHNAME));
// Create constants for open flags
fileClass.fastSetConstant("RDONLY", runtime.newFixnum(ModeFlags.RDONLY));
fileClass.fastSetConstant("WRONLY", runtime.newFixnum(ModeFlags.WRONLY));
fileClass.fastSetConstant("RDWR", runtime.newFixnum(ModeFlags.RDWR));
fileClass.fastSetConstant("CREAT", runtime.newFixnum(ModeFlags.CREAT));
fileClass.fastSetConstant("EXCL", runtime.newFixnum(ModeFlags.EXCL));
fileClass.fastSetConstant("NOCTTY", runtime.newFixnum(ModeFlags.NOCTTY));
fileClass.fastSetConstant("TRUNC", runtime.newFixnum(ModeFlags.TRUNC));
fileClass.fastSetConstant("APPEND", runtime.newFixnum(ModeFlags.APPEND));
fileClass.fastSetConstant("NONBLOCK", runtime.newFixnum(ModeFlags.NONBLOCK));
// Create constants for flock
fileClass.fastSetConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH));
fileClass.fastSetConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX));
fileClass.fastSetConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB));
fileClass.fastSetConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN));
// Create Constants class
RubyModule constants = fileClass.defineModuleUnder("Constants");
// TODO: These were missing, so we're not handling them elsewhere?
constants.fastSetConstant("BINARY", runtime.newFixnum(ModeFlags.BINARY));
constants.fastSetConstant("SYNC", runtime.newFixnum(0x1000));
constants.fastSetConstant("FNM_NOESCAPE", runtime.newFixnum(FNM_NOESCAPE));
constants.fastSetConstant("FNM_CASEFOLD", runtime.newFixnum(FNM_CASEFOLD));
constants.fastSetConstant("FNM_SYSCASE", runtime.newFixnum(FNM_SYSCASE));
constants.fastSetConstant("FNM_DOTMATCH", runtime.newFixnum(FNM_DOTMATCH));
constants.fastSetConstant("FNM_PATHNAME", runtime.newFixnum(FNM_PATHNAME));
// Create constants for open flags
constants.fastSetConstant("RDONLY", runtime.newFixnum(ModeFlags.RDONLY));
constants.fastSetConstant("WRONLY", runtime.newFixnum(ModeFlags.WRONLY));
constants.fastSetConstant("RDWR", runtime.newFixnum(ModeFlags.RDWR));
constants.fastSetConstant("CREAT", runtime.newFixnum(ModeFlags.CREAT));
constants.fastSetConstant("EXCL", runtime.newFixnum(ModeFlags.EXCL));
constants.fastSetConstant("NOCTTY", runtime.newFixnum(ModeFlags.NOCTTY));
constants.fastSetConstant("TRUNC", runtime.newFixnum(ModeFlags.TRUNC));
constants.fastSetConstant("APPEND", runtime.newFixnum(ModeFlags.APPEND));
constants.fastSetConstant("NONBLOCK", runtime.newFixnum(ModeFlags.NONBLOCK));
// Create constants for flock
constants.fastSetConstant("LOCK_SH", runtime.newFixnum(RubyFile.LOCK_SH));
constants.fastSetConstant("LOCK_EX", runtime.newFixnum(RubyFile.LOCK_EX));
constants.fastSetConstant("LOCK_NB", runtime.newFixnum(RubyFile.LOCK_NB));
constants.fastSetConstant("LOCK_UN", runtime.newFixnum(RubyFile.LOCK_UN));
// File::Constants module is included in IO.
runtime.getIO().includeModule(constants);
runtime.getFileTest().extend_object(fileClass);
fileClass.defineAnnotatedMethods(RubyFile.class);
return fileClass;
}
@JRubyMethod
@Override
public IRubyObject close() {
// Make sure any existing lock is released before we try and close the file
if (currentLock != null) {
try {
currentLock.release();
} catch (IOException e) {
throw getRuntime().newIOError(e.getMessage());
}
}
return super.close();
}
@JRubyMethod(required = 1)
public IRubyObject flock(ThreadContext context, IRubyObject lockingConstant) {
// TODO: port exact behavior from MRI, and move most locking logic into ChannelDescriptor
// TODO: for all LOCK_NB cases, return false if they would block
ChannelDescriptor descriptor = openFile.getMainStream().getDescriptor();
// null channel always succeeds for all locking operations
if (descriptor.isNull()) return RubyFixnum.zero(context.getRuntime());
FileChannel fileChannel = (FileChannel)descriptor.getChannel();
int lockMode = RubyNumeric.num2int(lockingConstant);
// Exclusive locks in Java require the channel to be writable, otherwise
// an exception is thrown (terminating JRuby execution).
// But flock behavior of MRI is that it allows
// exclusive locks even on non-writable file. So we convert exclusive
// lock to shared lock if the channel is not writable, to better match
// the MRI behavior.
if (!openFile.isWritable() && (lockMode & LOCK_EX) > 0) {
lockMode = (lockMode ^ LOCK_EX) | LOCK_SH;
}
try {
switch (lockMode) {
case LOCK_UN:
case LOCK_UN | LOCK_NB:
if (currentLock != null) {
currentLock.release();
currentLock = null;
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_EX:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.lock();
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_EX | LOCK_NB:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.tryLock();
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_SH:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.lock(0L, Long.MAX_VALUE, true);
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
case LOCK_SH | LOCK_NB:
if (currentLock != null) {
currentLock.release();
currentLock = null;
}
currentLock = fileChannel.tryLock(0L, Long.MAX_VALUE, true);
if (currentLock != null) {
return RubyFixnum.zero(context.getRuntime());
}
break;
default:
}
} catch (IOException ioe) {
if (context.getRuntime().getDebug().isTrue()) {
ioe.printStackTrace(System.err);
}
// Return false here
} catch (java.nio.channels.OverlappingFileLockException ioe) {
if (context.getRuntime().getDebug().isTrue()) {
ioe.printStackTrace(System.err);
}
// Return false here
}
return context.getRuntime().getFalse();
}
@JRubyMethod(required = 1, optional = 2, frame = true, visibility = Visibility.PRIVATE)
@Override
public IRubyObject initialize(IRubyObject[] args, Block block) {
if (openFile == null) {
throw getRuntime().newRuntimeError("reinitializing File");
}
if (args.length > 0 && args.length < 3) {
IRubyObject fd = TypeConverter.convertToTypeWithCheck(args[0], getRuntime().getFixnum(), MethodIndex.TO_INT, "to_int");
if (!fd.isNil()) {
args[0] = fd;
return super.initialize(args, block);
}
}
return openFile(args);
}
private IRubyObject openFile(IRubyObject args[]) {
IRubyObject filename = args[0].convertToString();
getRuntime().checkSafeString(filename);
path = filename.convertToString().getUnicodeValue();
String modeString;
ModeFlags modes;
int perm;
try {
if ((args.length > 1 && args[1] instanceof RubyFixnum) || (args.length > 2 && !args[2].isNil())) {
if (args[1] instanceof RubyFixnum) {
modes = new ModeFlags(RubyNumeric.num2int(args[1]));
} else {
modeString = args[1].convertToString().toString();
modes = getIOModes(getRuntime(), modeString);
}
if (args.length > 2 && !args[2].isNil()) {
perm = RubyNumeric.num2int(args[2]);
} else {
perm = 438; // 0666
}
sysopenInternal(path, modes, perm);
} else {
modeString = "r";
if (args.length > 1) {
if (!args[1].isNil()) {
modeString = args[1].convertToString().toString();
}
}
openInternal(path, modeString);
}
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} finally {}
return this;
}
private void sysopenInternal(String path, ModeFlags modes, int perm) throws InvalidValueException {
openFile = new OpenFile();
openFile.setPath(path);
openFile.setMode(modes.getOpenFileFlags());
ChannelDescriptor descriptor = sysopen(path, modes, perm);
openFile.setMainStream(fdopen(descriptor, modes));
registerDescriptor(descriptor);
}
private void openInternal(String path, String modeString) throws InvalidValueException {
openFile = new OpenFile();
openFile.setMode(getIOModes(getRuntime(), modeString).getOpenFileFlags());
openFile.setPath(path);
openFile.setMainStream(fopen(path, modeString));
registerDescriptor(openFile.getMainStream().getDescriptor());
}
private ChannelDescriptor sysopen(String path, ModeFlags modes, int perm) throws InvalidValueException {
try {
ChannelDescriptor descriptor = ChannelDescriptor.open(
getRuntime().getCurrentDirectory(),
path,
modes,
perm,
getRuntime().getPosix());
// TODO: check if too many open files, GC and try again
return descriptor;
} catch (FileNotFoundException fnfe) {
throw getRuntime().newErrnoENOENTError();
} catch (DirectoryAsFileException dafe) {
throw getRuntime().newErrnoEISDirError();
} catch (FileExistsException fee) {
throw getRuntime().newErrnoEEXISTError("file exists: " + path);
} catch (IOException ioe) {
throw getRuntime().newIOErrorFromException(ioe);
}
}
private Stream fopen(String path, String modeString) {
try {
Stream stream = ChannelStream.fopen(
getRuntime(),
path,
getIOModes(getRuntime(), modeString));
if (stream == null) {
// TODO
// if (errno == EMFILE || errno == ENFILE) {
// rb_gc();
// file = fopen(fname, mode);
// }
// if (!file) {
// rb_sys_fail(fname);
// }
}
// Do we need to be in SETVBUF mode for buffering to make sense? This comes up elsewhere.
// #ifdef USE_SETVBUF
// if (setvbuf(file, NULL, _IOFBF, 0) != 0)
// rb_warn("setvbuf() can't be honoured for %s", fname);
// #endif
// #ifdef __human68k__
// fmode(file, _IOTEXT);
// #endif
return stream;
} catch (BadDescriptorException e) {
throw getRuntime().newErrnoEBADFError();
} catch (FileNotFoundException ex) {
// FNFException can be thrown in both cases, when the file
// is not found, or when permission is denied.
if (Ruby.isSecurityRestricted() || new File(path).exists()) {
throw getRuntime().newErrnoEACCESError(
"Permission denied - " + path);
}
throw getRuntime().newErrnoENOENTError(
"File not found - " + path);
} catch (DirectoryAsFileException ex) {
throw getRuntime().newErrnoEISDirError();
} catch (FileExistsException ex) {
throw getRuntime().newErrnoEEXISTError(path);
} catch (IOException ex) {
throw getRuntime().newIOErrorFromException(ex);
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} catch (PipeException ex) {
throw getRuntime().newErrnoEPIPEError();
}
}
@JRubyMethod(required = 1)
public IRubyObject chmod(ThreadContext context, IRubyObject arg) {
int mode = (int) arg.convertToInteger().getLongValue();
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError("No such file or directory - " + path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().chmod(path, mode));
}
@JRubyMethod(required = 2)
public IRubyObject chown(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
int owner = -1;
if (!arg1.isNil()) {
owner = RubyNumeric.num2int(arg1);
}
int group = -1;
if (!arg2.isNil()) {
group = RubyNumeric.num2int(arg2);
}
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError("No such file or directory - " + path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().chown(path, owner, group));
}
@JRubyMethod
public IRubyObject atime(ThreadContext context) {
return context.getRuntime().newFileStat(path, false).atime();
}
@JRubyMethod
public IRubyObject ctime(ThreadContext context) {
return context.getRuntime().newFileStat(path, false).ctime();
}
@JRubyMethod(required = 1)
public IRubyObject lchmod(ThreadContext context, IRubyObject arg) {
int mode = (int) arg.convertToInteger().getLongValue();
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError("No such file or directory - " + path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().lchmod(path, mode));
}
// TODO: this method is not present in MRI!
@JRubyMethod(required = 2)
public IRubyObject lchown(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
int owner = -1;
if (!arg1.isNil()) {
owner = RubyNumeric.num2int(arg1);
}
int group = -1;
if (!arg2.isNil()) {
group = RubyNumeric.num2int(arg2);
}
if (!new File(path).exists()) {
throw context.getRuntime().newErrnoENOENTError("No such file or directory - " + path);
}
return context.getRuntime().newFixnum(context.getRuntime().getPosix().lchown(path, owner, group));
}
@JRubyMethod
public IRubyObject lstat(ThreadContext context) {
return context.getRuntime().newFileStat(path, true);
}
@JRubyMethod
public IRubyObject mtime(ThreadContext context) {
return getLastModified(context.getRuntime(), path);
}
@JRubyMethod
public RubyString path(ThreadContext context) {
return context.getRuntime().newString(path);
}
@JRubyMethod
@Override
public IRubyObject stat(ThreadContext context) {
openFile.checkClosed(context.getRuntime());
return context.getRuntime().newFileStat(path, false);
}
@JRubyMethod(required = 1)
public IRubyObject truncate(ThreadContext context, IRubyObject arg) {
RubyInteger newLength = arg.convertToInteger();
if (newLength.getLongValue() < 0) {
throw context.getRuntime().newErrnoEINVALError("invalid argument: " + path);
}
try {
openFile.checkWritable(context.getRuntime());
openFile.getMainStream().ftruncate(newLength.getLongValue());
} catch (BadDescriptorException e) {
throw context.getRuntime().newErrnoEBADFError();
} catch (PipeException e) {
throw context.getRuntime().newErrnoESPIPEError();
} catch (InvalidValueException ex) {
throw context.getRuntime().newErrnoEINVALError();
} catch (IOException e) {
// Should we do anything?
}
return RubyFixnum.zero(context.getRuntime());
}
@Override
public String toString() {
return "RubyFile(" + path + ", " + openFile.getMode() + ", " + openFile.getMainStream().getDescriptor().getFileno() + ")";
}
// TODO: This is also defined in the MetaClass too...Consolidate somewhere.
private static ModeFlags getModes(Ruby runtime, IRubyObject object) throws InvalidValueException {
if (object instanceof RubyString) {
return getIOModes(runtime, ((RubyString) object).toString());
} else if (object instanceof RubyFixnum) {
return new ModeFlags(((RubyFixnum) object).getLongValue());
}
throw runtime.newTypeError("Invalid type for modes");
}
@JRubyMethod
@Override
public IRubyObject inspect() {
StringBuilder val = new StringBuilder();
val.append("#<File:").append(path);
if(!openFile.isOpen()) {
val.append(" (closed)");
}
val.append(">");
return getRuntime().newString(val.toString());
}
/* File class methods */
@JRubyMethod(required = 1, optional = 1, meta = true)
public static IRubyObject basename(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
String name = RubyString.stringValue(args[0]).toString();
// MRI-compatible basename handling for windows drive letter paths
if (Platform.IS_WINDOWS) {
if (name.length() > 1 && name.charAt(1) == ':' && Character.isLetter(name.charAt(0))) {
switch (name.length()) {
case 2:
return RubyString.newEmptyString(context.getRuntime()).infectBy(args[0]);
case 3:
return context.getRuntime().newString(name.substring(2)).infectBy(args[0]);
default:
switch (name.charAt(2)) {
case '/':
case '\\':
break;
default:
// strip c: away from relative-pathed name
name = name.substring(2);
break;
}
break;
}
}
}
while (name.length() > 1 && name.charAt(name.length() - 1) == '/') {
name = name.substring(0, name.length() - 1);
}
// Paths which end in "/" or "\\" must be stripped off.
int slashCount = 0;
int length = name.length();
for (int i = length - 1; i >= 0; i--) {
char c = name.charAt(i);
if (c != '/' && c != '\\') {
break;
}
slashCount++;
}
if (slashCount > 0 && length > 1) {
name = name.substring(0, name.length() - slashCount);
}
int index = name.lastIndexOf('/');
if (index == -1) {
// XXX actually only on windows...
index = name.lastIndexOf('\\');
}
if (!name.equals("/") && index != -1) {
name = name.substring(index + 1);
}
if (args.length == 2) {
String ext = RubyString.stringValue(args[1]).toString();
if (".*".equals(ext)) {
index = name.lastIndexOf('.');
if (index > 0) { // -1 no match; 0 it is dot file not extension
name = name.substring(0, index);
}
} else if (name.endsWith(ext)) {
name = name.substring(0, name.length() - ext.length());
}
}
return context.getRuntime().newString(name).infectBy(args[0]);
}
@JRubyMethod(required = 2, rest = true, meta = true)
public static IRubyObject chmod(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int count = 0;
RubyInteger mode = args[0].convertToInteger();
for (int i = 1; i < args.length; i++) {
IRubyObject filename = args[i];
if (!RubyFileTest.exist_p(filename, filename.convertToString()).isTrue()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + filename);
}
boolean result = 0 == runtime.getPosix().chmod(filename.toString(), (int)mode.getLongValue());
if (result) {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 3, rest = true, meta = true)
public static IRubyObject chown(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int count = 0;
int owner = -1;
if (!args[0].isNil()) {
owner = RubyNumeric.num2int(args[0]);
}
int group = -1;
if (!args[1].isNil()) {
group = RubyNumeric.num2int(args[1]);
}
for (int i = 2; i < args.length; i++) {
IRubyObject filename = args[i];
if (!RubyFileTest.exist_p(filename, filename.convertToString()).isTrue()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + filename);
}
boolean result = 0 == runtime.getPosix().chown(filename.toString(), owner, group);
if (result) {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 1, meta = true)
public static IRubyObject dirname(ThreadContext context, IRubyObject recv, IRubyObject arg) {
RubyString filename = RubyString.stringValue(arg);
String jfilename = filename.toString();
String name = jfilename.replace('\\', '/');
int minPathLength = 1;
boolean trimmedSlashes = false;
boolean startsWithDriveLetterOnWindows = startsWithDriveLetterOnWindows(name);
if (startsWithDriveLetterOnWindows) {
minPathLength = 3;
}
while (name.length() > minPathLength && name.charAt(name.length() - 1) == '/') {
trimmedSlashes = true;
name = name.substring(0, name.length() - 1);
}
String result;
if (startsWithDriveLetterOnWindows && name.length() == 2) {
if (trimmedSlashes) {
// C:\ is returned unchanged
result = jfilename.substring(0, 3);
} else {
result = jfilename.substring(0, 2) + '.';
}
} else {
//TODO deal with UNC names
int index = name.lastIndexOf('/');
if (index == -1) {
if (startsWithDriveLetterOnWindows) {
return context.getRuntime().newString(jfilename.substring(0, 2) + ".");
} else {
return context.getRuntime().newString(".");
}
}
if (index == 0) return context.getRuntime().newString("/");
if (startsWithDriveLetterOnWindows && index == 2) {
// Include additional path separator
// (so that dirname of "C:\file.txt" is "C:\", not "C:")
index++;
}
result = jfilename.substring(0, index);
}
char endChar;
// trim trailing slashes
while (result.length() > minPathLength) {
endChar = result.charAt(result.length() - 1);
if (endChar == '/' || endChar == '\\') {
result = result.substring(0, result.length() - 1);
} else {
break;
}
}
return context.getRuntime().newString(result).infectBy(filename);
}
private static boolean isWindowsDriveLetter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
/**
* Returns the extension name of the file. An empty string is returned if
* the filename (not the entire path) starts or ends with a dot.
* @param recv
* @param arg Path to get extension name of
* @return Extension, including the dot, or an empty string
*/
@JRubyMethod(required = 1, meta = true)
public static IRubyObject extname(ThreadContext context, IRubyObject recv, IRubyObject arg) {
IRubyObject baseFilename = basename(context, recv, new IRubyObject[]{arg});
String filename = RubyString.stringValue(baseFilename).toString();
String result = "";
int dotIndex = filename.lastIndexOf(".");
if (dotIndex > 0 && dotIndex != (filename.length() - 1)) {
// Dot is not at beginning and not at end of filename.
result = filename.substring(dotIndex);
}
return context.getRuntime().newString(result);
}
/**
* Converts a pathname to an absolute pathname. Relative paths are
* referenced from the current working directory of the process unless
* a second argument is given, in which case it will be used as the
* starting point. If the second argument is also relative, it will
* first be converted to an absolute pathname.
* @param recv
* @param args
* @return Resulting absolute path as a String
*/
@JRubyMethod(required = 1, optional = 1, meta = true)
public static IRubyObject expand_path(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
String relativePath = RubyString.stringValue(args[0]).toString();
boolean isAbsoluteWithFilePrefix = relativePath.startsWith("file:");
String cwd = null;
// Handle ~user paths
relativePath = expandUserPath(context, relativePath);
// If there's a second argument, it's the path to which the first
// argument is relative.
if (args.length == 2 && !args[1].isNil()) {
String cwdArg = RubyString.stringValue(args[1]).toString();
// Handle ~user paths.
cwd = expandUserPath(context, cwdArg);
cwd = adjustRootPathOnWindows(runtime, cwd, null);
boolean startsWithSlashNotOnWindows = (cwd != null)
&& !Platform.IS_WINDOWS && cwd.length() > 0
&& cwd.charAt(0) == '/';
// TODO: better detection when path is absolute or not.
// If the path isn't absolute, then prepend the current working
// directory to the path.
if (!startsWithSlashNotOnWindows && !startsWithDriveLetterOnWindows(cwd)) {
cwd = new File(runtime.getCurrentDirectory(), cwd).getAbsolutePath();
}
} else {
// If there's no second argument, simply use the working directory
// of the runtime.
cwd = runtime.getCurrentDirectory();
}
// Something wrong we don't know the cwd...
// TODO: Is this behavior really desirable? /mov
if (cwd == null) return runtime.getNil();
/* The counting of slashes that follows is simply a way to adhere to
* Ruby's UNC (or something) compatibility. When Ruby's expand_path is
* called with "//foo//bar" it will return "//foo/bar". JRuby uses
* java.io.File, and hence returns "/foo/bar". In order to retain
* java.io.File in the lower layers and provide full Ruby
* compatibility, the number of extra slashes must be counted and
* prepended to the result.
*/
// TODO: special handling on windows for some corner cases
// if (IS_WINDOWS) {
// if (relativePath.startsWith("//")) {
// if (relativePath.length() > 2 && relativePath.charAt(2) != '/') {
// int nextSlash = relativePath.indexOf('/', 3);
// if (nextSlash != -1) {
// return runtime.newString(
// relativePath.substring(0, nextSlash)
// + canonicalize(relativePath.substring(nextSlash)));
// } else {
// return runtime.newString(relativePath);
// }
// }
// }
// }
// Find out which string to check.
String padSlashes = "";
if (!Platform.IS_WINDOWS) {
if (relativePath.length() > 0 && relativePath.charAt(0) == '/') {
padSlashes = countSlashes(relativePath);
} else if (cwd.length() > 0 && cwd.charAt(0) == '/') {
padSlashes = countSlashes(cwd);
}
}
JRubyFile path;
if (relativePath.length() == 0) {
path = JRubyFile.create(relativePath, cwd);
} else {
relativePath = adjustRootPathOnWindows(runtime, relativePath, cwd);
path = JRubyFile.create(cwd, relativePath);
}
String tempResult = padSlashes + canonicalize(path.getAbsolutePath());
if(isAbsoluteWithFilePrefix) {
tempResult = tempResult.substring(tempResult.indexOf("file:"));
}
return runtime.newString(tempResult);
}
/**
* This method checks a path, and if it starts with ~, then it expands
* the path to the absolute path of the user's home directory. If the
* string does not begin with ~, then the string is simply returned.
* unaltered.
* @param recv
* @param path Path to check
* @return Expanded path
*/
public static String expandUserPath(ThreadContext context, String path) {
int pathLength = path.length();
if (pathLength >= 1 && path.charAt(0) == '~') {
// Enebo : Should ~frogger\\foo work (it doesnt in linux ruby)?
int userEnd = path.indexOf('/');
if (userEnd == -1) {
if (pathLength == 1) {
// Single '~' as whole path to expand
path = RubyDir.getHomeDirectoryPath(context).toString();
} else {
// No directory delimeter. Rest of string is username
userEnd = pathLength;
}
}
if (userEnd == 1) {
// '~/...' as path to expand
path = RubyDir.getHomeDirectoryPath(context).toString() +
path.substring(1);
} else if (userEnd > 1){
// '~user/...' as path to expand
String user = path.substring(1, userEnd);
IRubyObject dir = RubyDir.getHomeDirectoryPath(context, user);
if (dir.isNil()) {
throw context.getRuntime().newArgumentError("user " + user + " does not exist");
}
path = "" + dir + (pathLength == userEnd ? "" : path.substring(userEnd));
}
}
return path;
}
/**
* Returns a string consisting of <code>n-1</code> slashes, where
* <code>n</code> is the number of slashes at the beginning of the input
* string.
* @param stringToCheck
* @return
*/
private static String countSlashes( String stringToCheck ) {
// Count number of extra slashes in the beginning of the string.
int slashCount = 0;
for (int i = 0; i < stringToCheck.length(); i++) {
if (stringToCheck.charAt(i) == '/') {
slashCount++;
} else {
break;
}
}
// If there are N slashes, then we want N-1.
if (slashCount > 0) {
slashCount--;
}
// Prepare a string with the same number of redundant slashes so that
// we easily can prepend it to the result.
byte[] slashes = new byte[slashCount];
for (int i = 0; i < slashCount; i++) {
slashes[i] = '/';
}
return new String(slashes);
}
private static String canonicalize(String path) {
return canonicalize(null, path);
}
private static String canonicalize(String canonicalPath, String remaining) {
if (remaining == null) {
if ("".equals(canonicalPath)) {
return "/";
} else {
// compensate for missing slash after drive letter on windows
if (startsWithDriveLetterOnWindows(canonicalPath)
&& canonicalPath.length() == 2) {
canonicalPath += "/";
}
}
return canonicalPath;
}
String child;
int slash = remaining.indexOf('/');
if (slash == -1) {
child = remaining;
remaining = null;
} else {
child = remaining.substring(0, slash);
remaining = remaining.substring(slash + 1);
}
if (child.equals(".")) {
// skip it
if (canonicalPath != null && canonicalPath.length() == 0 ) canonicalPath += "/";
} else if (child.equals("..")) {
if (canonicalPath == null) throw new IllegalArgumentException("Cannot have .. at the start of an absolute path");
int lastDir = canonicalPath.lastIndexOf('/');
if (lastDir == -1) {
if (startsWithDriveLetterOnWindows(canonicalPath)) {
// do nothing, we should not delete the drive letter
} else {
canonicalPath = "";
}
} else {
canonicalPath = canonicalPath.substring(0, lastDir);
}
} else if (canonicalPath == null) {
canonicalPath = child;
} else {
canonicalPath += "/" + child;
}
return canonicalize(canonicalPath, remaining);
}
/**
* Returns true if path matches against pattern The pattern is not a regular expression;
* instead it follows rules similar to shell filename globbing. It may contain the following
* metacharacters:
* *: Glob - match any sequence chars (re: .*). If like begins with '.' then it doesn't.
* ?: Matches a single char (re: .).
* [set]: Matches a single char in a set (re: [...]).
*
*/
@JRubyMethod(name = {"fnmatch", "fnmatch?"}, required = 2, optional = 1, meta = true)
public static IRubyObject fnmatch(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
int flags = args.length == 3 ? RubyNumeric.num2int(args[2]) : 0;
ByteList pattern = args[0].convertToString().getByteList();
ByteList path = args[1].convertToString().getByteList();
if (org.jruby.util.Dir.fnmatch(pattern.bytes, pattern.begin, pattern.begin+pattern.realSize,
path.bytes, path.begin, path.begin+path.realSize, flags) == 0) {
return context.getRuntime().getTrue();
}
return context.getRuntime().getFalse();
}
@JRubyMethod(name = "ftype", required = 1, meta = true)
public static IRubyObject ftype(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return context.getRuntime().newFileStat(filename.convertToString().toString(), true).ftype();
}
private static String inspectJoin(ThreadContext context, IRubyObject recv, RubyArray parent, RubyArray array) {
Ruby runtime = context.getRuntime();
// If already inspecting, there is no need to register/unregister again.
if (runtime.isInspecting(parent)) return join(context, recv, array).toString();
try {
runtime.registerInspecting(parent);
return join(context, recv, array).toString();
} finally {
runtime.unregisterInspecting(parent);
}
}
private static RubyString join(ThreadContext context, IRubyObject recv, RubyArray ary) {
IRubyObject[] args = ary.toJavaArray();
boolean isTainted = false;
StringBuilder buffer = new StringBuilder();
Ruby runtime = context.getRuntime();
for (int i = 0; i < args.length; i++) {
if (args[i].isTaint()) {
isTainted = true;
}
String element;
if (args[i] instanceof RubyString) {
element = args[i].toString();
} else if (args[i] instanceof RubyArray) {
if (runtime.isInspecting(args[i])) {
element = "[...]";
} else {
element = inspectJoin(context, recv, ary, ((RubyArray)args[i]));
}
} else {
element = args[i].convertToString().toString();
}
chomp(buffer);
if (i > 0 && !element.startsWith("/") && !element.startsWith("\\")) {
buffer.append("/");
}
buffer.append(element);
}
RubyString fixedStr = RubyString.newString(runtime, buffer.toString());
fixedStr.setTaint(isTainted);
return fixedStr;
}
/*
* Fixme: This does not have exact same semantics as RubyArray.join, but they
* probably could be consolidated (perhaps as join(args[], sep, doChomp)).
*/
@JRubyMethod(rest = true, meta = true)
public static RubyString join(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return join(context, recv, RubyArray.newArrayNoCopyLight(context.getRuntime(), args));
}
private static void chomp(StringBuilder buffer) {
int lastIndex = buffer.length() - 1;
while (lastIndex >= 0 && (buffer.lastIndexOf("/") == lastIndex || buffer.lastIndexOf("\\") == lastIndex)) {
buffer.setLength(lastIndex);
lastIndex--;
}
}
@JRubyMethod(name = "lstat", required = 1, meta = true)
public static IRubyObject lstat(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = filename.convertToString().toString();
if(f.startsWith("file:") && f.indexOf('!') != -1) {
f = f.substring(5, f.indexOf("!"));
}
return context.getRuntime().newFileStat(f, true);
}
@JRubyMethod(name = "stat", required = 1, meta = true)
public static IRubyObject stat(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = filename.convertToString().toString();
if(f.startsWith("file:") && f.indexOf('!') != -1) {
f = f.substring(5, f.indexOf("!"));
}
return context.getRuntime().newFileStat(f, false);
}
@JRubyMethod(name = "atime", required = 1, meta = true)
public static IRubyObject atime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = filename.convertToString().toString();
if(f.startsWith("file:") && f.indexOf('!') != -1) {
f = f.substring(5, f.indexOf("!"));
}
return context.getRuntime().newFileStat(f, false).atime();
}
@JRubyMethod(name = "ctime", required = 1, meta = true)
public static IRubyObject ctime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
String f = filename.convertToString().toString();
if(f.startsWith("file:") && f.indexOf('!') != -1) {
f = f.substring(5, f.indexOf("!"));
}
return context.getRuntime().newFileStat(f, false).ctime();
}
@JRubyMethod(required = 2, rest = true, meta = true)
public static IRubyObject lchmod(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int count = 0;
RubyInteger mode = args[0].convertToInteger();
for (int i = 1; i < args.length; i++) {
IRubyObject filename = args[i];
if (!RubyFileTest.exist_p(filename, filename.convertToString()).isTrue()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + filename);
}
boolean result = 0 == runtime.getPosix().lchmod(filename.toString(), (int)mode.getLongValue());
if (result) {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 3, rest = true, meta = true)
public static IRubyObject lchown(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int owner = !args[0].isNil() ? RubyNumeric.num2int(args[0]) : -1;
int group = !args[1].isNil() ? RubyNumeric.num2int(args[1]) : -1;
int count = 0;
for (int i = 2; i < args.length; i++) {
IRubyObject filename = args[i];
if (!RubyFileTest.exist_p(filename, filename.convertToString()).isTrue()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + filename);
}
boolean result = 0 == runtime.getPosix().lchown(filename.toString(), owner, group);
if (result) {
count++;
}
}
return runtime.newFixnum(count);
}
@JRubyMethod(required = 2, meta = true)
public static IRubyObject link(ThreadContext context, IRubyObject recv, IRubyObject from, IRubyObject to) {
Ruby runtime = context.getRuntime();
RubyString fromStr = RubyString.stringValue(from);
RubyString toStr = RubyString.stringValue(to);
try {
if (runtime.getPosix().link(
fromStr.toString(),toStr.toString()) == -1) {
// FIXME: When we get JNA3 we need to properly write this to errno.
throw runtime.newErrnoEEXISTError("File exists - "
+ fromStr + " or " + toStr);
}
} catch (java.lang.UnsatisfiedLinkError ule) {
throw runtime.newNotImplementedError("link() function is unimplemented on this machine");
}
return runtime.newFixnum(0);
}
@JRubyMethod(name = "mtime", required = 1, meta = true)
public static IRubyObject mtime(ThreadContext context, IRubyObject recv, IRubyObject filename) {
return getLastModified(context.getRuntime(), filename.convertToString().toString());
}
@JRubyMethod(required = 2, meta = true)
public static IRubyObject rename(ThreadContext context, IRubyObject recv, IRubyObject oldName, IRubyObject newName) {
Ruby runtime = context.getRuntime();
RubyString oldNameString = RubyString.stringValue(oldName);
RubyString newNameString = RubyString.stringValue(newName);
runtime.checkSafeString(oldNameString);
runtime.checkSafeString(newNameString);
JRubyFile oldFile = JRubyFile.create(runtime.getCurrentDirectory(), oldNameString.toString());
JRubyFile newFile = JRubyFile.create(runtime.getCurrentDirectory(), newNameString.toString());
if (!oldFile.exists() || !newFile.getParentFile().exists()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + oldNameString +
" or " + newNameString);
}
JRubyFile dest = JRubyFile.create(runtime.getCurrentDirectory(), newNameString.toString());
if (oldFile.renameTo(dest)) { // rename is successful
return RubyFixnum.zero(runtime);
}
// rename via Java API call wasn't successful, let's try some tricks, similar to MRI
if (newFile.exists()) {
runtime.getPosix().chmod(newNameString.toString(), 0666);
newFile.delete();
}
if (oldFile.renameTo(dest)) { // try to rename one more time
return RubyFixnum.zero(runtime);
}
throw runtime.newErrnoEACCESError("Permission denied - " + oldNameString + " or " +
newNameString);
}
@JRubyMethod(required = 1, meta = true)
public static RubyArray split(ThreadContext context, IRubyObject recv, IRubyObject arg) {
RubyString filename = RubyString.stringValue(arg);
return context.getRuntime().newArray(dirname(context, recv, filename),
basename(context, recv, new IRubyObject[] { filename }));
}
@JRubyMethod(required = 2, meta = true)
public static IRubyObject symlink(ThreadContext context, IRubyObject recv, IRubyObject from, IRubyObject to) {
Ruby runtime = context.getRuntime();
RubyString fromStr = RubyString.stringValue(from);
RubyString toStr = RubyString.stringValue(to);
try {
if (runtime.getPosix().symlink(
fromStr.toString(), toStr.toString()) == -1) {
// FIXME: When we get JNA3 we need to properly write this to errno.
throw runtime.newErrnoEEXISTError("File exists - "
+ fromStr + " or " + toStr);
}
} catch (java.lang.UnsatisfiedLinkError ule) {
throw runtime.newNotImplementedError("symlink() function is unimplemented on this machine");
}
return runtime.newFixnum(0);
}
@JRubyMethod(required = 1, meta = true)
public static IRubyObject readlink(ThreadContext context, IRubyObject recv, IRubyObject path) {
Ruby runtime = context.getRuntime();
try {
String realPath = runtime.getPosix().readlink(path.toString());
if (!RubyFileTest.exist_p(recv, path).isTrue()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + path);
}
if (!RubyFileTest.symlink_p(recv, path).isTrue()) {
throw runtime.newErrnoEINVALError("invalid argument - " + path);
}
if (realPath == null) {
//FIXME: When we get JNA3 we need to properly write this to errno.
}
return runtime.newString(realPath);
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
}
}
// Can we produce IOError which bypasses a close?
@JRubyMethod(required = 2, meta = true)
public static IRubyObject truncate(ThreadContext context, IRubyObject recv, IRubyObject arg1, IRubyObject arg2) {
Ruby runtime = context.getRuntime();
RubyString filename = arg1.convertToString(); // TODO: SafeStringValue here
RubyInteger newLength = arg2.convertToInteger();
if (!new File(runtime.getCurrentDirectory(), filename.getByteList().toString()).exists()) {
throw runtime.newErrnoENOENTError(
"No such file or directory - " + filename.getByteList().toString());
}
if (newLength.getLongValue() < 0) {
throw runtime.newErrnoEINVALError("invalid argument: " + filename);
}
IRubyObject[] args = new IRubyObject[] { filename, runtime.newString("r+") };
RubyFile file = (RubyFile) open(context, recv, args, Block.NULL_BLOCK);
file.truncate(context, newLength);
file.close();
return RubyFixnum.zero(runtime);
}
@JRubyMethod(meta = true, optional = 1)
public static IRubyObject umask(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int oldMask = 0;
if (args.length == 0) {
oldMask = runtime.getPosix().umask(0);
runtime.getPosix().umask(oldMask);
} else if (args.length == 1) {
oldMask = runtime.getPosix().umask((int) args[0].convertToInteger().getLongValue());
} else {
runtime.newArgumentError("wrong number of arguments");
}
return runtime.newFixnum(oldMask);
}
/**
* This method does NOT set atime, only mtime, since Java doesn't support anything else.
*/
@JRubyMethod(required = 2, rest = true, meta = true)
public static IRubyObject utime(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
// Ignore access_time argument since Java does not support it.
long mtime;
if (args[1] instanceof RubyTime) {
mtime = ((RubyTime) args[1]).getJavaDate().getTime();
} else if (args[1] instanceof RubyNumeric) {
mtime = RubyNumeric.num2long(args[1]);
} else if (args[1] == runtime.getNil()) {
mtime = System.currentTimeMillis();
} else {
RubyTime time = (RubyTime) TypeConverter.convertToType(args[1], runtime.getTime(), MethodIndex.NO_INDEX,"to_time", true);
mtime = time.getJavaDate().getTime();
}
for (int i = 2, j = args.length; i < j; i++) {
RubyString filename = RubyString.stringValue(args[i]);
runtime.checkSafeString(filename);
JRubyFile fileToTouch = JRubyFile.create(runtime.getCurrentDirectory(),filename.toString());
if (!fileToTouch.exists()) {
throw runtime.newErrnoENOENTError(" No such file or directory - \"" + filename + "\"");
}
fileToTouch.setLastModified(mtime);
}
return runtime.newFixnum(args.length - 2);
}
@JRubyMethod(name = {"unlink", "delete"}, rest = true, meta = true)
public static IRubyObject unlink(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
for (int i = 0; i < args.length; i++) {
RubyString filename = RubyString.stringValue(args[i]);
runtime.checkSafeString(filename);
JRubyFile lToDelete = JRubyFile.create(runtime.getCurrentDirectory(),filename.toString());
boolean isSymlink = RubyFileTest.symlink_p(recv, filename).isTrue();
// Broken symlinks considered by exists() as non-existing,
// so we need to check for symlinks explicitly.
if (!lToDelete.exists() && !isSymlink) {
throw runtime.newErrnoENOENTError(" No such file or directory - \"" + filename + "\"");
}
if (!lToDelete.delete()) {
throw runtime.newErrnoEACCESError("Permission denied - \"" + filename + "\"");
}
}
return runtime.newFixnum(args.length);
}
// Fast path since JNA stat is about 10x slower than this
private static IRubyObject getLastModified(Ruby runtime, String path) {
JRubyFile file = JRubyFile.create(runtime.getCurrentDirectory(), path);
if (!file.exists()) {
throw runtime.newErrnoENOENTError("No such file or directory - " + path);
}
return runtime.newTime(file.lastModified());
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Joey Gibson <joey@joeygibson.com>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.FileDescriptor;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.ext.posix.FileStat;
import org.jruby.ext.posix.util.Platform;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.JRubyFile;
/**
* Implements File::Stat
*/
@JRubyClass(name="File::Stat", include="Comparable")
public class RubyFileStat extends RubyObject {
private static final long serialVersionUID = 1L;
private JRubyFile file;
private FileStat stat;
private static ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyFileStat(runtime, klass);
}
};
public static RubyClass createFileStatClass(Ruby runtime) {
// TODO: NOT_ALLOCATABLE_ALLOCATOR is probably ok here. Confirm. JRUBY-415
final RubyClass fileStatClass = runtime.getFile().defineClassUnder("Stat",runtime.getObject(), ALLOCATOR);
runtime.setFileStat(fileStatClass);
fileStatClass.includeModule(runtime.fastGetModule("Comparable"));
fileStatClass.defineAnnotatedMethods(RubyFileStat.class);
return fileStatClass;
}
protected RubyFileStat(Ruby runtime, RubyClass clazz) {
super(runtime, clazz);
}
public static RubyFileStat newFileStat(Ruby runtime, String filename, boolean lstat) {
RubyFileStat stat = new RubyFileStat(runtime, runtime.getFileStat());
stat.setup(filename, lstat);
return stat;
}
public static RubyFileStat newFileStat(Ruby runtime, FileDescriptor descriptor) {
RubyFileStat stat = new RubyFileStat(runtime, runtime.getFileStat());
stat.setup(descriptor);
return stat;
}
private void setup(FileDescriptor descriptor) {
stat = getRuntime().getPosix().fstat(descriptor);
}
private void setup(String filename, boolean lstat) {
if (Platform.IS_WINDOWS && filename.length() == 2
&& filename.charAt(1) == ':' && Character.isLetter(filename.charAt(0))) {
filename += "/";
}
file = JRubyFile.create(getRuntime().getCurrentDirectory(), filename);
if (lstat) {
stat = getRuntime().getPosix().lstat(file.getAbsolutePath());
} else {
stat = getRuntime().getPosix().stat(file.getAbsolutePath());
}
}
@JRubyMethod(name = "initialize", required = 1, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject fname, Block unusedBlock) {
setup(fname.convertToString().toString(), false);
return this;
}
@JRubyMethod(name = "atime")
public IRubyObject atime() {
return getRuntime().newTime(stat.atime() * 1000);
}
@JRubyMethod(name = "blksize")
public RubyFixnum blksize() {
return getRuntime().newFixnum(stat.blockSize());
}
@JRubyMethod(name = "blockdev?")
public IRubyObject blockdev_p() {
return getRuntime().newBoolean(stat.isBlockDev());
}
@JRubyMethod(name = "blocks")
public IRubyObject blocks() {
return getRuntime().newFixnum(stat.blocks());
}
@JRubyMethod(name = "chardev?")
public IRubyObject chardev_p() {
return getRuntime().newBoolean(stat.isCharDev());
}
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject cmp(IRubyObject other) {
if (!(other instanceof RubyFileStat)) getRuntime().getNil();
long time1 = stat.mtime();
long time2 = ((RubyFileStat) other).stat.mtime();
if (time1 == time2) {
return getRuntime().newFixnum(0);
} else if (time1 < time2) {
return getRuntime().newFixnum(-1);
}
return getRuntime().newFixnum(1);
}
@JRubyMethod(name = "ctime")
public IRubyObject ctime() {
return getRuntime().newTime(stat.ctime() * 1000);
}
@JRubyMethod(name = "dev")
public IRubyObject dev() {
return getRuntime().newFixnum(stat.dev());
}
@JRubyMethod(name = "dev_major")
public IRubyObject devMajor() {
return getRuntime().newFixnum(stat.major(stat.dev()));
}
@JRubyMethod(name = "dev_minor")
public IRubyObject devMinor() {
return getRuntime().newFixnum(stat.minor(stat.dev()));
}
@JRubyMethod(name = "directory?")
public RubyBoolean directory_p() {
return getRuntime().newBoolean(stat.isDirectory());
}
@JRubyMethod(name = "executable?")
public IRubyObject executable_p() {
return getRuntime().newBoolean(stat.isExecutable());
}
@JRubyMethod(name = "executable_real?")
public IRubyObject executableReal_p() {
return getRuntime().newBoolean(stat.isExecutableReal());
}
@JRubyMethod(name = "file?")
public RubyBoolean file_p() {
return getRuntime().newBoolean(stat.isFile());
}
@JRubyMethod(name = "ftype")
public RubyString ftype() {
return getRuntime().newString(stat.ftype());
}
@JRubyMethod(name = "gid")
public IRubyObject gid() {
return getRuntime().newFixnum(stat.gid());
}
@JRubyMethod(name = "grpowned?")
public IRubyObject group_owned_p() {
return getRuntime().newBoolean(stat.isGroupOwned());
}
@JRubyMethod(name = "initialize_copy", required = 1)
public IRubyObject initialize_copy(IRubyObject original) {
if (!(original instanceof RubyFileStat)) {
throw getRuntime().newTypeError("wrong argument class");
}
RubyFileStat originalFileStat = (RubyFileStat) original;
file = originalFileStat.file;
stat = originalFileStat.stat;
return this;
}
@JRubyMethod(name = "ino")
public IRubyObject ino() {
return getRuntime().newFixnum(stat.ino());
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
StringBuilder buf = new StringBuilder("#<");
buf.append(getMetaClass().getRealClass().getName());
buf.append(" ");
// FIXME: Obvious issue that not all platforms can display all attributes. Ugly hacks.
// Using generic posix library makes pushing inspect behavior into specific system impls
// rather painful.
try { buf.append("dev=0x").append(Long.toHexString(stat.dev())).append(", "); } catch (Exception e) {}
try { buf.append("ino=").append(stat.ino()).append(", "); } catch (Exception e) {}
buf.append("mode=0").append(Integer.toOctalString(stat.mode())).append(", ");
try { buf.append("nlink=").append(stat.nlink()).append(", "); } catch (Exception e) {}
try { buf.append("uid=").append(stat.uid()).append(", "); } catch (Exception e) {}
try { buf.append("gid=").append(stat.gid()).append(", "); } catch (Exception e) {}
try { buf.append("rdev=0x").append(Long.toHexString(stat.rdev())).append(", "); } catch (Exception e) {}
buf.append("size=").append(stat.st_size()).append(", ");
try { buf.append("blksize=").append(stat.blockSize()).append(", "); } catch (Exception e) {}
try { buf.append("blocks=").append(stat.blocks()).append(", "); } catch (Exception e) {}
buf.append("atime=").append(atime()).append(", ");
buf.append("mtime=").append(mtime()).append(", ");
buf.append("ctime=").append(ctime());
buf.append(">");
return getRuntime().newString(buf.toString());
}
@JRubyMethod(name = "uid")
public IRubyObject uid() {
return getRuntime().newFixnum(stat.uid());
}
@JRubyMethod(name = "mode")
public IRubyObject mode() {
return getRuntime().newFixnum(stat.mode());
}
@JRubyMethod(name = "mtime")
public IRubyObject mtime() {
return getRuntime().newTime(stat.mtime() * 1000);
}
public IRubyObject mtimeEquals(IRubyObject other) {
return getRuntime().newBoolean(stat.mtime() == newFileStat(getRuntime(), other.convertToString().toString(), false).stat.mtime());
}
public IRubyObject mtimeGreaterThan(IRubyObject other) {
return getRuntime().newBoolean(stat.mtime() > newFileStat(getRuntime(), other.convertToString().toString(), false).stat.mtime());
}
public IRubyObject mtimeLessThan(IRubyObject other) {
return getRuntime().newBoolean(stat.mtime() < newFileStat(getRuntime(), other.convertToString().toString(), false).stat.mtime());
}
@JRubyMethod(name = "nlink")
public IRubyObject nlink() {
return getRuntime().newFixnum(stat.nlink());
}
@JRubyMethod(name = "owned?")
public IRubyObject owned_p() {
return getRuntime().newBoolean(stat.isOwned());
}
@JRubyMethod(name = "pipe?")
public IRubyObject pipe_p() {
return getRuntime().newBoolean(stat.isNamedPipe());
}
@JRubyMethod(name = "rdev")
public IRubyObject rdev() {
return getRuntime().newFixnum(stat.rdev());
}
@JRubyMethod(name = "rdev_major")
public IRubyObject rdevMajor() {
return getRuntime().newFixnum(stat.major(stat.rdev()));
}
@JRubyMethod(name = "rdev_minor")
public IRubyObject rdevMinor() {
return getRuntime().newFixnum(stat.minor(stat.rdev()));
}
@JRubyMethod(name = "readable?")
public IRubyObject readable_p() {
return getRuntime().newBoolean(stat.isReadable());
}
@JRubyMethod(name = "readable_real?")
public IRubyObject readableReal_p() {
return getRuntime().newBoolean(stat.isReadableReal());
}
@JRubyMethod(name = "setgid?")
public IRubyObject setgid_p() {
return getRuntime().newBoolean(stat.isSetgid());
}
@JRubyMethod(name = "setuid?")
public IRubyObject setuid_p() {
return getRuntime().newBoolean(stat.isSetuid());
}
@JRubyMethod(name = "size")
public IRubyObject size() {
return getRuntime().newFixnum(stat.st_size());
}
@JRubyMethod(name = "size?")
public IRubyObject size_p() {
long size = stat.st_size();
if (size == 0) return getRuntime().getNil();
return getRuntime().newFixnum(size);
}
@JRubyMethod(name = "socket?")
public IRubyObject socket_p() {
return getRuntime().newBoolean(stat.isSocket());
}
@JRubyMethod(name = "sticky?")
public IRubyObject sticky_p() {
return getRuntime().newBoolean(stat.isSticky());
}
@JRubyMethod(name = "symlink?")
public IRubyObject symlink_p() {
return getRuntime().newBoolean(stat.isSymlink());
}
@JRubyMethod(name = "writable?")
public IRubyObject writable_p() {
return getRuntime().newBoolean(stat.isWritable());
}
@JRubyMethod(name = "writable_real?")
public IRubyObject writableReal_p() {
return getRuntime().newBoolean(stat.isWritableReal());
}
@JRubyMethod(name = "zero?")
public IRubyObject zero_p() {
return getRuntime().newBoolean(stat.isEmpty());
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.JRubyFile;
@JRubyModule(name="FileTest")
public class RubyFileTest {
public static RubyModule createFileTestModule(Ruby runtime) {
RubyModule fileTestModule = runtime.defineModule("FileTest");
runtime.setFileTest(fileTestModule);
fileTestModule.defineAnnotatedMethods(RubyFileTest.class);
return fileTestModule;
}
@JRubyMethod(name = "blockdev?", required = 1, module = true)
public static IRubyObject blockdev_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isBlockDev());
}
@JRubyMethod(name = "chardev?", required = 1, module = true)
public static IRubyObject chardev_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isCharDev());
}
@JRubyMethod(name = "directory?", required = 1, module = true)
public static IRubyObject directory_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isDirectory());
}
@JRubyMethod(name = "executable?", required = 1, module = true)
public static IRubyObject executable_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isExecutable());
}
@JRubyMethod(name = "executable_real?", required = 1, module = true)
public static IRubyObject executable_real_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isExecutableReal());
}
@JRubyMethod(name = {"exist?", "exists?"}, required = 1, module = true)
public static IRubyObject exist_p(IRubyObject recv, IRubyObject filename) {
if (Ruby.isSecurityRestricted()) {
return recv.getRuntime().getFalse();
}
if(filename.convertToString().toString().startsWith("file:")) {
String file = filename.convertToString().toString().substring(5);
int bang = file.indexOf('!');
if (bang == -1 || bang == file.length() - 1) {
return recv.getRuntime().getFalse();
}
String jar = file.substring(0, bang);
String after = file.substring(bang + 2);
try {
java.util.jar.JarFile jf = new java.util.jar.JarFile(jar);
if(jf.getJarEntry(after) != null) {
return recv.getRuntime().getTrue();
} else {
return recv.getRuntime().getFalse();
}
} catch(Exception e) {
return recv.getRuntime().getFalse();
}
}
return recv.getRuntime().newBoolean(file(filename).exists());
}
@JRubyMethod(name = "file?", required = 1, module = true)
public static RubyBoolean file_p(IRubyObject recv, IRubyObject filename) {
JRubyFile file = file(filename);
return filename.getRuntime().newBoolean(file.exists() && file.isFile());
}
@JRubyMethod(name = "grpowned?", required = 1, module = true)
public static IRubyObject grpowned_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isGroupOwned());
}
@JRubyMethod(name = "identical?", required = 2, module = true)
public static IRubyObject identical_p(IRubyObject recv, IRubyObject filename1, IRubyObject filename2) {
Ruby runtime = recv.getRuntime();
JRubyFile file1 = file(filename1);
JRubyFile file2 = file(filename2);
return runtime.newBoolean(file1.exists() && file2.exists() &&
runtime.getPosix().stat(file1.getAbsolutePath()).isIdentical(runtime.getPosix().stat(file2.getAbsolutePath())));
}
@JRubyMethod(name = "owned?", required = 1, module = true)
public static IRubyObject owned_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isOwned());
}
@JRubyMethod(name = "pipe?", required = 1, module = true)
public static IRubyObject pipe_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isNamedPipe());
}
// We use file test since it is faster than a stat; also euid == uid in Java always
@JRubyMethod(name = {"readable?", "readable_real?"}, required = 1, module = true)
public static IRubyObject readable_p(IRubyObject recv, IRubyObject filename) {
JRubyFile file = file(filename);
return recv.getRuntime().newBoolean(file.exists() && file.canRead());
}
// Not exposed by filetest, but so similiar in nature that it is stored here
public static IRubyObject rowned_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isROwned());
}
@JRubyMethod(name = "setgid?", required = 1, module = true)
public static IRubyObject setgid_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isSetgid());
}
@JRubyMethod(name = "setuid?", required = 1, module = true)
public static IRubyObject setuid_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isSetuid());
}
@JRubyMethod(name = "size", required = 1, module = true)
public static IRubyObject size(IRubyObject recv, IRubyObject filename) {
JRubyFile file = file(filename);
if (!file.exists()) noFileError(filename);
return recv.getRuntime().newFixnum(file.length());
}
@JRubyMethod(name = "size?", required = 1, module = true)
public static IRubyObject size_p(IRubyObject recv, IRubyObject filename) {
JRubyFile file = file(filename);
if (!file.exists()) {
return recv.getRuntime().getNil();
}
long length = file.length();
if (length > 0) {
return recv.getRuntime().newFixnum(length);
} else {
return recv.getRuntime().getNil();
}
}
@JRubyMethod(name = "socket?", required = 1, module = true)
public static IRubyObject socket_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isSocket());
}
@JRubyMethod(name = "sticky?", required = 1, module = true)
public static IRubyObject sticky_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
return runtime.newBoolean(file.exists() && runtime.getPosix().stat(file.getAbsolutePath()).isSticky());
}
@JRubyMethod(name = "symlink?", required = 1, module = true)
public static RubyBoolean symlink_p(IRubyObject recv, IRubyObject filename) {
Ruby runtime = recv.getRuntime();
JRubyFile file = file(filename);
try {
// Note: We can't use file.exists() to check whether the symlink
// exists or not, because that method returns false for existing
// but broken symlink. So, we try without the existence check,
// but in the try-catch block.
// MRI behavior: symlink? on broken symlink should return true.
return runtime.newBoolean(runtime.getPosix().lstat(file.getAbsolutePath()).isSymlink());
} catch (RaiseException re) {
return runtime.getFalse();
}
}
// We do both writable and writable_real through the same method because
// in our java process effective and real userid will always be the same.
@JRubyMethod(name = {"writable?", "writable_real?"}, required = 1, module = true)
public static RubyBoolean writable_p(IRubyObject recv, IRubyObject filename) {
return filename.getRuntime().newBoolean(file(filename).canWrite());
}
@JRubyMethod(name = "zero?", required = 1, module = true)
public static RubyBoolean zero_p(IRubyObject recv, IRubyObject filename) {
JRubyFile file = file(filename);
return filename.getRuntime().newBoolean(file.exists() && file.length() == 0L);
}
private static JRubyFile file(IRubyObject path) {
String filename = path.convertToString().toString();
return JRubyFile.create(path.getRuntime().getCurrentDirectory(), filename);
}
private static void noFileError(IRubyObject filename) {
throw filename.getRuntime().newErrnoENOENTError("No such file or directory - " +
filename.convertToString());
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 David Corbin <dcorbin@users.sourceforge.net>
* Copyright (C) 2006 Antti Karanta <antti.karanta@napa.fi>
* Copyright (C) 2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.java.MiniJava;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.Convert;
import org.jruby.util.Numeric;
import org.jruby.util.TypeCoercer;
/**
* Implementation of the Fixnum class.
*/
@JRubyClass(name="Fixnum", parent="Integer", include="Precision")
public class RubyFixnum extends RubyInteger {
public static RubyClass createFixnumClass(Ruby runtime) {
RubyClass fixnum = runtime.defineClass("Fixnum", runtime.getInteger(),
ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setFixnum(fixnum);
fixnum.index = ClassIndex.FIXNUM;
fixnum.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyFixnum;
}
};
fixnum.includeModule(runtime.getPrecision());
fixnum.defineAnnotatedMethods(RubyFixnum.class);
for (int i = 0; i < runtime.fixnumCache.length; i++) {
runtime.fixnumCache[i] = new RubyFixnum(runtime, fixnum, i - 128);
}
return fixnum;
}
private final long value;
private static final int BIT_SIZE = 64;
public static final long SIGN_BIT = (1L << (BIT_SIZE - 1));
public static final long MAX = (1L<<(BIT_SIZE - 1)) - 1;
public static final long MIN = -1 * MAX - 1;
public static final long MAX_MARSHAL_FIXNUM = (1L << 30) - 1; // 0x3fff_ffff
public static final long MIN_MARSHAL_FIXNUM = - (1L << 30); // -0x4000_0000
private static IRubyObject fixCoerce(IRubyObject x) {
do {
x = x.convertToInteger();
} while (!(x instanceof RubyFixnum) && !(x instanceof RubyBignum));
return x;
}
public RubyFixnum(Ruby runtime) {
this(runtime, 0);
}
public RubyFixnum(Ruby runtime, long value) {
super(runtime, runtime.getFixnum(), false);
this.value = value;
}
private RubyFixnum(Ruby runtime, RubyClass klazz, long value) {
super(runtime, klazz, false);
this.value = value;
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.FIXNUM;
}
/**
* short circuit for Fixnum key comparison
*/
@Override
public final boolean eql(IRubyObject other) {
return other instanceof RubyFixnum && value == ((RubyFixnum)other).value;
}
@Override
public boolean isImmediate() {
return true;
}
@Override
public RubyClass getSingletonClass() {
throw getRuntime().newTypeError("can't define singleton");
}
@Override
public Class<?> getJavaClass() {
// this precision-guessing needs to be thought out more, since in the
// case of coercing to Object we generally want to get the same type
// always
// if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
// return byte.class;
// } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
// return short.class;
// } else if (value >= Character.MIN_VALUE && value <= Character.MAX_VALUE) {
// return char.class;
// } else if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
// return int.class;
// }
return long.class;
}
@Override
public double getDoubleValue() {
return value;
}
@Override
public long getLongValue() {
return value;
}
private static final int CACHE_OFFSET = 128;
public static RubyFixnum newFixnum(Ruby runtime, long value) {
if (isInCacheRange(value)) {
return runtime.fixnumCache[(int) value + CACHE_OFFSET];
}
return new RubyFixnum(runtime, value);
}
private static boolean isInCacheRange(long value) {
return value <= 127 && value >= -128;
}
public RubyFixnum newFixnum(long newValue) {
return newFixnum(getRuntime(), newValue);
}
public static RubyFixnum zero(Ruby runtime) {
return runtime.fixnumCache[CACHE_OFFSET];
}
public static RubyFixnum one(Ruby runtime) {
return runtime.fixnumCache[CACHE_OFFSET + 1];
}
public static RubyFixnum two(Ruby runtime) {
return runtime.fixnumCache[CACHE_OFFSET + 2];
}
public static RubyFixnum three(Ruby runtime) {
return runtime.fixnumCache[CACHE_OFFSET + 3];
}
public static RubyFixnum four(Ruby runtime) {
return runtime.fixnumCache[CACHE_OFFSET + 4];
}
public static RubyFixnum five(Ruby runtime) {
return runtime.fixnumCache[CACHE_OFFSET + 5];
}
public static RubyFixnum minus_one(Ruby runtime) {
return runtime.fixnumCache[CACHE_OFFSET - 1];
}
@Override
public RubyFixnum hash() {
return newFixnum(hashCode());
}
@Override
public final int hashCode() {
return (int)(value ^ value >>> 32);
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof RubyFixnum) {
RubyFixnum num = (RubyFixnum)other;
if (num.value == value) {
return true;
}
}
return false;
}
/* ================
* Instance Methods
* ================
*/
/** fix_to_s
*
*/
public RubyString to_s(IRubyObject[] args) {
switch (args.length) {
case 0: return to_s();
case 1: return to_s(args[0]);
default: throw getRuntime().newArgumentError(args.length, 1);
}
}
@JRubyMethod
@Override
public RubyString to_s() {
int base = 10;
return getRuntime().newString(Convert.longToByteList(value, base));
}
@JRubyMethod
public RubyString to_s(IRubyObject arg0) {
int base = num2int(arg0);
if (base < 2 || base > 36) {
throw getRuntime().newArgumentError("illegal radix " + base);
}
return getRuntime().newString(Convert.longToByteList(value, base));
}
/** fix_id2name
*
*/
@JRubyMethod
public IRubyObject id2name() {
RubySymbol symbol = RubySymbol.getSymbolLong(getRuntime(), value);
if (symbol != null) return getRuntime().newString(symbol.asJavaString());
return getRuntime().getNil();
}
/** fix_to_sym
*
*/
@JRubyMethod
public IRubyObject to_sym() {
RubySymbol symbol = RubySymbol.getSymbolLong(getRuntime(), value);
return symbol != null ? symbol : getRuntime().getNil();
}
/** fix_uminus
*
*/
@JRubyMethod(name = "-@")
public IRubyObject op_uminus() {
if (value == MIN) { // a gotcha
return RubyBignum.newBignum(getRuntime(), BigInteger.valueOf(value).negate());
}
return RubyFixnum.newFixnum(getRuntime(), -value);
}
/** fix_plus
*
*/
@JRubyMethod(name = "+")
public IRubyObject op_plus(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return addFixnum(context, (RubyFixnum)other);
}
return addOther(context, other);
}
private IRubyObject addFixnum(ThreadContext context, RubyFixnum other) {
long otherValue = other.value;
long result = value + otherValue;
if (additionOverflowed(value, otherValue, result)) {
return addAsBignum(context, other);
}
return newFixnum(context.getRuntime(), result);
}
private static boolean additionOverflowed(long original, long other, long result) {
return (~(original ^ other) & (original ^ result) & SIGN_BIT) != 0;
}
private static boolean subtractionOverflowed(long original, long other, long result) {
return (~(original ^ ~other) & (original ^ result) & SIGN_BIT) != 0;
}
private IRubyObject addAsBignum(ThreadContext context, RubyFixnum other) {
return RubyBignum.newBignum(context.getRuntime(), value).op_plus(context, other);
}
private IRubyObject addOther(ThreadContext context, IRubyObject other) {
if (other instanceof RubyBignum) {
return ((RubyBignum) other).op_plus(context, this);
}
if (other instanceof RubyFloat) {
return context.getRuntime().newFloat((double) value + ((RubyFloat) other).getDoubleValue());
}
return coerceBin(context, "+", other);
}
/** fix_minus
*
*/
@JRubyMethod(name = "-")
public IRubyObject op_minus(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return subtractFixnum(context, (RubyFixnum)other);
}
return subtractOther(context, other);
}
private IRubyObject subtractFixnum(ThreadContext context, RubyFixnum other) {
long otherValue = other.value;
long result = value - otherValue;
if (subtractionOverflowed(value, otherValue, result)) {
return subtractAsBignum(context, other);
}
return newFixnum(context.getRuntime(), result);
}
private IRubyObject subtractAsBignum(ThreadContext context, RubyFixnum other) {
return RubyBignum.newBignum(context.getRuntime(), value).op_minus(context, other);
}
private IRubyObject subtractOther(ThreadContext context, IRubyObject other) {
if (other instanceof RubyBignum) {
return RubyBignum.newBignum(context.getRuntime(), value).op_minus(context, other);
} else if (other instanceof RubyFloat) {
return context.getRuntime().newFloat((double) value - ((RubyFloat) other).getDoubleValue());
}
return coerceBin(context, "-", other);
}
/** fix_mul
*
*/
@JRubyMethod(name = "*")
public IRubyObject op_mul(ThreadContext context, IRubyObject other) {
Ruby runtime = context.getRuntime();
if (other instanceof RubyFixnum) {
long otherValue = ((RubyFixnum) other).value;
if (value == 0) {
return RubyFixnum.zero(runtime);
}
long result = value * otherValue;
if (result / value != otherValue) {
return RubyBignum.newBignum(runtime, value).op_mul(context, other);
}
return newFixnum(runtime, result);
} else if (other instanceof RubyBignum) {
return ((RubyBignum) other).op_mul(context, this);
} else if (other instanceof RubyFloat) {
return runtime.newFloat((double) value * ((RubyFloat) other).getDoubleValue());
}
return coerceBin(context, "*", other);
}
/** fix_div
* here is terrible MRI gotcha:
* 1.div 3.0 -> 0
* 1 / 3.0 -> 0.3333333333333333
*
* MRI is also able to do it in one place by looking at current frame in rb_num_coerce_bin:
* rb_funcall(x, ruby_frame->orig_func, 1, y);
*
* also note that RubyFloat doesn't override Numeric.div
*/
@JRubyMethod(name = "div")
public IRubyObject div_div(ThreadContext context, IRubyObject other) {
return idiv(context, other, "div");
}
@JRubyMethod(name = "/")
public IRubyObject op_div(ThreadContext context, IRubyObject other) {
return idiv(context, other, "/");
}
@JRubyMethod(name = {"odd?"})
public RubyBoolean odd_p() {
if(value%2 != 0) {
return getRuntime().getTrue();
}
return getRuntime().getFalse();
}
@JRubyMethod(name = {"even?"})
public RubyBoolean even_p() {
if(value%2 == 0) {
return getRuntime().getTrue();
}
return getRuntime().getFalse();
}
@JRubyMethod
public IRubyObject pred() {
return getRuntime().newFixnum(value-1);
}
public IRubyObject idiv(ThreadContext context, IRubyObject other, String method) {
if (other instanceof RubyFixnum) {
long x = value;
long y = ((RubyFixnum) other).value;
if (y == 0) {
throw context.getRuntime().newZeroDivisionError();
}
long div = x / y;
long mod = x % y;
if (mod < 0 && y > 0 || mod > 0 && y < 0) {
div -= 1;
}
return context.getRuntime().newFixnum(div);
}
return coerceBin(context, method, other);
}
/** fix_mod
*
*/
@JRubyMethod(name = {"%", "modulo"})
public IRubyObject op_mod(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
// Java / and % are not the same as ruby
long x = value;
long y = ((RubyFixnum) other).value;
if (y == 0) {
throw context.getRuntime().newZeroDivisionError();
}
long mod = x % y;
if (mod < 0 && y > 0 || mod > 0 && y < 0) {
mod += y;
}
return context.getRuntime().newFixnum(mod);
}
return coerceBin(context, "%", other);
}
/** fix_divmod
*
*/
@JRubyMethod
@Override
public IRubyObject divmod(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
long x = value;
long y = ((RubyFixnum) other).value;
final Ruby runtime = context.getRuntime();
if (y == 0) {
throw runtime.newZeroDivisionError();
}
long div = x / y;
long mod = x % y;
if (mod < 0 && y > 0 || mod > 0 && y < 0) {
div -= 1;
mod += y;
}
IRubyObject fixDiv = RubyFixnum.newFixnum(runtime, div);
IRubyObject fixMod = RubyFixnum.newFixnum(runtime, mod);
return RubyArray.newArray(runtime, fixDiv, fixMod);
}
return coerceBin(context, "divmod", other);
}
/** fix_quo
*
*/
@JRubyMethod(name = "quo", compat = CompatVersion.RUBY1_8)
public IRubyObject quo(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return RubyFloat.newFloat(context.getRuntime(), (double) value / (double) ((RubyFixnum) other).value);
}
return coerceBin(context, "quo", other);
}
/** fix_pow
*
*/
@JRubyMethod(name = "**")
public IRubyObject op_pow(ThreadContext context, IRubyObject other) {
if(other instanceof RubyFixnum) {
long b = ((RubyFixnum) other).value;
if (b == 0) {
return RubyFixnum.one(context.getRuntime());
}
if (b == 1) {
return this;
}
if (b > 0) {
return RubyBignum.newBignum(context.getRuntime(), value).op_pow(context, other);
}
return RubyFloat.newFloat(context.getRuntime(), Math.pow(value, b));
} else if (other instanceof RubyFloat) {
return RubyFloat.newFloat(context.getRuntime(), Math.pow(value, ((RubyFloat) other)
.getDoubleValue()));
}
return coerceBin(context, "**", other);
}
/** fix_pow
*
*/
@JRubyMethod(name = "**", compat = CompatVersion.RUBY1_9)
public IRubyObject op_pow_19(ThreadContext context, IRubyObject other) {
Ruby runtime = context.getRuntime();
long a = value;
if (other instanceof RubyFixnum) {
long b = ((RubyFixnum) other).value;
if (b < 0) {
return RubyRational.newRationalRaw(context.getRuntime(), this).callMethod(context, "**", other);
}
if (b == 0) return RubyFixnum.one(runtime);
if (b == 1) return this;
if (a == 0) {
return b > 0 ? RubyFixnum.zero(runtime) : RubyNumeric.dbl2num(runtime, 1.0 / 0.0);
}
if (a == 1) return RubyFixnum.one(runtime);
if (a == -1) {
return b % 2 == 0 ? RubyFixnum.one(runtime) : RubyFixnum.minus_one(runtime);
}
return Numeric.int_pow(context, a, b);
} else if (other instanceof RubyBignum) {
if (other.callMethod(context, "<", RubyFixnum.zero(runtime)).isTrue()) {
return RubyRational.newRationalRaw(runtime, this).callMethod(context, "**", other);
}
if (a == 0) return RubyFixnum.zero(runtime);
if (a == 1) return RubyFixnum.one(runtime);
if (a == -1) {
return RubyInteger.even_p(context, other).isTrue() ? RubyFixnum.one(runtime) : RubyFixnum.minus_one(runtime);
}
RubyBignum.newBignum(runtime, RubyBignum.fix2big(this)).op_pow(context, other);
} else if (other instanceof RubyFloat) {
return RubyFloat.newFloat(context.getRuntime(), Math.pow(a, ((RubyFloat) other).getDoubleValue()));
}
return coerceBin(context, "**", other);
}
/** fix_abs
*
*/
@JRubyMethod
public IRubyObject abs() {
if (value < 0) {
// A gotcha for Long.MIN_VALUE: value = -value
if (value == Long.MIN_VALUE) {
return RubyBignum.newBignum(
getRuntime(), BigInteger.valueOf(value).negate());
}
return RubyFixnum.newFixnum(getRuntime(), -value);
}
return this;
}
/** fix_equal
*
*/
@JRubyMethod(name = "==")
@Override
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return RubyBoolean.newBoolean(context.getRuntime(), value == ((RubyFixnum) other).value);
}
return super.op_num_equal(context, other);
}
/** fix_cmp
*
*/
@JRubyMethod(name = "<=>")
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return compareFixnum(context, (RubyFixnum)other);
}
return coerceCmp(context, "<=>", other);
}
private IRubyObject compareFixnum(ThreadContext context, RubyFixnum other) {
long otherValue = ((RubyFixnum) other).value;
if (value == otherValue) {
return RubyFixnum.zero(context.getRuntime());
}
if (value > otherValue) {
return RubyFixnum.one(context.getRuntime());
}
return RubyFixnum.minus_one(context.getRuntime());
}
/** fix_gt
*
*/
@JRubyMethod(name = ">")
public IRubyObject op_gt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return RubyBoolean.newBoolean(context.getRuntime(), value > ((RubyFixnum) other).value);
}
return coerceRelOp(context, ">", other);
}
/** fix_ge
*
*/
@JRubyMethod(name = ">=")
public IRubyObject op_ge(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return RubyBoolean.newBoolean(context.getRuntime(), value >= ((RubyFixnum) other).value);
}
return coerceRelOp(context, ">=", other);
}
/** fix_lt
*
*/
@JRubyMethod(name = "<")
public IRubyObject op_lt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return RubyBoolean.newBoolean(context.getRuntime(), value < ((RubyFixnum) other).value);
}
return coerceRelOp(context, "<", other);
}
/** fix_le
*
*/
@JRubyMethod(name = "<=")
public IRubyObject op_le(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum) {
return RubyBoolean.newBoolean(context.getRuntime(), value <= ((RubyFixnum) other).value);
}
return coerceRelOp(context, "<=", other);
}
/** fix_rev
*
*/
@JRubyMethod(name = "~")
public IRubyObject op_neg() {
return newFixnum(~value);
}
/** fix_and
*
*/
@JRubyMethod(name = "&")
public IRubyObject op_and(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum || (other = fixCoerce(other)) instanceof RubyFixnum) {
return newFixnum(context.getRuntime(), value & ((RubyFixnum) other).value);
}
return ((RubyBignum) other).op_and(context, this);
}
/** fix_or
*
*/
@JRubyMethod(name = "|")
public IRubyObject op_or(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum || (other = fixCoerce(other)) instanceof RubyFixnum) {
return newFixnum(context.getRuntime(), value | ((RubyFixnum) other).value);
}
return ((RubyBignum) other).op_or(context, this);
}
/** fix_xor
*
*/
@JRubyMethod(name = "^")
public IRubyObject op_xor(ThreadContext context, IRubyObject other) {
if (other instanceof RubyFixnum || (other = fixCoerce(other)) instanceof RubyFixnum) {
return newFixnum(context.getRuntime(), value ^ ((RubyFixnum) other).value);
}
return ((RubyBignum) other).op_xor(context, this);
}
/** fix_aref
*
*/
@JRubyMethod(name = "[]")
public IRubyObject op_aref(IRubyObject other) {
if(!(other instanceof RubyFixnum) && !((other = fixCoerce(other)) instanceof RubyFixnum)) {
RubyBignum big = (RubyBignum) other;
RubyObject tryFix = RubyBignum.bignorm(getRuntime(), big.getValue());
if (!(tryFix instanceof RubyFixnum)) {
return big.getValue().signum() == 0 || value >= 0 ? RubyFixnum.zero(getRuntime()) : RubyFixnum.one(getRuntime());
}
}
long otherValue = fix2long(other);
if (otherValue < 0) return RubyFixnum.zero(getRuntime());
if (BIT_SIZE - 1 < otherValue) {
return value < 0 ? RubyFixnum.one(getRuntime()) : RubyFixnum.zero(getRuntime());
}
return (value & (1L << otherValue)) == 0 ? RubyFixnum.zero(getRuntime()) : RubyFixnum.one(getRuntime());
}
/** fix_lshift
*
*/
@JRubyMethod(name = "<<")
public IRubyObject op_lshift(IRubyObject other) {
if (!(other instanceof RubyFixnum)) return RubyBignum.newBignum(getRuntime(), value).op_lshift(other);
long width = ((RubyFixnum)other).getLongValue();
return width < 0 ? rshift(-width) : lshift(width);
}
private IRubyObject lshift(long width) {
if (width > BIT_SIZE - 1 || ((~0L << BIT_SIZE - width - 1) & value) != 0) {
return RubyBignum.newBignum(getRuntime(), value).op_lshift(RubyFixnum.newFixnum(getRuntime(), width));
}
return RubyFixnum.newFixnum(getRuntime(), value << width);
}
/** fix_rshift
*
*/
@JRubyMethod(name = ">>")
public IRubyObject op_rshift(IRubyObject other) {
if (!(other instanceof RubyFixnum)) return RubyBignum.newBignum(getRuntime(), value).op_rshift(other);
long width = ((RubyFixnum)other).getLongValue();
if (width == 0) return this;
return width < 0 ? lshift(-width) : rshift(width);
}
private IRubyObject rshift(long width) {
if (width >= BIT_SIZE - 1) {
return value < 0 ? RubyFixnum.minus_one(getRuntime()) : RubyFixnum.zero(getRuntime());
}
return RubyFixnum.newFixnum(getRuntime(), value >> width);
}
/** fix_to_f
*
*/
@JRubyMethod
public IRubyObject to_f() {
return RubyFloat.newFloat(getRuntime(), (double) value);
}
/** fix_size
*
*/
@JRubyMethod
public IRubyObject size() {
return newFixnum((long) ((BIT_SIZE + 7) / 8));
}
/** fix_zero_p
*
*/
@JRubyMethod(name = "zero?")
public IRubyObject zero_p() {
return RubyBoolean.newBoolean(getRuntime(), value == 0);
}
@JRubyMethod
@Override
public IRubyObject id() {
if (value <= Long.MAX_VALUE / 2 && value >= Long.MIN_VALUE / 2) {
return newFixnum(2 * value + 1);
}
return super.id();
}
@Override
public IRubyObject taint(ThreadContext context) {
return this;
}
@Override
public IRubyObject freeze(ThreadContext context) {
return this;
}
// Piece of mri rb_to_id
@Override
public String asJavaString() {
getRuntime().getWarnings().warn(ID.FIXNUMS_NOT_SYMBOLS, "do not use Fixnums as Symbols");
// FIXME: I think this chunk is equivalent to MRI id2name (and not our public method
// id2name). Make into method if used more than once.
RubySymbol symbol = RubySymbol.getSymbolLong(getRuntime(), value);
if (symbol == null) {
throw getRuntime().newArgumentError("" + value + " is not a symbol");
}
return symbol.asJavaString();
}
public static RubyFixnum unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
return input.getRuntime().newFixnum(input.unmarshalInt());
}
/* ================
* Singleton Methods
* ================
*/
/** rb_fix_induced_from
*
*/
@JRubyMethod(meta = true)
public static IRubyObject induced_from(IRubyObject recv, IRubyObject other) {
return RubyNumeric.num2fix(other);
}
@Override
public IRubyObject to_java() {
return MiniJava.javaToRuby(getRuntime(), Long.valueOf(value));
}
@Override
public IRubyObject as(Class javaClass) {
return MiniJava.javaToRuby(getRuntime(), coerceToJavaType(getRuntime(), this, javaClass));
}
private static Object coerceToJavaType(Ruby ruby, RubyFixnum self, Class javaClass) {
if (!Number.class.isAssignableFrom(javaClass)) {
throw ruby.newTypeError(javaClass.getCanonicalName() + " is not a numeric type");
}
TypeCoercer coercer = JAVA_COERCERS.get(javaClass);
if (coercer == null) {
throw ruby.newTypeError("Cannot coerce Fixnum to " + javaClass.getCanonicalName());
}
return coercer.coerce(self);
}
private static final Map<Class, TypeCoercer> JAVA_COERCERS = new HashMap<Class, TypeCoercer>();
static {
TypeCoercer intCoercer = new TypeCoercer() {
public Object coerce(IRubyObject self) {
RubyFixnum fixnum = (RubyFixnum)self;
if (fixnum.value > Integer.MAX_VALUE) {
throw self.getRuntime().newRangeError("Fixnum " + fixnum.value + " is too large for Java int");
}
return Integer.valueOf((int)fixnum.value);
}
};
JAVA_COERCERS.put(int.class, intCoercer);
JAVA_COERCERS.put(Integer.class, intCoercer);
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Don Schwartz <schwardo@users.sourceforge.net>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.util.Numeric.f_expt;
import static org.jruby.util.Numeric.f_mul;
import static org.jruby.util.Numeric.f_to_i;
import static org.jruby.util.Numeric.frexp;
import static org.jruby.util.Numeric.ldexp;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
/**
* A representation of a float object
*/
@JRubyClass(name="Float", parent="Numeric", include="Precision")
public class RubyFloat extends RubyNumeric {
public static RubyClass createFloatClass(Ruby runtime) {
RubyClass floatc = runtime.defineClass("Float", runtime.getNumeric(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setFloat(floatc);
floatc.index = ClassIndex.FLOAT;
floatc.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyFloat;
}
};
floatc.getSingletonClass().undefineMethod("new");
floatc.includeModule(runtime.getPrecision());
// Java Doubles are 64 bit long:
floatc.defineConstant("ROUNDS", RubyFixnum.newFixnum(runtime, 1));
floatc.defineConstant("RADIX", RubyFixnum.newFixnum(runtime, 2));
floatc.defineConstant("MANT_DIG", RubyFixnum.newFixnum(runtime, 53));
floatc.defineConstant("DIG", RubyFixnum.newFixnum(runtime, 15));
// Double.MAX_EXPONENT since Java 1.6
floatc.defineConstant("MIN_EXP", RubyFixnum.newFixnum(runtime, -1021));
// Double.MAX_EXPONENT since Java 1.6
floatc.defineConstant("MAX_EXP", RubyFixnum.newFixnum(runtime, 1024));
floatc.defineConstant("MIN_10_EXP", RubyFixnum.newFixnum(runtime, -307));
floatc.defineConstant("MAX_10_EXP", RubyFixnum.newFixnum(runtime, 308));
floatc.defineConstant("MIN", RubyFloat.newFloat(runtime, Double.MIN_VALUE));
floatc.defineConstant("MAX", RubyFloat.newFloat(runtime, Double.MAX_VALUE));
floatc.defineConstant("EPSILON", RubyFloat.newFloat(runtime, 2.2204460492503131e-16));
floatc.defineAnnotatedMethods(RubyFloat.class);
return floatc;
}
private final double value;
public int getNativeTypeIndex() {
return ClassIndex.FLOAT;
}
public RubyFloat(Ruby runtime) {
this(runtime, 0.0);
}
public RubyFloat(Ruby runtime, double value) {
super(runtime, runtime.getFloat());
this.value = value;
}
public Class<?> getJavaClass() {
// this needs to be thought out more along with the changes in RubyFixnum
// since "to Object" coercion will generally want to produce the same
// type every time
// if (value >= Float.MIN_VALUE && value <= Float.MAX_VALUE) {
// return float.class;
// }
return double.class;
}
/** Getter for property value.
* @return Value of property value.
*/
public double getValue() {
return this.value;
}
public double getDoubleValue() {
return value;
}
public long getLongValue() {
return (long) value;
}
public RubyFloat convertToFloat() {
return this;
}
protected int compareValue(RubyNumeric other) {
double otherVal = other.getDoubleValue();
return getValue() > otherVal ? 1 : getValue() < otherVal ? -1 : 0;
}
public static RubyFloat newFloat(Ruby runtime, double value) {
return new RubyFloat(runtime, value);
}
/* ================
* Instance Methods
* ================
*/
/** rb_flo_induced_from
*
*/
@JRubyMethod(required = 1, meta = true)
public static IRubyObject induced_from(ThreadContext context, IRubyObject recv, IRubyObject number) {
if (number instanceof RubyFixnum || number instanceof RubyBignum || number instanceof RubyRational) {
return number.callMethod(context, MethodIndex.TO_F, "to_f");
} else if (number instanceof RubyFloat) {
return number;
}
throw recv.getRuntime().newTypeError(
"failed to convert " + number.getMetaClass() + " into Float");
}
private final static DecimalFormat FORMAT = new DecimalFormat("##############0.0##############",
new DecimalFormatSymbols(Locale.ENGLISH));
/** flo_to_s
*
*/
@JRubyMethod(name = "to_s")
public IRubyObject to_s() {
if (Double.isInfinite(value)) {
return RubyString.newString(getRuntime(), value < 0 ? "-Infinity" : "Infinity");
}
if (Double.isNaN(value)) {
return RubyString.newString(getRuntime(), "NaN");
}
String val = ""+value;
if(val.indexOf('E') != -1) {
String v2 = FORMAT.format(value);
int ix = v2.length()-1;
while(v2.charAt(ix) == '0' && v2.charAt(ix-1) != '.') {
ix--;
}
if(ix > 15 || "0.0".equals(v2.substring(0,ix+1))) {
val = val.replaceFirst("E(\\d)","e+$1").replaceFirst("E-","e-");
} else {
val = v2.substring(0,ix+1);
}
}
return RubyString.newString(getRuntime(), val);
}
/** flo_coerce
*
*/
@JRubyMethod(name = "coerce", required = 1)
public IRubyObject coerce(IRubyObject other) {
return getRuntime().newArray(RubyKernel.new_float(this, other), this);
}
/** flo_uminus
*
*/
@JRubyMethod(name = "-@")
public IRubyObject op_uminus() {
return RubyFloat.newFloat(getRuntime(), -value);
}
/** flo_plus
*
*/
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
return RubyFloat.newFloat(getRuntime(), value + ((RubyNumeric) other).getDoubleValue());
default:
return coerceBin(context, "+", other);
}
}
/** flo_minus
*
*/
@JRubyMethod(name = "-", required = 1)
public IRubyObject op_minus(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
return RubyFloat.newFloat(getRuntime(), value - ((RubyNumeric) other).getDoubleValue());
default:
return coerceBin(context, "-", other);
}
}
/** flo_mul
*
*/
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_mul(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
return RubyFloat.newFloat(
getRuntime(), value * ((RubyNumeric) other).getDoubleValue());
default:
return coerceBin(context, "*", other);
}
}
/** flo_div
*
*/
@JRubyMethod(name = "/", required = 1)
public IRubyObject op_fdiv(ThreadContext context, IRubyObject other) { // don't override Numeric#div !
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
return RubyFloat.newFloat(getRuntime(), value / ((RubyNumeric) other).getDoubleValue());
default:
return coerceBin(context, "/", other);
}
}
/** flo_mod
*
*/
@JRubyMethod(name = {"%", "modulo"}, required = 1)
public IRubyObject op_mod(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
double y = ((RubyNumeric) other).getDoubleValue();
// Modelled after c ruby implementation (java /,% not same as ruby)
double x = value;
double mod = Math.IEEEremainder(x, y);
if (y * mod < 0) {
mod += y;
}
return RubyFloat.newFloat(getRuntime(), mod);
default:
return coerceBin(context, "%", other);
}
}
/** flo_divmod
*
*/
@JRubyMethod(name = "divmod", required = 1)
public IRubyObject divmod(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
double y = ((RubyNumeric) other).getDoubleValue();
double x = value;
double mod = Math.IEEEremainder(x, y);
// MRI behavior:
if (Double.isNaN(mod)) {
throw getRuntime().newFloatDomainError("NaN");
}
double div = Math.floor(x / y);
if (y * mod < 0) {
mod += y;
}
final Ruby runtime = getRuntime();
IRubyObject car = dbl2num(runtime, div);
RubyFloat cdr = RubyFloat.newFloat(runtime, mod);
return RubyArray.newArray(runtime, car, cdr);
default:
return coerceBin(context, "divmod", other);
}
}
/** flo_pow
*
*/
@JRubyMethod(name = "**", required = 1)
public IRubyObject op_pow(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
return RubyFloat.newFloat(getRuntime(), Math.pow(value, ((RubyNumeric) other)
.getDoubleValue()));
default:
return coerceBin(context, "**", other);
}
}
/** flo_eq
*
*/
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
if (Double.isNaN(value)) {
return getRuntime().getFalse();
}
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
return RubyBoolean.newBoolean(getRuntime(), value == ((RubyNumeric) other)
.getDoubleValue());
default:
// Numeric.equal
return super.op_num_equal(context, other);
}
}
/** flo_cmp
*
*/
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
double b = ((RubyNumeric) other).getDoubleValue();
return dbl_cmp(getRuntime(), value, b);
default:
return coerceCmp(context, "<=>", other);
}
}
/** flo_gt
*
*/
@JRubyMethod(name = ">", required = 1)
public IRubyObject op_gt(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
double b = ((RubyNumeric) other).getDoubleValue();
return RubyBoolean.newBoolean(getRuntime(), !Double.isNaN(b) && value > b);
default:
return coerceRelOp(context, ">", other);
}
}
/** flo_ge
*
*/
@JRubyMethod(name = ">=", required = 1)
public IRubyObject op_ge(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
double b = ((RubyNumeric) other).getDoubleValue();
return RubyBoolean.newBoolean(getRuntime(), !Double.isNaN(b) && value >= b);
default:
return coerceRelOp(context, ">=", other);
}
}
/** flo_lt
*
*/
@JRubyMethod(name = "<", required = 1)
public IRubyObject op_lt(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
double b = ((RubyNumeric) other).getDoubleValue();
return RubyBoolean.newBoolean(getRuntime(), !Double.isNaN(b) && value < b);
default:
return coerceRelOp(context, "<", other);
}
}
/** flo_le
*
*/
@JRubyMethod(name = "<=", required = 1)
public IRubyObject op_le(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
case ClassIndex.FLOAT:
double b = ((RubyNumeric) other).getDoubleValue();
return RubyBoolean.newBoolean(getRuntime(), !Double.isNaN(b) && value <= b);
default:
return coerceRelOp(context, "<=", other);
}
}
/** flo_eql
*
*/
@JRubyMethod(name = "eql?", required = 1)
public IRubyObject eql_p(IRubyObject other) {
if (other instanceof RubyFloat) {
double b = ((RubyFloat) other).value;
if (Double.isNaN(value) || Double.isNaN(b)) {
return getRuntime().getFalse();
}
if (value == b) {
return getRuntime().getTrue();
}
}
return getRuntime().getFalse();
}
/** flo_hash
*
*/
@JRubyMethod(name = "hash")
public RubyFixnum hash() {
return getRuntime().newFixnum(hashCode());
}
public final int hashCode() {
long l = Double.doubleToLongBits(value);
return (int)(l ^ l >>> 32);
}
/** flo_fo
*
*/
@JRubyMethod(name = "to_f")
public IRubyObject to_f() {
return this;
}
/** flo_abs
*
*/
@JRubyMethod(name = "abs")
public IRubyObject abs() {
if (Double.doubleToLongBits(value) < 0) {
return RubyFloat.newFloat(getRuntime(), Math.abs(value));
}
return this;
}
/** flo_zero_p
*
*/
@JRubyMethod(name = "zero?")
public IRubyObject zero_p() {
return RubyBoolean.newBoolean(getRuntime(), value == 0.0);
}
/** flo_truncate
*
*/
@JRubyMethod(name = {"truncate", "to_i", "to_int"})
public IRubyObject truncate() {
double f = value;
if (f > 0.0) f = Math.floor(f);
if (f < 0.0) f = Math.ceil(f);
return dbl2num(getRuntime(), f);
}
/** float_to_r, float_decode
*
*/
static final int DBL_MANT_DIG = 53;
static final int FLT_RADIX = 2;
@JRubyMethod(name = "to_r", compat = CompatVersion.RUBY1_9)
public IRubyObject to_r(ThreadContext context) {
long[]exp = new long[1];
double f = frexp(value, exp);
f = ldexp(f, DBL_MANT_DIG);
long n = exp[0] - DBL_MANT_DIG;
Ruby runtime = context.getRuntime();
IRubyObject x = f_mul(context, f_to_i(context, runtime.newFloat(f)),
f_expt(context,
RubyFixnum.newFixnum(context.getRuntime(), FLT_RADIX),
RubyFixnum.newFixnum(runtime, n)));
return x;
}
/** floor
*
*/
@JRubyMethod(name = "floor")
public IRubyObject floor() {
return dbl2num(getRuntime(), Math.floor(value));
}
/** flo_ceil
*
*/
@JRubyMethod(name = "ceil")
public IRubyObject ceil() {
return dbl2num(getRuntime(), Math.ceil(value));
}
/** flo_round
*
*/
@JRubyMethod(name = "round")
public IRubyObject round() {
double f = value;
if (f > 0.0) {
f = Math.floor(f + 0.5);
}
if (f < 0.0) {
f = Math.ceil(f - 0.5);
}
return dbl2num(getRuntime(), f);
}
/** flo_is_nan_p
*
*/
@JRubyMethod(name = "nan?")
public IRubyObject nan_p() {
return RubyBoolean.newBoolean(getRuntime(), Double.isNaN(value));
}
/** flo_is_infinite_p
*
*/
@JRubyMethod(name = "infinite?")
public IRubyObject infinite_p() {
if (Double.isInfinite(value)) {
return RubyFixnum.newFixnum(getRuntime(), value < 0 ? -1 : 1);
}
return getRuntime().getNil();
}
/** flo_is_finite_p
*
*/
@JRubyMethod(name = "finite?")
public IRubyObject finite_p() {
if (Double.isInfinite(value) || Double.isNaN(value)) {
return getRuntime().getFalse();
}
return getRuntime().getTrue();
}
public static void marshalTo(RubyFloat aFloat, MarshalStream output) throws java.io.IOException {
output.registerLinkTarget(aFloat);
String strValue = aFloat.toString();
if (Double.isInfinite(aFloat.value)) {
strValue = aFloat.value < 0 ? "-inf" : "inf";
} else if (Double.isNaN(aFloat.value)) {
strValue = "nan";
}
output.writeString(strValue);
}
public static RubyFloat unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
RubyFloat result = RubyFloat.newFloat(input.getRuntime(), org.jruby.util.Convert.byteListToDouble(input.unmarshalString(),false));
input.registerLinkTarget(result);
return result;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
/**
* GC (Garbage Collection) Module
*
* Note: Since we rely on Java's memory model we can't provide the
* kind of control over garbage collection that MRI provides.
*
* @author Anders
*/
@JRubyModule(name="GC")
public class RubyGC {
public static RubyModule createGCModule(Ruby runtime) {
RubyModule result = runtime.defineModule("GC");
runtime.setGC(result);
result.defineAnnotatedMethods(RubyGC.class);
return result;
}
@JRubyMethod(module = true, visibility = Visibility.PRIVATE)
public static IRubyObject start(IRubyObject recv) {
System.gc();
return recv.getRuntime().getNil();
}
@JRubyMethod
public static IRubyObject garbage_collect(IRubyObject recv) {
System.gc();
return recv.getRuntime().getNil();
}
@JRubyMethod(module = true, visibility = Visibility.PRIVATE)
public static IRubyObject enable(IRubyObject recv) {
recv.getRuntime().getWarnings().warn(ID.EMPTY_IMPLEMENTATION, "GC.enable will not work on JRuby", "GC.enable");
return recv.getRuntime().getNil();
}
@JRubyMethod(module = true, visibility = Visibility.PRIVATE)
public static IRubyObject disable(IRubyObject recv) {
recv.getRuntime().getWarnings().warn(ID.EMPTY_IMPLEMENTATION, "GC.disable will not work on JRuby", "GC.disable");
return recv.getRuntime().getNil();
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Tim Azzopardi <tim@tigerfive.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.util.io.STDIO;
import java.util.HashMap;
import java.util.Map;
import org.jruby.anno.JRubyMethod;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.environment.OSEnvironmentReaderExcepton;
import org.jruby.environment.OSEnvironment;
import org.jruby.internal.runtime.ValueAccessor;
import org.jruby.javasupport.JavaUtil;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Constants;
import org.jruby.runtime.GlobalVariable;
import org.jruby.runtime.IAccessor;
import org.jruby.runtime.ReadonlyGlobalVariable;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.KCode;
/** This class initializes global variables and constants.
*
* @author jpetersen
*/
public class RubyGlobal {
/**
* Obligate string-keyed and string-valued hash, used for ENV and ENV_JAVA
*
*/
public static class StringOnlyRubyHash extends RubyHash {
public StringOnlyRubyHash(Ruby runtime, Map valueMap, IRubyObject defaultValue) {
super(runtime, valueMap, defaultValue);
}
@Override
public RubyHash to_hash() {
Ruby runtime = getRuntime();
RubyHash hash = RubyHash.newHash(runtime);
hash.replace(runtime.getCurrentContext(), this);
return hash;
}
@Override
public IRubyObject op_aref(ThreadContext context, IRubyObject key) {
return super.op_aref(context, key.convertToString());
}
@Override
public IRubyObject op_aset(ThreadContext context, IRubyObject key, IRubyObject value) {
if (!key.respondsTo("to_str")) {
throw getRuntime().newTypeError("can't convert " + key.getMetaClass() + " into String");
}
if (!value.respondsTo("to_str") && !value.isNil()) {
throw getRuntime().newTypeError("can't convert " + value.getMetaClass() + " into String");
}
if (value.isNil()) {
return super.delete(context, key, org.jruby.runtime.Block.NULL_BLOCK);
}
//return super.aset(getRuntime().newString("sadfasdF"), getRuntime().newString("sadfasdF"));
return super.op_aset(context, RuntimeHelpers.invoke(context, key, "to_str"),
value.isNil() ? getRuntime().getNil() : RuntimeHelpers.invoke(context, value, "to_str"));
}
@JRubyMethod
@Override
public IRubyObject to_s(){
return getRuntime().newString("ENV");
}
}
public static void createGlobals(ThreadContext context, Ruby runtime) {
runtime.defineGlobalConstant("TOPLEVEL_BINDING", runtime.newBinding());
runtime.defineGlobalConstant("TRUE", runtime.getTrue());
runtime.defineGlobalConstant("FALSE", runtime.getFalse());
runtime.defineGlobalConstant("NIL", runtime.getNil());
// define ARGV and $* for this runtime
RubyArray argvArray = runtime.newArray();
String[] argv = runtime.getInstanceConfig().getArgv();
for (int i = 0; i < argv.length; i++) {
argvArray.append(RubyString.newString(runtime, argv[i].getBytes()));
}
runtime.defineGlobalConstant("ARGV", argvArray);
runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(argvArray));
IAccessor d = new ValueAccessor(runtime.newString(
runtime.getInstanceConfig().displayedFileName()));
runtime.getGlobalVariables().define("$PROGRAM_NAME", d);
runtime.getGlobalVariables().define("$0", d);
// Version information:
IRubyObject version = runtime.newString(Constants.RUBY_VERSION).freeze(context);
IRubyObject release = runtime.newString(Constants.COMPILE_DATE).freeze(context);
IRubyObject platform = runtime.newString(Constants.PLATFORM).freeze(context);
IRubyObject engine = runtime.newString(Constants.ENGINE).freeze(context);
runtime.defineGlobalConstant("RUBY_VERSION", version);
runtime.defineGlobalConstant("RUBY_PATCHLEVEL", runtime.newString(Constants.RUBY_PATCHLEVEL).freeze(context));
runtime.defineGlobalConstant("RUBY_RELEASE_DATE", release);
runtime.defineGlobalConstant("RUBY_PLATFORM", platform);
runtime.defineGlobalConstant("RUBY_ENGINE", engine);
runtime.defineGlobalConstant("VERSION", version);
runtime.defineGlobalConstant("RELEASE_DATE", release);
runtime.defineGlobalConstant("PLATFORM", platform);
IRubyObject jrubyVersion = runtime.newString(Constants.VERSION).freeze(context);
runtime.defineGlobalConstant("JRUBY_VERSION", jrubyVersion);
GlobalVariable kcodeGV = new KCodeGlobalVariable(runtime, "$KCODE", runtime.newString("NONE"));
runtime.defineVariable(kcodeGV);
runtime.defineVariable(new GlobalVariable.Copy(runtime, "$-K", kcodeGV));
IRubyObject defaultRS = runtime.newString(runtime.getInstanceConfig().getRecordSeparator()).freeze(context);
GlobalVariable rs = new StringGlobalVariable(runtime, "$/", defaultRS);
runtime.defineVariable(rs);
runtime.setRecordSeparatorVar(rs);
runtime.getGlobalVariables().setDefaultSeparator(defaultRS);
runtime.defineVariable(new StringGlobalVariable(runtime, "$\\", runtime.getNil()));
runtime.defineVariable(new StringGlobalVariable(runtime, "$,", runtime.getNil()));
runtime.defineVariable(new LineNumberGlobalVariable(runtime, "$.", RubyFixnum.one(runtime)));
runtime.defineVariable(new LastlineGlobalVariable(runtime, "$_"));
runtime.defineVariable(new LastExitStatusVariable(runtime, "$?"));
runtime.defineVariable(new ErrorInfoGlobalVariable(runtime, "$!", runtime.getNil()));
runtime.defineVariable(new NonEffectiveGlobalVariable(runtime, "$=", runtime.getFalse()));
if(runtime.getInstanceConfig().getInputFieldSeparator() == null) {
runtime.defineVariable(new GlobalVariable(runtime, "$;", runtime.getNil()));
} else {
runtime.defineVariable(new GlobalVariable(runtime, "$;", RubyRegexp.newRegexp(runtime, runtime.getInstanceConfig().getInputFieldSeparator(), 0)));
}
Boolean verbose = runtime.getInstanceConfig().getVerbose();
IRubyObject verboseValue = null;
if (verbose == null) {
verboseValue = runtime.getNil();
} else if(verbose == Boolean.TRUE) {
verboseValue = runtime.getTrue();
} else {
verboseValue = runtime.getFalse();
}
runtime.defineVariable(new VerboseGlobalVariable(runtime, "$VERBOSE", verboseValue));
IRubyObject debug = runtime.newBoolean(runtime.getInstanceConfig().isDebug());
runtime.defineVariable(new DebugGlobalVariable(runtime, "$DEBUG", debug));
runtime.defineVariable(new DebugGlobalVariable(runtime, "$-d", debug));
runtime.defineVariable(new SafeGlobalVariable(runtime, "$SAFE"));
runtime.defineVariable(new BacktraceGlobalVariable(runtime, "$@"));
IRubyObject stdin = new RubyIO(runtime, STDIO.IN);
IRubyObject stdout = new RubyIO(runtime, STDIO.OUT);
IRubyObject stderr = new RubyIO(runtime, STDIO.ERR);
runtime.defineVariable(new InputGlobalVariable(runtime, "$stdin", stdin));
runtime.defineVariable(new OutputGlobalVariable(runtime, "$stdout", stdout));
runtime.getGlobalVariables().alias("$>", "$stdout");
runtime.getGlobalVariables().alias("$defout", "$stdout");
runtime.defineVariable(new OutputGlobalVariable(runtime, "$stderr", stderr));
runtime.getGlobalVariables().alias("$deferr", "$stderr");
runtime.defineGlobalConstant("STDIN", stdin);
runtime.defineGlobalConstant("STDOUT", stdout);
runtime.defineGlobalConstant("STDERR", stderr);
runtime.defineVariable(new LoadedFeatures(runtime, "$\""));
runtime.defineVariable(new LoadedFeatures(runtime, "$LOADED_FEATURES"));
runtime.defineVariable(new LoadPath(runtime, "$:"));
runtime.defineVariable(new LoadPath(runtime, "$-I"));
runtime.defineVariable(new LoadPath(runtime, "$LOAD_PATH"));
runtime.defineVariable(new MatchMatchGlobalVariable(runtime, "$&"));
runtime.defineVariable(new PreMatchGlobalVariable(runtime, "$`"));
runtime.defineVariable(new PostMatchGlobalVariable(runtime, "$'"));
runtime.defineVariable(new LastMatchGlobalVariable(runtime, "$+"));
runtime.defineVariable(new BackRefGlobalVariable(runtime, "$~"));
// On platforms without a c-library accessable through JNA, getpid will return hashCode
// as $$ used to. Using $$ to kill processes could take down many runtimes, but by basing
// $$ on getpid() where available, we have the same semantics as MRI.
runtime.getGlobalVariables().defineReadonly("$$", new ValueAccessor(runtime.newFixnum(runtime.getPosix().getpid())));
// after defn of $stderr as the call may produce warnings
defineGlobalEnvConstants(runtime);
// Fixme: Do we need the check or does Main.java not call this...they should consolidate
if (runtime.getGlobalVariables().get("$*").isNil()) {
runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(runtime.newArray()));
}
runtime.getGlobalVariables().defineReadonly("$-p",
new ValueAccessor(runtime.getInstanceConfig().isAssumePrinting() ? runtime.getTrue() : runtime.getNil()));
runtime.getGlobalVariables().defineReadonly("$-n",
new ValueAccessor(runtime.getInstanceConfig().isAssumeLoop() ? runtime.getTrue() : runtime.getNil()));
runtime.getGlobalVariables().defineReadonly("$-a",
new ValueAccessor(runtime.getInstanceConfig().isSplit() ? runtime.getTrue() : runtime.getNil()));
runtime.getGlobalVariables().defineReadonly("$-l",
new ValueAccessor(runtime.getInstanceConfig().isProcessLineEnds() ? runtime.getTrue() : runtime.getNil()));
// ARGF, $< object
RubyArgsFile.initArgsFile(runtime);
}
private static void defineGlobalEnvConstants(Ruby runtime) {
Map environmentVariableMap = null;
OSEnvironment environment = new OSEnvironment();
try {
environmentVariableMap = environment.getEnvironmentVariableMap(runtime);
} catch (OSEnvironmentReaderExcepton e) {
// If the environment variables are not accessible shouldn't terminate
runtime.getWarnings().warn(ID.MISCELLANEOUS, e.getMessage());
}
if (environmentVariableMap == null) {
// if the environment variables can't be obtained, define an empty ENV
environmentVariableMap = new HashMap();
}
StringOnlyRubyHash h1 = new StringOnlyRubyHash(runtime,
environmentVariableMap, runtime.getNil());
h1.getSingletonClass().defineAnnotatedMethods(StringOnlyRubyHash.class);
runtime.defineGlobalConstant("ENV", h1);
// Define System.getProperties() in ENV_JAVA
Map systemProps = environment.getSystemPropertiesMap(runtime);
runtime.defineGlobalConstant("ENV_JAVA", new StringOnlyRubyHash(
runtime, systemProps, runtime.getNil()));
}
private static class NonEffectiveGlobalVariable extends GlobalVariable {
public NonEffectiveGlobalVariable(Ruby runtime, String name, IRubyObject value) {
super(runtime, name, value);
}
@Override
public IRubyObject set(IRubyObject value) {
runtime.getWarnings().warn(ID.INEFFECTIVE_GLOBAL, "warning: variable " + name + " is no longer effective; ignored", name);
return value;
}
@Override
public IRubyObject get() {
runtime.getWarnings().warn(ID.INEFFECTIVE_GLOBAL, "warning: variable " + name + " is no longer effective", name);
return runtime.getFalse();
}
}
private static class LastExitStatusVariable extends GlobalVariable {
public LastExitStatusVariable(Ruby runtime, String name) {
super(runtime, name, runtime.getNil());
}
@Override
public IRubyObject get() {
IRubyObject lastExitStatus = runtime.getCurrentContext().getLastExitStatus();
return lastExitStatus == null ? runtime.getNil() : lastExitStatus;
}
@Override
public IRubyObject set(IRubyObject lastExitStatus) {
runtime.getCurrentContext().setLastExitStatus(lastExitStatus);
return lastExitStatus;
}
}
private static class MatchMatchGlobalVariable extends GlobalVariable {
public MatchMatchGlobalVariable(Ruby runtime, String name) {
super(runtime, name, runtime.getNil());
}
@Override
public IRubyObject get() {
return RubyRegexp.last_match(runtime.getCurrentContext().getCurrentFrame().getBackRef());
}
}
private static class PreMatchGlobalVariable extends GlobalVariable {
public PreMatchGlobalVariable(Ruby runtime, String name) {
super(runtime, name, runtime.getNil());
}
@Override
public IRubyObject get() {
return RubyRegexp.match_pre(runtime.getCurrentContext().getCurrentFrame().getBackRef());
}
}
private static class PostMatchGlobalVariable extends GlobalVariable {
public PostMatchGlobalVariable(Ruby runtime, String name) {
super(runtime, name, runtime.getNil());
}
@Override
public IRubyObject get() {
return RubyRegexp.match_post(runtime.getCurrentContext().getCurrentFrame().getBackRef());
}
}
private static class LastMatchGlobalVariable extends GlobalVariable {
public LastMatchGlobalVariable(Ruby runtime, String name) {
super(runtime, name, runtime.getNil());
}
@Override
public IRubyObject get() {
return RubyRegexp.match_last(runtime.getCurrentContext().getCurrentFrame().getBackRef());
}
}
private static class BackRefGlobalVariable extends GlobalVariable {
public BackRefGlobalVariable(Ruby runtime, String name) {
super(runtime, name, runtime.getNil());
}
@Override
public IRubyObject get() {
return RuntimeHelpers.getBackref(runtime, runtime.getCurrentContext());
}
@Override
public IRubyObject set(IRubyObject value) {
RuntimeHelpers.setBackref(runtime, runtime.getCurrentContext(), value);
return value;
}
}
// Accessor methods.
private static class LineNumberGlobalVariable extends GlobalVariable {
public LineNumberGlobalVariable(Ruby runtime, String name, RubyFixnum value) {
super(runtime, name, value);
}
@Override
public IRubyObject set(IRubyObject value) {
RubyArgsFile.setCurrentLineNumber(runtime.getGlobalVariables().get("$<"),RubyNumeric.fix2int(value));
return super.set(value);
}
}
private static class ErrorInfoGlobalVariable extends GlobalVariable {
public ErrorInfoGlobalVariable(Ruby runtime, String name, IRubyObject value) {
super(runtime, name, null);
set(value);
}
@Override
public IRubyObject set(IRubyObject value) {
if (!value.isNil() &&
!runtime.getException().isInstance(value) &&
!(JavaUtil.isJavaObject(value) && JavaUtil.unwrapJavaObject(value) instanceof Exception)) {
throw runtime.newTypeError("assigning non-exception to $!");
}
return runtime.getCurrentContext().setErrorInfo(value);
}
@Override
public IRubyObject get() {
return runtime.getCurrentContext().getErrorInfo();
}
}
// FIXME: move out of this class!
public static class StringGlobalVariable extends GlobalVariable {
public StringGlobalVariable(Ruby runtime, String name, IRubyObject value) {
super(runtime, name, value);
}
@Override
public IRubyObject set(IRubyObject value) {
if (!value.isNil() && ! (value instanceof RubyString)) {
throw runtime.newTypeError("value of " + name() + " must be a String");
}
return super.set(value);
}
}
public static class KCodeGlobalVariable extends GlobalVariable {
public KCodeGlobalVariable(Ruby runtime, String name, IRubyObject value) {
super(runtime, name, value);
}
@Override
public IRubyObject get() {
return runtime.getKCode().kcode(runtime);
}
@Override
public IRubyObject set(IRubyObject value) {
runtime.setKCode(KCode.create(runtime, value.convertToString().toString()));
return value;
}
}
private static class SafeGlobalVariable extends GlobalVariable {
public SafeGlobalVariable(Ruby runtime, String name) {
super(runtime, name, null);
}
@Override
public IRubyObject get() {
return runtime.newFixnum(runtime.getSafeLevel());
}
@Override
public IRubyObject set(IRubyObject value) {
// int level = RubyNumeric.fix2int(value);
// if (level < runtime.getSafeLevel()) {
// throw runtime.newSecurityError("tried to downgrade safe level from " +
// runtime.getSafeLevel() + " to " + level);
// }
// runtime.setSafeLevel(level);
// thread.setSafeLevel(level);
runtime.getWarnings().warn(ID.SAFE_NOT_SUPPORTED, "SAFE levels are not supported in JRuby");
return RubyFixnum.newFixnum(runtime, runtime.getSafeLevel());
}
}
private static class VerboseGlobalVariable extends GlobalVariable {
public VerboseGlobalVariable(Ruby runtime, String name, IRubyObject initialValue) {
super(runtime, name, initialValue);
set(initialValue);
}
@Override
public IRubyObject get() {
return runtime.getVerbose();
}
@Override
public IRubyObject set(IRubyObject newValue) {
if (newValue.isNil()) {
runtime.setVerbose(newValue);
} else {
runtime.setVerbose(runtime.newBoolean(newValue.isTrue()));
}
return newValue;
}
}
private static class DebugGlobalVariable extends GlobalVariable {
public DebugGlobalVariable(Ruby runtime, String name, IRubyObject initialValue) {
super(runtime, name, initialValue);
set(initialValue);
}
@Override
public IRubyObject get() {
return runtime.getDebug();
}
@Override
public IRubyObject set(IRubyObject newValue) {
if (newValue.isNil()) {
runtime.setDebug(newValue);
} else {
runtime.setDebug(runtime.newBoolean(newValue.isTrue()));
}
return newValue;
}
}
private static class BacktraceGlobalVariable extends GlobalVariable {
public BacktraceGlobalVariable(Ruby runtime, String name) {
super(runtime, name, null);
}
@Override
public IRubyObject get() {
IRubyObject errorInfo = runtime.getGlobalVariables().get("$!");
IRubyObject backtrace = errorInfo.isNil() ? runtime.getNil() : errorInfo.callMethod(errorInfo.getRuntime().getCurrentContext(), "backtrace");
//$@ returns nil if $!.backtrace is not an array
if (!(backtrace instanceof RubyArray)) {
backtrace = runtime.getNil();
}
return backtrace;
}
@Override
public IRubyObject set(IRubyObject value) {
if (runtime.getGlobalVariables().get("$!").isNil()) {
throw runtime.newArgumentError("$! not set.");
}
runtime.getGlobalVariables().get("$!").callMethod(value.getRuntime().getCurrentContext(), "set_backtrace", value);
return value;
}
}
private static class LastlineGlobalVariable extends GlobalVariable {
public LastlineGlobalVariable(Ruby runtime, String name) {
super(runtime, name, null);
}
@Override
public IRubyObject get() {
return RuntimeHelpers.getLastLine(runtime, runtime.getCurrentContext());
}
@Override
public IRubyObject set(IRubyObject value) {
RuntimeHelpers.setLastLine(runtime, runtime.getCurrentContext(), value);
return value;
}
}
private static class InputGlobalVariable extends GlobalVariable {
public InputGlobalVariable(Ruby runtime, String name, IRubyObject value) {
super(runtime, name, value);
}
@Override
public IRubyObject set(IRubyObject value) {
if (value == get()) {
return value;
}
return super.set(value);
}
}
private static class OutputGlobalVariable extends GlobalVariable {
public OutputGlobalVariable(Ruby runtime, String name, IRubyObject value) {
super(runtime, name, value);
}
@Override
public IRubyObject set(IRubyObject value) {
if (value == get()) {
return value;
}
if (value instanceof RubyIO) {
RubyIO io = (RubyIO)value;
// HACK: in order to have stdout/err act like ttys and flush always,
// we set anything assigned to stdout/stderr to sync
io.getHandler().setSync(true);
}
if (!value.respondsTo("write")) {
throw runtime.newTypeError(name() + " must have write method, " +
value.getType().getName() + " given");
}
return super.set(value);
}
}
private static class LoadPath extends ReadonlyGlobalVariable {
public LoadPath(Ruby runtime, String name) {
super(runtime, name, null);
}
/**
* @see org.jruby.runtime.GlobalVariable#get()
*/
@Override
public IRubyObject get() {
return runtime.getLoadService().getLoadPath();
}
}
private static class LoadedFeatures extends ReadonlyGlobalVariable {
public LoadedFeatures(Ruby runtime, String name) {
super(runtime, name, null);
}
/**
* @see org.jruby.runtime.GlobalVariable#get()
*/
@Override
public IRubyObject get() {
return runtime.getLoadService().getLoadedFeatures();
}
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2006 Ola Bini <Ola.Bini@ki.se>
* Copyright (C) 2006 Tim Azzopardi <tim@tigerfive.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 MenTaLguY <mental@rydia.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.javasupport.JavaUtil;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.TypeConverter;
// Design overview:
//
// RubyHash is implemented as hash table with a singly-linked list of
// RubyHash.RubyHashEntry objects for each bucket. RubyHashEntry objects
// are also kept in a doubly-linked list which reflects their insertion
// order and is used for iteration. For simplicity, this latter list is
// circular; a dummy RubyHashEntry, RubyHash.head, is used to mark the
// ends of the list.
//
// When an entry is removed from the table, it is also removed from the
// doubly-linked list. However, while the reference to the previous
// RubyHashEntry is cleared (to mark the entry as dead), the reference
// to the next RubyHashEntry is preserved so that iterators are not
// invalidated: any iterator with a reference to a dead entry can climb
// back up into the list of live entries by chasing next references until
// it finds a live entry (or head).
//
// Ordinarily, this scheme would require O(N) time to clear a hash (since
// each RubyHashEntry would need to be visited and unlinked from the
// iteration list), but RubyHash also maintains a generation count. Every
// time the hash is cleared, the doubly-linked list is simply discarded and
// the generation count incremented. Iterators check to see whether the
// generation count has changed; if it has, they reset themselves back to
// the new start of the list.
//
// This design means that iterators are never invalidated by changes to the
// hashtable, and they do not need to modify the structure during their
// lifecycle.
//
/** Implementation of the Hash class.
*
* Concurrency: no synchronization is required among readers, but
* all users must synchronize externally with writers.
*
*/
@JRubyClass(name = "Hash", include="Enumerable")
public class RubyHash extends RubyObject implements Map {
public static RubyClass createHashClass(Ruby runtime) {
RubyClass hashc = runtime.defineClass("Hash", runtime.getObject(), HASH_ALLOCATOR);
runtime.setHash(hashc);
hashc.index = ClassIndex.HASH;
hashc.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyHash;
}
};
hashc.includeModule(runtime.getEnumerable());
hashc.defineAnnotatedMethods(RubyHash.class);
return hashc;
}
private final static ObjectAllocator HASH_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyHash(runtime, klass);
}
};
public int getNativeTypeIndex() {
return ClassIndex.HASH;
}
/** rb_hash_s_create
*
*/
@JRubyMethod(name = "[]", rest = true, frame = true, meta = true)
public static IRubyObject create(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyClass klass = (RubyClass) recv;
Ruby runtime = context.getRuntime();
RubyHash hash;
if (args.length == 1) {
IRubyObject tmp = TypeConverter.convertToTypeWithCheck(
args[0], runtime.getHash(), MethodIndex.TO_HASH, "to_hash");
if (!tmp.isNil()) {
RubyHash otherHash = (RubyHash) tmp;
return new RubyHash(runtime, klass, otherHash);
}
}
if ((args.length & 1) != 0) {
throw runtime.newArgumentError("odd number of args for Hash");
}
hash = (RubyHash)klass.allocate();
for (int i=0; i < args.length; i+=2) hash.op_aset(context, args[i], args[i+1]);
return hash;
}
/** rb_hash_new
*
*/
public static final RubyHash newHash(Ruby runtime) {
return new RubyHash(runtime);
}
/** rb_hash_new
*
*/
public static final RubyHash newHash(Ruby runtime, Map valueMap, IRubyObject defaultValue) {
assert defaultValue != null;
return new RubyHash(runtime, valueMap, defaultValue);
}
private RubyHashEntry[] table;
private int size = 0;
private int threshold;
private static final int PROCDEFAULT_HASH_F = 1 << 10;
private IRubyObject ifNone;
private RubyHash(Ruby runtime, RubyClass klass, RubyHash other) {
super(runtime, klass);
this.ifNone = runtime.getNil();
threshold = INITIAL_THRESHOLD;
table = other.internalCopyTable(head);
size = other.size;
}
public RubyHash(Ruby runtime, RubyClass klass) {
super(runtime, klass);
this.ifNone = runtime.getNil();
alloc();
}
public RubyHash(Ruby runtime) {
this(runtime, runtime.getNil());
}
public RubyHash(Ruby runtime, IRubyObject defaultValue) {
super(runtime, runtime.getHash());
this.ifNone = defaultValue;
alloc();
}
/*
* Constructor for internal usage (mainly for Array#|, Array#&, Array#- and Array#uniq)
* it doesn't initialize ifNone field
*/
RubyHash(Ruby runtime, boolean objectSpace) {
super(runtime, runtime.getHash(), objectSpace);
alloc();
}
// TODO should this be deprecated ? (to be efficient, internals should deal with RubyHash directly)
public RubyHash(Ruby runtime, Map valueMap, IRubyObject defaultValue) {
super(runtime, runtime.getHash());
this.ifNone = defaultValue;
alloc();
for (Iterator iter = valueMap.entrySet().iterator();iter.hasNext();) {
Map.Entry e = (Map.Entry)iter.next();
internalPut((IRubyObject)e.getKey(), (IRubyObject)e.getValue());
}
}
private final void alloc() {
threshold = INITIAL_THRESHOLD;
generation++;
head.nextAdded = head.prevAdded = head;
table = new RubyHashEntry[MRI_HASH_RESIZE ? MRI_INITIAL_CAPACITY : JAVASOFT_INITIAL_CAPACITY];
}
/* ============================
* Here are hash internals
* (This could be extracted to a separate class but it's not too large though)
* ============================
*/
private static final int MRI_PRIMES[] = {
8 + 3, 16 + 3, 32 + 5, 64 + 3, 128 + 3, 256 + 27, 512 + 9, 1024 + 9, 2048 + 5, 4096 + 3,
8192 + 27, 16384 + 43, 32768 + 3, 65536 + 45, 131072 + 29, 262144 + 3, 524288 + 21, 1048576 + 7,
2097152 + 17, 4194304 + 15, 8388608 + 9, 16777216 + 43, 33554432 + 35, 67108864 + 15,
134217728 + 29, 268435456 + 3, 536870912 + 11, 1073741824 + 85, 0
};
private static final int JAVASOFT_INITIAL_CAPACITY = 8; // 16 ?
private static final int MRI_INITIAL_CAPACITY = MRI_PRIMES[0];
private static final int INITIAL_THRESHOLD = JAVASOFT_INITIAL_CAPACITY - (JAVASOFT_INITIAL_CAPACITY >> 2);
private static final int MAXIMUM_CAPACITY = 1 << 30;
private static final RubyHashEntry NO_ENTRY = new RubyHashEntry();
private int generation = 0; // generation count for O(1) clears
private final RubyHashEntry head = new RubyHashEntry();
{ head.prevAdded = head.nextAdded = head; }
static final class RubyHashEntry implements Map.Entry {
private IRubyObject key;
private IRubyObject value;
private RubyHashEntry next;
private RubyHashEntry prevAdded;
private RubyHashEntry nextAdded;
private int hash;
RubyHashEntry() {
key = NEVER;
}
RubyHashEntry(int h, IRubyObject k, IRubyObject v, RubyHashEntry e, RubyHashEntry head) {
key = k; value = v; next = e; hash = h;
prevAdded = head.prevAdded;
nextAdded = head;
nextAdded.prevAdded = this;
prevAdded.nextAdded = this;
}
public void detach() {
if (prevAdded != null) {
prevAdded.nextAdded = nextAdded;
nextAdded.prevAdded = prevAdded;
prevAdded = null;
}
}
public boolean isLive() {
return prevAdded != null;
}
public Object getKey() {
return key;
}
public Object getJavaifiedKey(){
return JavaUtil.convertRubyToJava(key);
}
public Object getValue() {
return value;
}
public Object getJavaifiedValue() {
return JavaUtil.convertRubyToJava(value);
}
public Object setValue(Object value) {
IRubyObject oldValue = this.value;
if (value instanceof IRubyObject) {
this.value = (IRubyObject)value;
} else {
throw new UnsupportedOperationException("directEntrySet() doesn't support setValue for non IRubyObject instance entries, convert them manually or use entrySet() instead");
}
return oldValue;
}
public boolean equals(Object other){
if(!(other instanceof RubyHashEntry)) return false;
RubyHashEntry otherEntry = (RubyHashEntry)other;
if(key == otherEntry.key || key.eql(otherEntry.key)){
if(value == otherEntry.value || value.equals(otherEntry.value)) return true;
}
return false;
}
public int hashCode(){
return key.hashCode() ^ value.hashCode();
}
}
private static int JavaSoftHashValue(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
private static int JavaSoftBucketIndex(final int h, final int length) {
return h & (length - 1);
}
private static int MRIHashValue(int h) {
return h & HASH_SIGN_BIT_MASK;
}
private static final int HASH_SIGN_BIT_MASK = ~(1 << 31);
private static int MRIBucketIndex(final int h, final int length) {
return (h % length);
}
private final void resize(int newCapacity) {
final RubyHashEntry[] oldTable = table;
final RubyHashEntry[] newTable = new RubyHashEntry[newCapacity];
for (int j = 0; j < oldTable.length; j++) {
RubyHashEntry entry = oldTable[j];
oldTable[j] = null;
while (entry != null) {
RubyHashEntry next = entry.next;
int i = bucketIndex(entry.hash, newCapacity);
entry.next = newTable[i];
newTable[i] = entry;
entry = next;
}
}
table = newTable;
}
private final void JavaSoftCheckResize() {
if (size > threshold) {
int oldCapacity = table.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
int newCapacity = table.length << 1;
resize(newCapacity);
threshold = newCapacity - (newCapacity >> 2);
}
}
private static final int MIN_CAPA = 8;
private static final int ST_DEFAULT_MAX_DENSITY = 5;
private final void MRICheckResize() {
if (size / table.length > ST_DEFAULT_MAX_DENSITY) {
int forSize = table.length + 1; // size + 1;
for (int i=0, newCapacity = MIN_CAPA; i < MRI_PRIMES.length; i++, newCapacity <<= 1) {
if (newCapacity > forSize) {
resize(MRI_PRIMES[i]);
return;
}
}
return; // suboptimal for large hashes (> 1073741824 + 85 entries) not very likely to happen
}
}
// ------------------------------
private static boolean MRI_HASH = true;
private static boolean MRI_HASH_RESIZE = true;
private static int hashValue(final int h) {
return MRI_HASH ? MRIHashValue(h) : JavaSoftHashValue(h);
}
private static int bucketIndex(final int h, final int length) {
return MRI_HASH ? MRIBucketIndex(h, length) : JavaSoftBucketIndex(h, length);
}
private void checkResize() {
if (MRI_HASH_RESIZE) MRICheckResize(); else JavaSoftCheckResize();
}
// ------------------------------
public static long collisions = 0;
// put implementation
private final void internalPut(final IRubyObject key, final IRubyObject value) {
internalPut(key, value, true);
}
private final void internalPut(final IRubyObject key, final IRubyObject value, final boolean checkForExisting) {
checkResize();
final int hash = hashValue(key.hashCode());
final int i = bucketIndex(hash, table.length);
// if (table[i] != null) collisions++;
if (checkForExisting) {
for (RubyHashEntry entry = table[i]; entry != null; entry = entry.next) {
IRubyObject k;
if (entry.hash == hash && ((k = entry.key) == key || key.eql(k))) {
entry.value = value;
return;
}
}
}
table[i] = new RubyHashEntry(hash, key, value, table[i], head);
size++;
}
// get implementation
private final IRubyObject internalGet(IRubyObject key) { // specialized for value
return internalGetEntry(key).value;
}
private final RubyHashEntry internalGetEntry(IRubyObject key) {
final int hash = hashValue(key.hashCode());
for (RubyHashEntry entry = table[bucketIndex(hash, table.length)]; entry != null; entry = entry.next) {
IRubyObject k;
if (entry.hash == hash && ((k = entry.key) == key || key.eql(k))) return entry;
}
return NO_ENTRY;
}
// delete implementation
private final RubyHashEntry internalDelete(final IRubyObject key) {
return internalDelete(hashValue(key.hashCode()), MATCH_KEY, key);
}
private final RubyHashEntry internalDeleteEntry(final RubyHashEntry entry) {
// n.b. we need to recompute the hash in case the key object was modified
return internalDelete(hashValue(entry.key.hashCode()), MATCH_ENTRY, entry);
}
private final RubyHashEntry internalDelete(final int hash, final EntryMatchType matchType, final Object obj) {
final int i = bucketIndex(hash, table.length);
RubyHashEntry entry = table[i];
if (entry != null) {
RubyHashEntry prior = null;
for (; entry != null; prior = entry, entry = entry.next) {
if (entry.hash == hash && matchType.matches(entry, obj)) {
if (prior != null) {
prior.next = entry.next;
} else {
table[i] = entry.next;
}
entry.detach();
size--;
return entry;
}
}
}
return NO_ENTRY;
}
private static abstract class EntryMatchType {
public abstract boolean matches(final RubyHashEntry entry, final Object obj);
}
private static final EntryMatchType MATCH_KEY = new EntryMatchType() {
public boolean matches(final RubyHashEntry entry, final Object obj) {
final IRubyObject key = entry.key;
return obj == key || (((IRubyObject)obj).eql(key));
}
};
private static final EntryMatchType MATCH_ENTRY = new EntryMatchType() {
public boolean matches(final RubyHashEntry entry, final Object obj) {
return entry.equals(obj);
}
};
private final RubyHashEntry[] internalCopyTable(RubyHashEntry destHead) {
RubyHashEntry[]newTable = new RubyHashEntry[table.length];
for (RubyHashEntry entry = head.nextAdded; entry != head; entry = entry.nextAdded) {
int i = bucketIndex(entry.hash, table.length);
newTable[i] = new RubyHashEntry(entry.hash, entry.key, entry.value, newTable[i], destHead);
}
return newTable;
}
public static abstract class Visitor {
public abstract void visit(IRubyObject key, IRubyObject value);
}
public void visitAll(Visitor visitor) {
int startGeneration = generation;
for (RubyHashEntry entry = head.nextAdded; entry != head; entry = entry.nextAdded) {
if (startGeneration != generation) {
startGeneration = generation;
entry = head.nextAdded;
if (entry == head) break;
}
if (entry.isLive()) visitor.visit(entry.key, entry.value);
}
}
/* ============================
* End of hash internals
* ============================
*/
/* ================
* Instance Methods
* ================
*/
/** rb_hash_initialize
*
*/
@JRubyMethod(name = "initialize", optional = 1, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, final Block block) {
modify();
if (block.isGiven()) {
if (args.length > 0) throw getRuntime().newArgumentError("wrong number of arguments");
ifNone = getRuntime().newProc(Block.Type.PROC, block);
flags |= PROCDEFAULT_HASH_F;
} else {
Arity.checkArgumentCount(getRuntime(), args, 0, 1);
if (args.length == 1) ifNone = args[0];
}
return this;
}
/** rb_hash_default
*
*/
@Deprecated
public IRubyObject default_value_get(ThreadContext context, IRubyObject[] args) {
switch (args.length) {
case 0: return default_value_get(context);
case 1: return default_value_get(context, args[0]);
default: throw context.getRuntime().newArgumentError(args.length, 1);
}
}
@JRubyMethod(name = "default", frame = true)
public IRubyObject default_value_get(ThreadContext context) {
if ((flags & PROCDEFAULT_HASH_F) != 0) {
return getRuntime().getNil();
}
return ifNone;
}
@JRubyMethod(name = "default", frame = true)
public IRubyObject default_value_get(ThreadContext context, IRubyObject arg) {
if ((flags & PROCDEFAULT_HASH_F) != 0) {
return RuntimeHelpers.invoke(context, ifNone, "call", this, arg);
}
return ifNone;
}
/** rb_hash_set_default
*
*/
@JRubyMethod(name = "default=", required = 1)
public IRubyObject default_value_set(final IRubyObject defaultValue) {
modify();
ifNone = defaultValue;
flags &= ~PROCDEFAULT_HASH_F;
return ifNone;
}
/** rb_hash_default_proc
*
*/
@JRubyMethod(name = "default_proc", frame = true)
public IRubyObject default_proc() {
return (flags & PROCDEFAULT_HASH_F) != 0 ? ifNone : getRuntime().getNil();
}
/** rb_hash_modify
*
*/
public void modify() {
testFrozen("hash");
if (isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't modify hash");
}
}
/** inspect_hash
*
*/
private IRubyObject inspectHash(final ThreadContext context) {
final ByteList buffer = new ByteList();
buffer.append('{');
final boolean[] firstEntry = new boolean[1];
firstEntry[0] = true;
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
if (!firstEntry[0]) buffer.append(',').append(' ');
buffer.append(inspect(context, key).getByteList());
buffer.append('=').append('>');
buffer.append(inspect(context, value).getByteList());
firstEntry[0] = false;
}
});
buffer.append('}');
return getRuntime().newString(buffer);
}
/** rb_hash_inspect
*
*/
@JRubyMethod(name = "inspect")
public IRubyObject inspect(ThreadContext context) {
if (size == 0) return getRuntime().newString("{}");
if (getRuntime().isInspecting(this)) return getRuntime().newString("{...}");
try {
getRuntime().registerInspecting(this);
return inspectHash(context);
} finally {
getRuntime().unregisterInspecting(this);
}
}
/** rb_hash_size
*
*/
@JRubyMethod(name = {"size", "length"})
public RubyFixnum rb_size() {
return getRuntime().newFixnum(size);
}
/** rb_hash_empty_p
*
*/
@JRubyMethod(name = "empty?")
public RubyBoolean empty_p() {
return size == 0 ? getRuntime().getTrue() : getRuntime().getFalse();
}
/** rb_hash_to_a
*
*/
@JRubyMethod(name = "to_a")
public RubyArray to_a() {
final Ruby runtime = getRuntime();
final RubyArray result = RubyArray.newArray(runtime, size);
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
result.append(RubyArray.newArray(runtime, key, value));
}
});
result.setTaint(isTaint());
return result;
}
/** rb_hash_to_s & to_s_hash
*
*/
@JRubyMethod(name = "to_s")
public IRubyObject to_s() {
if (getRuntime().isInspecting(this)) return getRuntime().newString("{...}");
try {
getRuntime().registerInspecting(this);
return to_a().to_s();
} finally {
getRuntime().unregisterInspecting(this);
}
}
/** rb_hash_rehash
*
*/
@JRubyMethod(name = "rehash")
public RubyHash rehash() {
modify();
final RubyHashEntry[] oldTable = table;
final RubyHashEntry[] newTable = new RubyHashEntry[oldTable.length];
for (int j = 0; j < oldTable.length; j++) {
RubyHashEntry entry = oldTable[j];
oldTable[j] = null;
while (entry != null) {
RubyHashEntry next = entry.next;
entry.hash = entry.key.hashCode(); // update the hash value
int i = bucketIndex(entry.hash, newTable.length);
entry.next = newTable[i];
newTable[i] = entry;
entry = next;
}
}
table = newTable;
return this;
}
/** rb_hash_to_hash
*
*/
@JRubyMethod(name = "to_hash")
public RubyHash to_hash() {
return this;
}
public RubyHash convertToHash() {
return this;
}
public final void fastASet(IRubyObject key, IRubyObject value) {
internalPut(key, value);
}
@Deprecated
public IRubyObject op_aset(IRubyObject key, IRubyObject value) {
return op_aset(getRuntime().getCurrentContext(), key, value);
}
/** rb_hash_aset
*
*/
@JRubyMethod(name = {"[]=", "store"}, required = 2)
public IRubyObject op_aset(ThreadContext context, IRubyObject key, IRubyObject value) {
modify();
if (!(key instanceof RubyString)) {
internalPut(key, value);
} else {
final RubyHashEntry entry = internalGetEntry(key);
if (entry != NO_ENTRY) {
entry.value = value;
} else {
RubyString realKey = (RubyString)key;
if (!realKey.isFrozen()) {
realKey = realKey.strDup(context.getRuntime(), realKey.getMetaClass().getRealClass());;
realKey.setFrozen(true);
}
internalPut(realKey, value, false);
}
}
return value;
}
/**
* Note: this is included as a compatibility measure for AR-JDBC
* @deprecated use RubyHash.op_aset instead
*/
public IRubyObject aset(IRubyObject key, IRubyObject value) {
return op_aset(getRuntime().getCurrentContext(), key, value);
}
/**
* Note: this is included as a compatibility measure for Mongrel+JRuby
* @deprecated use RubyHash.op_aref instead
*/
public IRubyObject aref(IRubyObject key) {
return op_aref(getRuntime().getCurrentContext(), key);
}
public final IRubyObject fastARef(IRubyObject key) { // retuns null when not found to avoid unnecessary getRuntime().getNil() call
return internalGet(key);
}
/** rb_hash_aref
*
*/
@JRubyMethod(name = "[]", required = 1)
public IRubyObject op_aref(ThreadContext context, IRubyObject key) {
IRubyObject value;
return ((value = internalGet(key)) == null) ? callMethod(context, MethodIndex.DEFAULT, "default", key) : value;
}
/** rb_hash_fetch
*
*/
@JRubyMethod(name = "fetch", required = 1, optional = 1, frame = true)
public IRubyObject fetch(ThreadContext context, IRubyObject[] args, Block block) {
if (args.length == 2 && block.isGiven()) {
getRuntime().getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument");
}
IRubyObject value;
if ((value = internalGet(args[0])) == null) {
if (block.isGiven()) return block.yield(context, args[0]);
if (args.length == 1) throw getRuntime().newIndexError("key not found");
return args[1];
}
return value;
}
/** rb_hash_has_key
*
*/
@JRubyMethod(name = {"has_key?", "key?", "include?", "member?"}, required = 1)
public RubyBoolean has_key_p(IRubyObject key) {
return internalGetEntry(key) == NO_ENTRY ? getRuntime().getFalse() : getRuntime().getTrue();
}
private class Found extends RuntimeException {}
private boolean hasValue(final ThreadContext context, final IRubyObject expected) {
try {
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
if (equalInternal(context, value, expected)) {
throw new Found();
}
}
});
return false;
} catch (Found found) {
return true;
}
}
/** rb_hash_has_value
*
*/
@JRubyMethod(name = {"has_value?", "value?"}, required = 1)
public RubyBoolean has_value_p(ThreadContext context, IRubyObject expected) {
return getRuntime().newBoolean(hasValue(context, expected));
}
/** rb_hash_each
*
*/
@JRubyMethod(name = "each", frame = true)
public RubyHash each(final ThreadContext context, final Block block) {
final Ruby runtime = getRuntime();
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
// rb_assoc_new equivalent
block.yield(context, RubyArray.newArray(runtime, key, value), null, null, false);
}
});
return this;
}
/** rb_hash_each_pair
*
*/
@JRubyMethod(name = "each_pair", frame = true)
public RubyHash each_pair(final ThreadContext context, final Block block) {
final Ruby runtime = getRuntime();
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
// rb_yield_values(2,...) equivalent
block.yield(context, RubyArray.newArray(runtime, key, value), null, null, true);
}
});
return this;
}
/** rb_hash_each_value
*
*/
@JRubyMethod(name = "each_value", frame = true)
public RubyHash each_value(final ThreadContext context, final Block block) {
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
block.yield(context, value);
}
});
return this;
}
/** rb_hash_each_key
*
*/
@JRubyMethod(name = "each_key", frame = true)
public RubyHash each_key(final ThreadContext context, final Block block) {
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
block.yield(context, key);
}
});
return this;
}
/** rb_hash_sort
*
*/
@JRubyMethod(name = "sort", frame = true)
public RubyArray sort(Block block) {
return to_a().sort_bang(block);
}
private static class FoundKey extends RuntimeException {
public IRubyObject key;
FoundKey(IRubyObject key) {
super();
this.key = key;
}
}
/** rb_hash_index
*
*/
@JRubyMethod(name = "index", required = 1)
public IRubyObject index(ThreadContext context, IRubyObject expected) {
IRubyObject key = internalIndex(context, expected);
if (key != null) {
return key;
} else {
return getRuntime().getNil();
}
}
private IRubyObject internalIndex(final ThreadContext context, final IRubyObject expected) {
try {
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
if (equalInternal(context, value, expected)) {
throw new FoundKey(key);
}
}
});
return null;
} catch (FoundKey found) {
return found.key;
}
}
/** rb_hash_indexes
*
*/
@JRubyMethod(name = {"indexes", "indices"}, rest = true)
public RubyArray indices(ThreadContext context, IRubyObject[] indices) {
return values_at(context, indices);
}
/** rb_hash_keys
*
*/
@JRubyMethod(name = "keys")
public RubyArray keys() {
final Ruby runtime = getRuntime();
final RubyArray keys = RubyArray.newArray(runtime, size);
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
keys.append(key);
}
});
return keys;
}
/** rb_hash_values
*
*/
@JRubyMethod(name = "values")
public RubyArray rb_values() {
final RubyArray values = RubyArray.newArray(getRuntime(), size);
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
values.append(value);
}
});
return values;
}
/** rb_hash_equal
*
*/
private static final boolean EQUAL_CHECK_DEFAULT_VALUE = false;
private static class Mismatch extends RuntimeException {}
@Override
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(final ThreadContext context, final IRubyObject other) {
if (this == other) return getRuntime().getTrue();
if (!(other instanceof RubyHash)) {
if (other.respondsTo("to_hash") && equalInternal(context, other, this)) return getRuntime().getTrue();
return getRuntime().getFalse();
}
final RubyHash otherHash = (RubyHash)other;
if (size != otherHash.size) return getRuntime().getFalse();
final Ruby runtime = getRuntime();
if (EQUAL_CHECK_DEFAULT_VALUE) {
if (!equalInternal(context, ifNone, otherHash.ifNone) &&
(flags & PROCDEFAULT_HASH_F) != (otherHash.flags & PROCDEFAULT_HASH_F)) return runtime.getFalse();
}
try {
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
IRubyObject otherValue = otherHash.internalGet(key);
if (otherValue == null || !equalInternal(context, value, otherValue)) throw new Mismatch();
}
});
return runtime.getTrue();
} catch (Mismatch e) {
return runtime.getFalse();
}
}
/** rb_hash_shift
*
*/
@JRubyMethod(name = "shift")
public IRubyObject shift(ThreadContext context) {
modify();
RubyHashEntry entry = head.nextAdded;
if (entry != head) {
RubyArray result = RubyArray.newArray(getRuntime(), entry.key, entry.value);
internalDeleteEntry(entry);
return result;
}
if ((flags & PROCDEFAULT_HASH_F) != 0) {
return RuntimeHelpers.invoke(context, ifNone, "call", this, getRuntime().getNil());
} else {
return ifNone;
}
}
public final boolean fastDelete(IRubyObject key) {
return internalDelete(key) != NO_ENTRY;
}
/** rb_hash_delete
*
*/
@JRubyMethod(name = "delete", required = 1, frame = true)
public IRubyObject delete(ThreadContext context, IRubyObject key, Block block) {
modify();
final RubyHashEntry entry = internalDelete(key);
if (entry != NO_ENTRY) return entry.value;
if (block.isGiven()) return block.yield(context, key);
return getRuntime().getNil();
}
/** rb_hash_select
*
*/
@JRubyMethod(name = "select", frame = true)
public IRubyObject select(final ThreadContext context, final Block block) {
final RubyArray result = getRuntime().newArray();
final Ruby runtime = getRuntime();
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
if (block.yield(context, runtime.newArray(key, value), null, null, true).isTrue()) {
result.append(runtime.newArray(key, value));
}
}
});
return result;
}
/** rb_hash_delete_if
*
*/
@JRubyMethod(name = "delete_if", frame = true)
public RubyHash delete_if(final ThreadContext context, final Block block) {
modify();
final Ruby runtime = getRuntime();
final RubyHash self = this;
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
if (block.yield(context, RubyArray.newArray(runtime, key, value), null, null, true).isTrue()) {
self.delete(context, key, block);
}
}
});
return this;
}
/** rb_hash_reject
*
*/
@JRubyMethod(name = "reject", frame = true)
public RubyHash reject(ThreadContext context, Block block) {
return ((RubyHash)dup()).delete_if(context, block);
}
/** rb_hash_reject_bang
*
*/
@JRubyMethod(name = "reject!", frame = true)
public IRubyObject reject_bang(ThreadContext context, Block block) {
int n = size;
delete_if(context, block);
if (n == size) return getRuntime().getNil();
return this;
}
/** rb_hash_clear
*
*/
@JRubyMethod(name = "clear")
public RubyHash rb_clear() {
modify();
if (size > 0) {
alloc();
size = 0;
}
return this;
}
/** rb_hash_invert
*
*/
@JRubyMethod(name = "invert")
public RubyHash invert(final ThreadContext context) {
final RubyHash result = newHash(getRuntime());
visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
result.op_aset(context, value, key);
}
});
return result;
}
/** rb_hash_update
*
*/
@JRubyMethod(name = {"merge!", "update"}, required = 1, frame = true)
public RubyHash merge_bang(final ThreadContext context, final IRubyObject other, final Block block) {
modify();
final Ruby runtime = getRuntime();
final RubyHash otherHash = other.convertToHash();
final RubyHash self = this;
otherHash.visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
if (block.isGiven()) {
IRubyObject existing = self.internalGet(key);
if (existing != null)
value = block.yield(context, RubyArray.newArrayNoCopy(runtime, new IRubyObject[]{key, existing, value}));
}
self.op_aset(context, key, value);
}
});
return this;
}
/** rb_hash_merge
*
*/
@JRubyMethod(name = "merge", required = 1, frame = true)
public RubyHash merge(ThreadContext context, IRubyObject other, Block block) {
return ((RubyHash)dup()).merge_bang(context, other, block);
}
/** rb_hash_replace
*
*/
@JRubyMethod(name = "initialize_copy", required = 1, visibility = Visibility.PRIVATE)
public RubyHash initialize_copy(ThreadContext context, IRubyObject other) {
return replace(context, other);
}
/** rb_hash_replace
*
*/
@JRubyMethod(name = "replace", required = 1)
public RubyHash replace(final ThreadContext context, IRubyObject other) {
final RubyHash otherHash = other.convertToHash();
if (this == otherHash) return this;
rb_clear();
final RubyHash self = this;
otherHash.visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
self.op_aset(context, key, value);
}
});
ifNone = otherHash.ifNone;
if ((otherHash.flags & PROCDEFAULT_HASH_F) != 0) {
flags |= PROCDEFAULT_HASH_F;
} else {
flags &= ~PROCDEFAULT_HASH_F;
}
return this;
}
/** rb_hash_values_at
*
*/
@JRubyMethod(name = "values_at", rest = true)
public RubyArray values_at(ThreadContext context, IRubyObject[] args) {
RubyArray result = RubyArray.newArray(getRuntime(), args.length);
for (int i = 0; i < args.length; i++) {
result.append(op_aref(context, args[i]));
}
return result;
}
public boolean hasDefaultProc() {
return (flags & PROCDEFAULT_HASH_F) != 0;
}
public IRubyObject getIfNone(){
return ifNone;
}
private static class VisitorIOException extends RuntimeException {
VisitorIOException(Throwable cause) {
super(cause);
}
}
// FIXME: Total hack to get flash in Rails marshalling/unmarshalling in session ok...We need
// to totally change marshalling to work with overridden core classes.
public static void marshalTo(final RubyHash hash, final MarshalStream output) throws IOException {
output.registerLinkTarget(hash);
output.writeInt(hash.size);
try {
hash.visitAll(new Visitor() {
public void visit(IRubyObject key, IRubyObject value) {
try {
output.dumpObject(key);
output.dumpObject(value);
} catch (IOException e) {
throw new VisitorIOException(e);
}
}
});
} catch (VisitorIOException e) {
throw (IOException)e.getCause();
}
if (!hash.ifNone.isNil()) output.dumpObject(hash.ifNone);
}
public static RubyHash unmarshalFrom(UnmarshalStream input, boolean defaultValue) throws IOException {
RubyHash result = newHash(input.getRuntime());
input.registerLinkTarget(result);
int size = input.unmarshalInt();
ThreadContext context = input.getRuntime().getCurrentContext();
for (int i = 0; i < size; i++) {
result.op_aset(context, input.unmarshalObject(), input.unmarshalObject());
}
if (defaultValue) result.default_value_set(input.unmarshalObject());
return result;
}
public Class getJavaClass() {
return Map.class;
}
// Satisfy java.util.Set interface (for Java integration)
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean containsKey(Object key) {
return internalGet(JavaUtil.convertJavaToRuby(getRuntime(), key)) != null;
}
public boolean containsValue(Object value) {
return hasValue(getRuntime().getCurrentContext(), JavaUtil.convertJavaToRuby(getRuntime(), value));
}
public Object get(Object key) {
return JavaUtil.convertRubyToJava(internalGet(JavaUtil.convertJavaToRuby(getRuntime(), key)));
}
public Object put(Object key, Object value) {
internalPut(JavaUtil.convertJavaToRuby(getRuntime(), key), JavaUtil.convertJavaToRuby(getRuntime(), value));
return value;
}
public Object remove(Object key) {
IRubyObject rubyKey = JavaUtil.convertJavaToRuby(getRuntime(), key);
return internalDelete(rubyKey).value;
}
public void putAll(Map map) {
Ruby runtime = getRuntime();
for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
Object key = iter.next();
internalPut(JavaUtil.convertJavaToRuby(runtime, key), JavaUtil.convertJavaToRuby(runtime, map.get(key)));
}
}
public void clear() {
rb_clear();
}
public boolean equals(Object other) {
if (!(other instanceof RubyHash)) return false;
if (this == other) return true;
return op_equal(getRuntime().getCurrentContext(), (RubyHash)other).isTrue() ? true : false;
}
public Set keySet() {
return new BaseSet(KEY_VIEW);
}
public Set directKeySet() {
return new BaseSet(DIRECT_KEY_VIEW);
}
public Collection values() {
return new BaseCollection(VALUE_VIEW);
}
public Collection directValues() {
return new BaseCollection(DIRECT_VALUE_VIEW);
}
public Set entrySet() {
return new BaseSet(ENTRY_VIEW);
}
public Set directEntrySet() {
return new BaseSet(DIRECT_ENTRY_VIEW);
}
private class BaseSet extends AbstractSet {
final EntryView view;
public BaseSet(EntryView view) {
this.view = view;
}
public Iterator iterator() {
return new BaseIterator(view);
}
public boolean contains(Object o) {
return view.contains(RubyHash.this, o);
}
public void clear() {
RubyHash.this.clear();
}
public int size() {
return RubyHash.this.size;
}
public boolean remove(Object o) {
return view.remove(RubyHash.this, o);
}
}
private class BaseCollection extends AbstractCollection {
final EntryView view;
public BaseCollection(EntryView view) {
this.view = view;
}
public Iterator iterator() {
return new BaseIterator(view);
}
public boolean contains(Object o) {
return view.contains(RubyHash.this, o);
}
public void clear() {
RubyHash.this.clear();
}
public int size() {
return RubyHash.this.size;
}
public boolean remove(Object o) {
return view.remove(RubyHash.this, o);
}
}
private class BaseIterator implements Iterator {
final private EntryView view;
private RubyHashEntry entry;
private boolean peeking;
private int startGeneration;
public BaseIterator(EntryView view) {
this.view = view;
this.entry = head;
this.startGeneration = generation;
}
private void advance(boolean consume) {
if (!peeking) {
do {
if (startGeneration != generation) {
startGeneration = generation;
entry = head;
}
entry = entry.nextAdded;
} while (entry != head && !entry.isLive());
}
peeking = !consume;
}
public Object next() {
advance(true);
if (entry == head) {
peeking = true; // remain where we are
throw new NoSuchElementException();
}
return view.convertEntry(getRuntime(), entry);
}
// once hasNext has been called, we commit to next() returning
// the entry it found, even if it were subsequently deleted
public boolean hasNext() {
advance(false);
return entry != head;
}
public void remove() {
if (entry == head) {
throw new IllegalStateException("Iterator out of range");
}
internalDeleteEntry(entry);
}
}
private static abstract class EntryView {
public abstract Object convertEntry(Ruby runtime, RubyHashEntry value);
public abstract boolean contains(RubyHash hash, Object o);
public abstract boolean remove(RubyHash hash, Object o);
}
private static final EntryView DIRECT_KEY_VIEW = new EntryView() {
public Object convertEntry(Ruby runtime, RubyHashEntry entry) {
return entry.key;
}
public boolean contains(RubyHash hash, Object o) {
if (!(o instanceof IRubyObject)) return false;
return hash.internalGet((IRubyObject)o) != null;
}
public boolean remove(RubyHash hash, Object o) {
if (!(o instanceof IRubyObject)) return false;
return hash.internalDelete((IRubyObject)o) != NO_ENTRY;
}
};
private static final EntryView KEY_VIEW = new EntryView() {
public Object convertEntry(Ruby runtime, RubyHashEntry entry) {
return JavaUtil.convertRubyToJava(entry.key, Object.class);
}
public boolean contains(RubyHash hash, Object o) {
return hash.containsKey(o);
}
public boolean remove(RubyHash hash, Object o) {
return hash.remove(o) != null;
}
};
private static final EntryView DIRECT_VALUE_VIEW = new EntryView() {
public Object convertEntry(Ruby runtime, RubyHashEntry entry) {
return entry.value;
}
public boolean contains(RubyHash hash, Object o) {
if (!(o instanceof IRubyObject)) return false;
IRubyObject obj = (IRubyObject)o;
return hash.hasValue(obj.getRuntime().getCurrentContext(), obj);
}
public boolean remove(RubyHash hash, Object o) {
if (!(o instanceof IRubyObject)) return false;
IRubyObject obj = (IRubyObject) o;
IRubyObject key = hash.internalIndex(obj.getRuntime().getCurrentContext(), obj);
if (key == null) return false;
return hash.internalDelete(key) != NO_ENTRY;
}
};
private final EntryView VALUE_VIEW = new EntryView() {
public Object convertEntry(Ruby runtime, RubyHashEntry entry) {
return JavaUtil.convertRubyToJava(entry.value, Object.class);
}
public boolean contains(RubyHash hash, Object o) {
return hash.containsValue(o);
}
public boolean remove(RubyHash hash, Object o) {
IRubyObject value = JavaUtil.convertJavaToRuby(hash.getRuntime(), o);
IRubyObject key = hash.internalIndex(hash.getRuntime().getCurrentContext(), value);
if (key == null) return false;
return hash.internalDelete(key) != NO_ENTRY;
}
};
private final EntryView DIRECT_ENTRY_VIEW = new EntryView() {
public Object convertEntry(Ruby runtime, RubyHashEntry entry) {
return entry;
}
public boolean contains(RubyHash hash, Object o) {
if (!(o instanceof RubyHashEntry)) return false;
RubyHashEntry entry = (RubyHashEntry)o;
RubyHashEntry candidate = internalGetEntry(entry.key);
return candidate != NO_ENTRY && entry.equals(candidate);
}
public boolean remove(RubyHash hash, Object o) {
if (!(o instanceof RubyHashEntry)) return false;
return hash.internalDeleteEntry((RubyHashEntry)o) != NO_ENTRY;
}
};
private final EntryView ENTRY_VIEW = new EntryView() {
public Object convertEntry(Ruby runtime, RubyHashEntry entry) {
return new ConvertingEntry(runtime, entry);
}
public boolean contains(RubyHash hash, Object o) {
if (!(o instanceof ConvertingEntry)) return false;
ConvertingEntry entry = (ConvertingEntry)o;
RubyHashEntry candidate = hash.internalGetEntry(entry.entry.key);
return candidate != NO_ENTRY && entry.entry.equals(candidate);
}
public boolean remove(RubyHash hash, Object o) {
if (!(o instanceof ConvertingEntry)) return false;
ConvertingEntry entry = (ConvertingEntry)o;
return hash.internalDeleteEntry(entry.entry) != NO_ENTRY;
}
};
private static class ConvertingEntry implements Map.Entry {
private final RubyHashEntry entry;
private final Ruby runtime;
public ConvertingEntry(Ruby runtime, RubyHashEntry entry) {
this.entry = entry;
this.runtime = runtime;
}
public Object getKey() {
return JavaUtil.convertRubyToJava(entry.key, Object.class);
}
public Object getValue() {
return JavaUtil.convertRubyToJava(entry.value, Object.class);
}
public Object setValue(Object o) {
return entry.setValue(JavaUtil.convertJavaToRuby(runtime, o));
}
public boolean equals(Object o) {
if (!(o instanceof ConvertingEntry)) {
return false;
}
ConvertingEntry other = (ConvertingEntry)o;
return entry.equals(other.entry);
}
public int hashCode() {
return entry.hashCode();
}
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2007 Koichiro Ohba <koichiro@meadowy.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.UnmappableCharacterException;
import java.nio.charset.UnsupportedCharsetException;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
@JRubyClass(name="Iconv")
public class RubyIconv extends RubyObject {
//static private final String TRANSLIT = "//translit";
static private final String IGNORE = "//ignore";
private CharsetDecoder fromEncoding;
private CharsetEncoder toEncoding;
public RubyIconv(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private static final ObjectAllocator ICONV_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyIconv(runtime, klass);
}
};
@JRubyModule(name="Iconv::Failure")
public static class Failure {}
@JRubyClass(name="Iconv::IllegalSequence", parent="ArgumentError", include="Iconv::Failure")
public static class IllegalSequence {}
@JRubyClass(name="Iconv::InvalidCharacter", parent="ArgumentError", include="Iconv::Failure")
public static class InvalidCharacter {}
@JRubyClass(name="Iconv::InvalidEncoding", parent="ArgumentError", include="Iconv::Failure")
public static class InvalidEncoding {}
@JRubyClass(name="Iconv::OutOfRange", parent="ArgumentError", include="Iconv::Failure")
public static class OutOfRange {}
@JRubyClass(name="Iconv::BrokenLibrary", parent="ArgumentError", include="Iconv::Failure")
public static class BrokenLibrary {}
public static void createIconv(Ruby runtime) {
RubyClass iconvClass = runtime.defineClass("Iconv", runtime.getObject(), ICONV_ALLOCATOR);
iconvClass.defineAnnotatedMethods(RubyIconv.class);
RubyModule failure = iconvClass.defineModuleUnder("Failure");
RubyClass argumentError = runtime.getArgumentError();
String[] iconvErrors = {"IllegalSequence", "InvalidCharacter", "InvalidEncoding",
"OutOfRange", "BrokenLibrary"};
for (int i = 0; i < iconvErrors.length; i++) {
RubyClass subClass = iconvClass.defineClassUnder(iconvErrors[i], argumentError, RubyFailure.ICONV_FAILURE_ALLOCATOR);
subClass.defineAnnotatedMethods(RubyFailure.class);
subClass.includeModule(failure);
}
}
public static class RubyFailure extends RubyException {
private IRubyObject success;
private IRubyObject failed;
public static RubyFailure newInstance(Ruby runtime, RubyClass excptnClass, String msg) {
return new RubyFailure(runtime, excptnClass, msg);
}
protected static final ObjectAllocator ICONV_FAILURE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyFailure(runtime, klass);
}
};
protected RubyFailure(Ruby runtime, RubyClass rubyClass) {
this(runtime, rubyClass, null);
}
public RubyFailure(Ruby runtime, RubyClass rubyClass, String message) {
super(runtime, rubyClass, message);
}
@JRubyMethod(name = "initialize", required = 1, optional = 2, frame = true)
public IRubyObject initialize(IRubyObject[] args, Block block) {
super.initialize(args, block);
success = args.length >= 2 ? args[1] : getRuntime().getNil();
failed = args.length == 3 ? args[2] : getRuntime().getNil();
return this;
}
@JRubyMethod(name = "success")
public IRubyObject success() {
return success;
}
@JRubyMethod(name = "failed")
public IRubyObject failed() {
return failed;
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
RubyModule rubyClass = getMetaClass();
StringBuilder buffer = new StringBuilder("#<");
buffer.append(rubyClass.getName()).append(": ").append(success.inspect().toString());
buffer.append(", ").append(failed.inspect().toString()).append(">");
return getRuntime().newString(buffer.toString());
}
}
private static String getCharset(String encoding) {
int index = encoding.indexOf("//");
if (index == -1) return encoding;
return encoding.substring(0, index);
}
/* Currently dead code, but useful when we figure out how to actually perform translit.
private static boolean isTranslit(String encoding) {
return encoding.toLowerCase().indexOf(TRANSLIT) != -1 ? true : false;
}*/
private static boolean isIgnore(String encoding) {
return encoding.toLowerCase().indexOf(IGNORE) != -1 ? true : false;
}
@JRubyMethod(name = "open", required = 2, frame = true, meta = true)
public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject to, IRubyObject from, Block block) {
Ruby runtime = context.getRuntime();
RubyIconv iconv = newIconv(context, recv, to, from);
if (!block.isGiven()) return iconv;
IRubyObject result = runtime.getNil();
try {
result = block.yield(context, iconv);
} finally {
iconv.close();
}
return result;
}
private static RubyIconv newIconv(ThreadContext context, IRubyObject recv,
IRubyObject to, IRubyObject from) {
RubyClass klazz = (RubyClass)recv;
return (RubyIconv) klazz.newInstance(
context, new IRubyObject[] {to, from}, Block.NULL_BLOCK);
}
@JRubyMethod(name = "initialize", required = 2, frame = true)
public IRubyObject initialize(IRubyObject arg1, IRubyObject arg2, Block unusedBlock) {
Ruby runtime = getRuntime();
if (!arg1.respondsTo("to_str")) {
throw runtime.newTypeError("can't convert " + arg1.getMetaClass() + " into String");
}
if (!arg2.respondsTo("to_str")) {
throw runtime.newTypeError("can't convert " + arg2.getMetaClass() + " into String");
}
String to = arg1.convertToString().toString();
String from = arg2.convertToString().toString();
try {
fromEncoding = Charset.forName(getCharset(from)).newDecoder();
toEncoding = Charset.forName(getCharset(to)).newEncoder();
if (!isIgnore(from)) fromEncoding.onUnmappableCharacter(CodingErrorAction.REPORT);
if (!isIgnore(to)) toEncoding.onUnmappableCharacter(CodingErrorAction.REPORT);
} catch (IllegalCharsetNameException e) {
throw runtime.newInvalidEncoding("invalid encoding");
} catch (UnsupportedCharsetException e) {
throw runtime.newInvalidEncoding("invalid encoding");
} catch (Exception e) {
throw runtime.newSystemCallError(e.toString());
}
return this;
}
@JRubyMethod(name = "close")
public IRubyObject close() {
toEncoding = null;
fromEncoding = null;
return RubyString.newEmptyString(getRuntime());
}
@JRubyMethod
public IRubyObject iconv(IRubyObject str) {
return iconv(str, 0, -1);
}
@JRubyMethod
public IRubyObject iconv(IRubyObject str, IRubyObject startArg) {
int start = 0;
if (!startArg.isNil()) start = RubyNumeric.fix2int(startArg);
return iconv(str, start, -1);
}
@JRubyMethod
public IRubyObject iconv(IRubyObject str, IRubyObject startArg, IRubyObject endArg) {
int start = 0;
int end = -1;
if (!startArg.isNil()) start = RubyNumeric.fix2int(startArg);
if (!endArg.isNil()) end = RubyNumeric.fix2int(endArg);
return iconv(str, start, end);
}
private IRubyObject iconv(IRubyObject str, int start, int end) {
if (str.isNil()) {
fromEncoding.reset();
toEncoding.reset();
return RubyString.newEmptyString(getRuntime());
}
return _iconv(str.convertToString(), start, end);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one, two or three arguments.
*/
public IRubyObject iconv(IRubyObject[] args) {
switch (args.length) {
case 1:
return iconv(args[0]);
case 2:
return iconv(args[0], args[1]);
case 3:
return iconv(args[0], args[1], args[2]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
// FIXME: We are assuming that original string will be raw bytes. If -Ku is provided
// this will not be true, but that is ok for now. Deal with that when someone needs it.
private IRubyObject _iconv(RubyString str, int start, int end) {
if (fromEncoding == null) {
throw getRuntime().newArgumentError("closed iconv");
}
ByteList bytes = str.getByteList();
// treat start and end as start...end for end >= 0, start..end for end < 0
if (start < 0) {
start += bytes.length();
}
if (end < 0) {
end += 1 + bytes.length();
} else if (end > bytes.length()) {
end = bytes.length();
}
if (start < 0 || end < start) { // invalid ranges result in an empty string
return RubyString.newEmptyString(getRuntime());
}
ByteBuffer buf = ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin() + start, end - start);
try {
CharBuffer cbuf = fromEncoding.decode(buf);
buf = toEncoding.encode(cbuf);
} catch (MalformedInputException e) {
} catch (UnmappableCharacterException e) {
} catch (CharacterCodingException e) {
throw getRuntime().newInvalidEncoding("invalid sequence");
} catch (IllegalStateException e) {
}
byte[] arr = buf.array();
return getRuntime().newString(new ByteList(arr, 0, buf.limit()));
}
@JRubyMethod(name = "iconv", required = 2, rest = true, meta = true)
public static IRubyObject iconv(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
return convertWithArgs(context, recv, args, "iconv");
}
@JRubyMethod(name = "conv", required = 3, rest = true, meta = true)
public static IRubyObject conv(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
return convertWithArgs(context, recv, args, "conv").join(context, RubyString.newEmptyString(recv.getRuntime()));
}
@JRubyMethod(name = "charset_map", meta= true)
public static IRubyObject charset_map_get(IRubyObject recv) {
return recv.getRuntime().getCharsetMap();
}
private static String mapCharset(ThreadContext context, IRubyObject val) {
RubyHash charset = val.getRuntime().getCharsetMap();
if (charset.size() > 0) {
RubyString key = val.callMethod(context, "downcase").convertToString();
IRubyObject tryVal = charset.fastARef(key);
if (tryVal != null) val = tryVal;
}
return val.convertToString().toString();
}
public static RubyArray convertWithArgs(ThreadContext context, IRubyObject recv, IRubyObject[] args, String function) {
assert args.length >= 2;
RubyArray array = context.getRuntime().newArray(args.length - 2);
RubyIconv iconv = newIconv(context, recv, args[0], args[1]);
try {
for (int i = 2; i < args.length; i++) {
array.append(iconv.iconv(args[i]));
}
} finally {
iconv.close();
}
return array;
}
/*
private static IRubyObject convert(String fromEncoding, String toEncoding, RubyString original)
throws UnsupportedEncodingException {
// Get all bytes from PLAIN string pretend they are not encoded in any way.
byte[] string = original.getBytes();
// Now create a string pretending it is from fromEncoding
string = new String(string, fromEncoding).getBytes(toEncoding);
// Finally recode back to PLAIN
return RubyString.newString(original.getRuntime(), string);
}
*/
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.jruby.ast.executable.Script;
import org.jruby.exceptions.MainExitException;
import org.jruby.runtime.Constants;
import org.jruby.runtime.load.LoadService;
import org.jruby.util.ClassCache;
import org.jruby.util.JRubyFile;
import org.jruby.util.KCode;
import org.jruby.util.NormalizedFile;
import org.jruby.util.SafePropertyAccessor;
import org.objectweb.asm.Opcodes;
public class RubyInstanceConfig {
/**
* The max count of active methods eligible for JIT-compilation.
*/
private static final int JIT_MAX_METHODS_LIMIT = 4096;
/**
* The max size of JIT-compiled methods (full class size) allowed.
*/
private static final int JIT_MAX_SIZE_LIMIT = Integer.MAX_VALUE;
/**
* The JIT threshold to the specified method invocation count.
*/
private static final int JIT_THRESHOLD = 50;
/** The version to use for generated classes. Set to current JVM version by default */
public static final int JAVA_VERSION;
/**
* Default size for chained compilation.
*/
private static final int CHAINED_COMPILE_LINE_COUNT_DEFAULT = 500;
/**
* The number of lines at which a method, class, or block body is split into
* chained methods (to dodge 64k method-size limit in JVM).
*/
public static final int CHAINED_COMPILE_LINE_COUNT
= SafePropertyAccessor.getInt("jruby.compile.chainsize", CHAINED_COMPILE_LINE_COUNT_DEFAULT);
public enum CompileMode {
JIT, FORCE, OFF;
public boolean shouldPrecompileCLI() {
switch (this) {
case JIT: case FORCE:
return true;
}
return false;
}
public boolean shouldJIT() {
switch (this) {
case JIT: case FORCE:
return true;
}
return false;
}
public boolean shouldPrecompileAll() {
return this == FORCE;
}
}
private InputStream input = System.in;
private PrintStream output = System.out;
private PrintStream error = System.err;
private Profile profile = Profile.DEFAULT;
private boolean objectSpaceEnabled
= SafePropertyAccessor.getBoolean("jruby.objectspace.enabled", false);
private CompileMode compileMode = CompileMode.JIT;
private boolean runRubyInProcess = true;
private String currentDirectory;
private Map environment;
private String[] argv = {};
private final boolean jitLogging;
private final boolean jitLoggingVerbose;
private final int jitLogEvery;
private final int jitThreshold;
private final int jitMax;
private final int jitMaxSize;
private final boolean samplingEnabled;
private CompatVersion compatVersion;
private ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
private ClassLoader loader = contextLoader == null ? RubyInstanceConfig.class.getClassLoader() : contextLoader;
private ClassCache<Script> classCache;
// from CommandlineParser
private List<String> loadPaths = new ArrayList<String>();
private Set<String> excludedMethods = new HashSet<String>();
private StringBuffer inlineScript = new StringBuffer();
private boolean hasInlineScript = false;
private String scriptFileName = null;
private List<String> requiredLibraries = new ArrayList<String>();
private boolean benchmarking = false;
private boolean argvGlobalsOn = false;
private boolean assumeLoop = false;
private boolean assumePrinting = false;
private Map optionGlobals = new HashMap();
private boolean processLineEnds = false;
private boolean split = false;
// This property is a Boolean, to allow three values, so it can match MRI's nil, false and true
private Boolean verbose = Boolean.FALSE;
private boolean debug = false;
private boolean showVersion = false;
private boolean showBytecode = false;
private boolean showCopyright = false;
private boolean endOfArguments = false;
private boolean shouldRunInterpreter = true;
private boolean shouldPrintUsage = false;
private boolean shouldPrintProperties=false;
private boolean yarv = false;
private boolean rubinius = false;
private boolean yarvCompile = false;
private KCode kcode = KCode.NONE;
private String recordSeparator = "\n";
private boolean shouldCheckSyntax = false;
private String inputFieldSeparator = null;
private boolean managementEnabled = true;
private int safeLevel = 0;
private String jrubyHome;
public static final boolean FASTEST_COMPILE_ENABLED
= SafePropertyAccessor.getBoolean("jruby.compile.fastest");
public static final boolean BOXED_COMPILE_ENABLED
= FASTEST_COMPILE_ENABLED
|| SafePropertyAccessor.getBoolean("jruby.compile.boxed");
public static final boolean FASTOPS_COMPILE_ENABLED
= FASTEST_COMPILE_ENABLED
|| SafePropertyAccessor.getBoolean("jruby.compile.fastops");
public static final boolean FRAMELESS_COMPILE_ENABLED
= FASTEST_COMPILE_ENABLED
|| SafePropertyAccessor.getBoolean("jruby.compile.frameless");
public static final boolean POSITIONLESS_COMPILE_ENABLED
= FASTEST_COMPILE_ENABLED
|| SafePropertyAccessor.getBoolean("jruby.compile.positionless");
public static final boolean THREADLESS_COMPILE_ENABLED
= FASTEST_COMPILE_ENABLED
|| SafePropertyAccessor.getBoolean("jruby.compile.threadless");
public static final boolean LAZYHANDLES_COMPILE = SafePropertyAccessor.getBoolean("jruby.compile.lazyHandles", false);
public static final boolean FORK_ENABLED
= SafePropertyAccessor.getBoolean("jruby.fork.enabled");
public static final boolean POOLING_ENABLED
= SafePropertyAccessor.getBoolean("jruby.thread.pool.enabled");
public static final int POOL_MAX
= SafePropertyAccessor.getInt("jruby.thread.pool.max", Integer.MAX_VALUE);
public static final int POOL_MIN
= SafePropertyAccessor.getInt("jruby.thread.pool.min", 0);
public static final int POOL_TTL
= SafePropertyAccessor.getInt("jruby.thread.pool.ttl", 60);
public static final boolean NATIVE_NET_PROTOCOL
= SafePropertyAccessor.getBoolean("jruby.native.net.protocol", false);
public static boolean FULL_TRACE_ENABLED
= SafePropertyAccessor.getBoolean("jruby.debug.fullTrace", false);
public static final String COMPILE_EXCLUDE
= SafePropertyAccessor.getProperty("jruby.jit.exclude");
public static boolean nativeEnabled = true;
public static interface LoadServiceCreator {
LoadService create(Ruby runtime);
LoadServiceCreator DEFAULT = new LoadServiceCreator() {
public LoadService create(Ruby runtime) {
return new LoadService(runtime);
}
};
}
private LoadServiceCreator creator = LoadServiceCreator.DEFAULT;
static {
String specVersion = null;
try {
specVersion = System.getProperty("jruby.bytecode.version");
if (specVersion == null) {
specVersion = System.getProperty("java.specification.version");
}
if (System.getProperty("jruby.native.enabled") != null) {
nativeEnabled = Boolean.getBoolean("jruby.native.enabled");
}
} catch (SecurityException se) {
nativeEnabled = false;
specVersion = "1.5";
}
if (specVersion.equals("1.5")) {
JAVA_VERSION = Opcodes.V1_5;
} else {
JAVA_VERSION = Opcodes.V1_6;
}
}
public int characterIndex = 0;
public RubyInstanceConfig() {
if (Ruby.isSecurityRestricted())
currentDirectory = "/";
else {
currentDirectory = JRubyFile.getFileProperty("user.dir");
}
samplingEnabled = SafePropertyAccessor.getBoolean("jruby.sampling.enabled", false);
String compatString = SafePropertyAccessor.getProperty("jruby.compat.version", "RUBY1_8");
if (compatString.equalsIgnoreCase("RUBY1_8")) {
compatVersion = CompatVersion.RUBY1_8;
} else if (compatString.equalsIgnoreCase("RUBY1_9")) {
compatVersion = CompatVersion.RUBY1_9;
} else {
System.err.println("Compatibility version `" + compatString + "' invalid; use RUBY1_8 or RUBY1_9. Using RUBY1_8.");
compatVersion = CompatVersion.RUBY1_8;
}
if (Ruby.isSecurityRestricted()) {
compileMode = CompileMode.OFF;
jitLogging = false;
jitLoggingVerbose = false;
jitLogEvery = 0;
jitThreshold = -1;
jitMax = 0;
jitMaxSize = -1;
managementEnabled = false;
} else {
String threshold = SafePropertyAccessor.getProperty("jruby.jit.threshold");
String max = SafePropertyAccessor.getProperty("jruby.jit.max");
String maxSize = SafePropertyAccessor.getProperty("jruby.jit.maxsize");
if (COMPILE_EXCLUDE != null) {
String[] elements = COMPILE_EXCLUDE.split(",");
for (String element : elements) excludedMethods.add(element);
}
managementEnabled = SafePropertyAccessor.getBoolean("jruby.management.enabled", true);
runRubyInProcess = SafePropertyAccessor.getBoolean("jruby.launch.inproc", true);
boolean jitProperty = SafePropertyAccessor.getProperty("jruby.jit.enabled") != null;
if (jitProperty) {
error.print("jruby.jit.enabled property is deprecated; use jruby.compile.mode=(OFF|JIT|FORCE) for -C, default, and +C flags");
compileMode = SafePropertyAccessor.getBoolean("jruby.jit.enabled") ? CompileMode.JIT : CompileMode.OFF;
} else {
String jitModeProperty = SafePropertyAccessor.getProperty("jruby.compile.mode", "JIT");
if (jitModeProperty.equals("OFF")) {
compileMode = CompileMode.OFF;
} else if (jitModeProperty.equals("JIT")) {
compileMode = CompileMode.JIT;
} else if (jitModeProperty.equals("FORCE")) {
compileMode = CompileMode.FORCE;
} else {
error.print("jruby.compile.mode property must be OFF, JIT, FORCE, or unset; defaulting to JIT");
compileMode = CompileMode.JIT;
}
}
jitLogging = SafePropertyAccessor.getBoolean("jruby.jit.logging");
jitLoggingVerbose = SafePropertyAccessor.getBoolean("jruby.jit.logging.verbose");
String logEvery = SafePropertyAccessor.getProperty("jruby.jit.logEvery");
jitLogEvery = logEvery == null ? 0 : Integer.parseInt(logEvery);
jitThreshold = threshold == null ?
JIT_THRESHOLD : Integer.parseInt(threshold);
jitMax = max == null ?
JIT_MAX_METHODS_LIMIT : Integer.parseInt(max);
jitMaxSize = maxSize == null ?
JIT_MAX_SIZE_LIMIT : Integer.parseInt(maxSize);
}
// default ClassCache using jitMax as a soft upper bound
classCache = new ClassCache<Script>(loader, jitMax);
if (FORK_ENABLED) {
error.print("WARNING: fork is highly unlikely to be safe or stable on the JVM. Have fun!\n");
}
}
public LoadServiceCreator getLoadServiceCreator() {
return creator;
}
public void setLoadServiceCreator(LoadServiceCreator creator) {
this.creator = creator;
}
public LoadService createLoadService(Ruby runtime) {
return this.creator.create(runtime);
}
public String getBasicUsageHelp() {
StringBuilder sb = new StringBuilder();
sb
.append("Usage: jruby [switches] [--] [programfile] [arguments]\n")
.append(" -0[octal] specify record separator (\0, if no argument)\n")
.append(" -a autosplit mode with -n or -p (splits $_ into $F)\n")
.append(" -b benchmark mode, times the script execution\n")
.append(" -c check syntax only\n")
.append(" -Cdirectory cd to directory, before executing your script\n")
.append(" -d set debugging flags (set $DEBUG to true)\n")
.append(" -e 'command' one line of script. Several -e's allowed. Omit [programfile]\n")
.append(" -Fpattern split() pattern for autosplit (-a)\n")
//.append(" -i[extension] edit ARGV files in place (make backup if extension supplied)\n")
.append(" -Idirectory specify $LOAD_PATH directory (may be used more than once)\n")
.append(" -J[java option] pass an option on to the JVM (e.g. -J-Xmx512m)\n")
.append(" use --properties to list JRuby properties\n")
.append(" run 'java -help' for a list of other Java options\n")
.append(" -Kkcode specifies code-set (e.g. -Ku for Unicode\n")
.append(" -l enable line ending processing\n")
.append(" -n assume 'while gets(); ... end' loop around your script\n")
.append(" -p assume loop like -n but print line also like sed\n")
.append(" -rlibrary require the library, before executing your script\n")
.append(" -s enable some switch parsing for switches after script name\n")
.append(" -S look for the script in bin or using PATH environment variable\n")
.append(" -T[level] turn on tainting checks\n")
.append(" -v print version number, then turn on verbose mode\n")
.append(" -w turn warnings on for your script\n")
.append(" -W[level] set warning level; 0=silence, 1=medium, 2=verbose (default)\n")
//.append(" -x[directory] strip off text before #!ruby line and perhaps cd to directory\n")
.append(" -X[option] enable extended option (omit option to list)\n")
.append(" --copyright print the copyright\n")
.append(" --debug sets the execution mode most suitable for debugger functionality\n")
.append(" --jdb runs JRuby process under JDB\n")
.append(" --properties List all configuration Java properties (pass -J-Dproperty=value)\n")
.append(" --sample run with profiling using the JVM's sampling profiler\n")
.append(" --client use the non-optimizing \"client\" JVM (improves startup; default)\n")
.append(" --server use the optimizing \"server\" JVM (improves perf)\n")
.append(" --manage enable remote JMX management and monitoring of the VM and JRuby\n")
.append(" --1.8 specify Ruby 1.8.x compatibility (default)\n")
.append(" --1.9 specify Ruby 1.9.x compatibility\n")
.append(" --bytecode show the JVM bytecode produced by compiling specified code\n")
.append(" --version print the version\n");
return sb.toString();
}
public String getExtendedHelp() {
StringBuilder sb = new StringBuilder();
sb
.append("These flags are for extended JRuby options.\n")
.append("Specify them by passing -X<option>\n")
.append(" -O run with ObjectSpace disabled (default; improves performance)\n")
.append(" +O run with ObjectSpace enabled (reduces performance)\n")
.append(" -C disable all compilation\n")
.append(" +C force compilation of all scripts before they are run (except eval)\n")
.append(" -y read a YARV-compiled Ruby script and run that (EXPERIMENTAL)\n")
.append(" -Y compile a Ruby script into YARV bytecodes and run this (EXPERIMENTAL)\n")
.append(" -R read a Rubinius-compiled Ruby script and run that (EXPERIMENTAL)\n");
return sb.toString();
}
public String getPropertyHelp() {
StringBuilder sb = new StringBuilder();
sb
.append("These properties can be used to alter runtime behavior for perf or compatibility.\n")
.append("Specify them by passing -J-D<property>=<value>\n")
.append("\nCOMPILER SETTINGS:\n")
.append(" jruby.compile.mode=JIT|FORCE|OFF\n")
.append(" Set compilation mode. JIT is default; FORCE compiles all, OFF disables\n")
.append(" jruby.compile.fastest=true|false\n")
.append(" (EXPERIMENTAL) Turn on all experimental compiler optimizations\n")
.append(" jruby.compile.boxed=true|false\n")
.append(" (EXPERIMENTAL) Use boxed variables; this can speed up some methods. Default is false\n")
.append(" jruby.compile.frameless=true|false\n")
.append(" (EXPERIMENTAL) Turn on frameless compilation where possible\n")
.append(" jruby.compile.positionless=true|false\n")
.append(" (EXPERIMENTAL) Turn on compilation that avoids updating Ruby position info. Default is false\n")
.append(" jruby.compile.threadless=true|false\n")
.append(" (EXPERIMENTAL) Turn on compilation without polling for \"unsafe\" thread events. Default is false\n")
.append(" jruby.compile.fastops=true|false\n")
.append(" (EXPERIMENTAL) Turn on fast operators for Fixnum. Default is false\n")
.append(" jruby.compile.chainsize=<line count>\n")
.append(" Set the number of lines at which compiled bodies are \"chained\". Default is " + CHAINED_COMPILE_LINE_COUNT_DEFAULT + "\n")
.append(" jruby.compile.lazyHandles=true|false\n")
.append(" Generate method bindings (handles) for compiled methods lazily. Default is false.")
.append("\nJIT SETTINGS:\n")
.append(" jruby.jit.threshold=<invocation count>\n")
.append(" Set the JIT threshold to the specified method invocation count. Default is " + JIT_THRESHOLD + ".\n")
.append(" jruby.jit.max=<method count>\n")
.append(" Set the max count of active methods eligible for JIT-compilation.\n")
.append(" Default is " + JIT_MAX_METHODS_LIMIT + " per runtime. A value of 0 disables JIT, -1 disables max.\n")
.append(" jruby.jit.maxsize=<jitted method size (full .class)>\n")
.append(" Set the maximum full-class byte size allowed for jitted methods. Default is Integer.MAX_VALUE\n")
.append(" jruby.jit.logging=true|false\n")
.append(" Enable JIT logging (reports successful compilation). Default is false\n")
.append(" jruby.jit.logging.verbose=true|false\n")
.append(" Enable verbose JIT logging (reports failed compilation). Default is false\n")
.append(" jruby.jit.logEvery=<method count>\n")
.append(" Log a message every n methods JIT compiled. Default is 0 (off).\n")
.append(" jruby.jit.exclude=<ClsOrMod,ClsOrMod::method_name,-::method_name>\n")
.append(" Exclude methods from JIT by class/module short name, c/m::method_name,\n")
.append(" or -::method_name for anon/singleton classes/modules. Comma-delimited.\n")
.append("\nNATIVE SUPPORT:\n")
.append(" jruby.native.enabled=true|false\n")
.append(" Enable/disable native extensions (like JNA for non-Java APIs; Default is true\n")
.append(" (This affects all JRuby instances in a given JVM)\n")
.append(" jruby.native.verbose=true|false\n")
.append(" Enable verbose logging of native extension loading. Default is false.\n")
.append(" jruby.fork.enabled=true|false\n")
.append(" (EXPERIMENTAL, maybe dangerous) Enable fork(2) on platforms that support it.\n")
.append("\nTHREAD POOLING:\n")
.append(" jruby.thread.pool.enabled=true|false\n")
.append(" Enable reuse of native backing threads via a thread pool. Default is false.\n")
.append(" jruby.thread.pool.min=<min thread count>\n")
.append(" The minimum number of threads to keep alive in the pool. Default is 0.\n")
.append(" jruby.thread.pool.max=<max thread count>\n")
.append(" The maximum number of threads to allow in the pool. Default is unlimited.\n")
.append(" jruby.thread.pool.ttl=<time to live, in seconds>\n")
.append(" The maximum number of seconds to keep alive an idle thread. Default is 60.\n")
.append("\nMISCELLANY:\n")
.append(" jruby.compat.version=RUBY1_8|RUBY1_9\n")
.append(" Specify the major Ruby version to be compatible with; Default is RUBY1_8\n")
.append(" jruby.objectspace.enabled=true|false\n")
.append(" Enable or disable ObjectSpace.each_object (default is disabled)\n")
.append(" jruby.launch.inproc=true|false\n")
.append(" Set in-process launching of e.g. system('ruby ...'). Default is true\n")
.append(" jruby.bytecode.version=1.5|1.6\n")
.append(" Set bytecode version for JRuby to generate. Default is current JVM version.\n")
.append(" jruby.management.enabled=true|false\n")
.append(" Set whether JMX management is enabled. Default is true.\n")
.append(" jruby.debug.fullTrace=true|false\n")
.append(" Set whether full traces are enabled (c-call/c-return). Default is false.\n");
return sb.toString();
}
public String getVersionString() {
String ver = Constants.RUBY_VERSION;
switch (compatVersion) {
case RUBY1_8:
ver = Constants.RUBY_VERSION;
break;
case RUBY1_9:
ver = Constants.RUBY1_9_VERSION;
break;
}
String fullVersion = String.format(
"jruby %s (ruby %s patchlevel %s) (%s rev %s) [%s-java]\n",
Constants.VERSION, ver, Constants.RUBY_PATCHLEVEL,
Constants.COMPILE_DATE, Constants.REVISION,
SafePropertyAccessor.getProperty("os.arch", "unknown")
);
return fullVersion;
}
public String getCopyrightString() {
return "JRuby - Copyright (C) 2001-2008 The JRuby Community (and contribs)\n";
}
public void processArguments(String[] arguments) {
new ArgumentProcessor(arguments).processArguments();
}
public CompileMode getCompileMode() {
return compileMode;
}
public void setCompileMode(CompileMode compileMode) {
this.compileMode = compileMode;
}
public boolean isJitLogging() {
return jitLogging;
}
public boolean isJitLoggingVerbose() {
return jitLoggingVerbose;
}
public int getJitLogEvery() {
return jitLogEvery;
}
public boolean isSamplingEnabled() {
return samplingEnabled;
}
public int getJitThreshold() {
return jitThreshold;
}
public int getJitMax() {
return jitMax;
}
public int getJitMaxSize() {
return jitMaxSize;
}
public boolean isRunRubyInProcess() {
return runRubyInProcess;
}
public void setRunRubyInProcess(boolean flag) {
this.runRubyInProcess = flag;
}
public void setInput(InputStream newInput) {
input = newInput;
}
public InputStream getInput() {
return input;
}
public CompatVersion getCompatVersion() {
return compatVersion;
}
public void setOutput(PrintStream newOutput) {
output = newOutput;
}
public PrintStream getOutput() {
return output;
}
public void setError(PrintStream newError) {
error = newError;
}
public PrintStream getError() {
return error;
}
public void setCurrentDirectory(String newCurrentDirectory) {
currentDirectory = newCurrentDirectory;
}
public String getCurrentDirectory() {
return currentDirectory;
}
public void setProfile(Profile newProfile) {
profile = newProfile;
}
public Profile getProfile() {
return profile;
}
public void setObjectSpaceEnabled(boolean newObjectSpaceEnabled) {
objectSpaceEnabled = newObjectSpaceEnabled;
}
public boolean isObjectSpaceEnabled() {
return objectSpaceEnabled;
}
public void setEnvironment(Map newEnvironment) {
environment = newEnvironment;
}
public Map getEnvironment() {
return environment;
}
public ClassLoader getLoader() {
return loader;
}
public void setLoader(ClassLoader loader) {
// Setting the loader needs to reset the class cache
if(this.loader != loader) {
this.classCache = new ClassCache<Script>(loader, this.classCache.getMax());
}
this.loader = loader;
}
public String[] getArgv() {
return argv;
}
public void setArgv(String[] argv) {
this.argv = argv;
}
public String getJRubyHome() {
if (jrubyHome == null) {
if (Ruby.isSecurityRestricted()) {
return "SECURITY RESTRICTED";
}
jrubyHome = verifyHome(SafePropertyAccessor.getProperty("jruby.home",
SafePropertyAccessor.getProperty("user.home") + "/.jruby"));
try {
// This comment also in rbConfigLibrary
// Our shell scripts pass in non-canonicalized paths, but even if we didn't
// anyone who did would become unhappy because Ruby apps expect no relative
// operators in the pathname (rubygems, for example).
jrubyHome = new NormalizedFile(jrubyHome).getCanonicalPath();
} catch (IOException e) { }
jrubyHome = new NormalizedFile(jrubyHome).getAbsolutePath();
}
return jrubyHome;
}
public void setJRubyHome(String home) {
jrubyHome = verifyHome(home);
}
// We require the home directory to be absolute
private String verifyHome(String home) {
if (home.equals(".")) {
home = System.getProperty("user.dir");
}
if (!home.startsWith("file:")) {
NormalizedFile f = new NormalizedFile(home);
if (!f.isAbsolute()) {
home = f.getAbsolutePath();
}
f.mkdirs();
}
return home;
}
private class ArgumentProcessor {
private String[] arguments;
private int argumentIndex = 0;
public ArgumentProcessor(String[] arguments) {
this.arguments = arguments;
}
public void processArguments() {
while (argumentIndex < arguments.length && isInterpreterArgument(arguments[argumentIndex])) {
processArgument();
argumentIndex++;
}
if (!hasInlineScript && scriptFileName == null) {
if (argumentIndex < arguments.length) {
setScriptFileName(arguments[argumentIndex]); //consume the file name
argumentIndex++;
}
}
processArgv();
}
private void processArgv() {
List<String> arglist = new ArrayList<String>();
for (; argumentIndex < arguments.length; argumentIndex++) {
String arg = arguments[argumentIndex];
if (argvGlobalsOn && arg.startsWith("-")) {
arg = arg.substring(1);
if (arg.indexOf('=') > 0) {
String[] keyvalue = arg.split("=", 2);
optionGlobals.put(keyvalue[0], keyvalue[1]);
} else {
optionGlobals.put(arg, null);
}
} else {
argvGlobalsOn = false;
arglist.add(arg);
}
}
// Remaining arguments are for the script itself
argv = arglist.toArray(new String[arglist.size()]);
}
private boolean isInterpreterArgument(String argument) {
return (argument.charAt(0) == '-' || argument.charAt(0) == '+') && !endOfArguments;
}
private String getArgumentError(String additionalError) {
return "jruby: invalid argument\n" + additionalError + "\n";
}
private void processArgument() {
String argument = arguments[argumentIndex];
FOR : for (characterIndex = 1; characterIndex < argument.length(); characterIndex++) {
switch (argument.charAt(characterIndex)) {
case '0': {
String temp = grabOptionalValue();
if (null == temp) {
recordSeparator = "\u0000";
} else if (temp.equals("0")) {
recordSeparator = "\n\n";
} else if (temp.equals("777")) {
recordSeparator = "\uFFFF"; // Specify something that can't separate
} else {
try {
int val = Integer.parseInt(temp, 8);
recordSeparator = "" + (char) val;
} catch (Exception e) {
MainExitException mee = new MainExitException(1, getArgumentError(" -0 must be followed by either 0, 777, or a valid octal value"));
mee.setUsageError(true);
throw mee;
}
}
break FOR;
}
case 'a':
split = true;
break;
case 'b':
benchmarking = true;
break;
case 'c':
shouldCheckSyntax = true;
break;
case 'C':
try {
String saved = grabValue(getArgumentError(" -C must be followed by a directory expression"));
File base = new File(currentDirectory);
File newDir = new File(saved);
if (newDir.isAbsolute()) {
currentDirectory = newDir.getCanonicalPath();
} else {
currentDirectory = new File(base, newDir.getPath()).getCanonicalPath();
}
if (!(new File(currentDirectory).isDirectory())) {
MainExitException mee = new MainExitException(1, "jruby: Can't chdir to " + saved + " (fatal)");
mee.setUsageError(true);
throw mee;
}
} catch (IOException e) {
MainExitException mee = new MainExitException(1, getArgumentError(" -C must be followed by a valid directory"));
mee.setUsageError(true);
throw mee;
}
break;
case 'd':
debug = true;
verbose = Boolean.TRUE;
break;
case 'e':
inlineScript.append(grabValue(getArgumentError(" -e must be followed by an expression to evaluate")));
inlineScript.append('\n');
hasInlineScript = true;
break FOR;
case 'F':
inputFieldSeparator = grabValue(getArgumentError(" -F must be followed by a pattern for input field separation"));
break;
case 'h':
shouldPrintUsage = true;
shouldRunInterpreter = false;
break;
// FIXME: -i flag not supported
// case 'i' :
// break;
case 'I':
String s = grabValue(getArgumentError("-I must be followed by a directory name to add to lib path"));
String[] ls = s.split(java.io.File.pathSeparator);
for (int i = 0; i < ls.length; i++) {
loadPaths.add(ls[i]);
}
break FOR;
case 'K':
// FIXME: No argument seems to work for -K in MRI plus this should not
// siphon off additional args 'jruby -K ~/scripts/foo'. Also better error
// processing.
String eArg = grabValue(getArgumentError("provide a value for -K"));
kcode = KCode.create(null, eArg);
break;
case 'l':
processLineEnds = true;
break;
case 'n':
assumeLoop = true;
break;
case 'p':
assumePrinting = true;
assumeLoop = true;
break;
case 'r':
requiredLibraries.add(grabValue(getArgumentError("-r must be followed by a package to require")));
break FOR;
case 's' :
argvGlobalsOn = true;
break;
case 'S':
runBinScript();
break FOR;
case 'T' :{
String temp = grabOptionalValue();
int value = 1;
if(temp!=null) {
try {
value = Integer.parseInt(temp, 8);
} catch(Exception e) {
value = 1;
}
}
safeLevel = value;
break FOR;
}
case 'v':
verbose = Boolean.TRUE;
setShowVersion(true);
break;
case 'w':
verbose = Boolean.TRUE;
break;
case 'W': {
String temp = grabOptionalValue();
int value = 2;
if (null != temp) {
if (temp.equals("2")) {
value = 2;
} else if (temp.equals("1")) {
value = 1;
} else if (temp.equals("0")) {
value = 0;
} else {
MainExitException mee = new MainExitException(1, getArgumentError(" -W must be followed by either 0, 1, 2 or nothing"));
mee.setUsageError(true);
throw mee;
}
}
switch (value) {
case 0:
verbose = null;
break;
case 1:
verbose = Boolean.FALSE;
break;
case 2:
verbose = Boolean.TRUE;
break;
}
break FOR;
}
// FIXME: -x flag not supported
// case 'x' :
// break;
case 'X':
String extendedOption = grabOptionalValue();
if (extendedOption == null) {
throw new MainExitException(0, "jruby: missing extended option, listing available options\n" + getExtendedHelp());
} else if (extendedOption.equals("-O")) {
objectSpaceEnabled = false;
} else if (extendedOption.equals("+O")) {
objectSpaceEnabled = true;
} else if (extendedOption.equals("-C")) {
compileMode = CompileMode.OFF;
} else if (extendedOption.equals("+C")) {
compileMode = CompileMode.FORCE;
} else if (extendedOption.equals("-y")) {
yarv = true;
} else if (extendedOption.equals("-Y")) {
yarvCompile = true;
} else if (extendedOption.equals("-R")) {
rubinius = true;
} else {
MainExitException mee =
new MainExitException(1, "jruby: invalid extended option " + extendedOption + " (-X will list valid options)\n");
mee.setUsageError(true);
throw mee;
}
break FOR;
case '-':
if (argument.equals("--command") || argument.equals("--bin")) {
characterIndex = argument.length();
runBinScript();
break;
} else if (argument.equals("--compat")) {
characterIndex = argument.length();
compatVersion = CompatVersion.getVersionFromString(grabValue(getArgumentError("--compat must be RUBY1_8 or RUBY1_9")));
if (compatVersion == null) {
compatVersion = CompatVersion.RUBY1_8;
}
break FOR;
} else if (argument.equals("--copyright")) {
setShowCopyright(true);
shouldRunInterpreter = false;
break FOR;
} else if (argument.equals("--debug")) {
compileMode = CompileMode.OFF;
FULL_TRACE_ENABLED = true;
System.setProperty("jruby.reflection", "true");
break FOR;
} else if (argument.equals("--jdb")) {
debug = true;
verbose = Boolean.TRUE;
break;
} else if (argument.equals("--help")) {
shouldPrintUsage = true;
shouldRunInterpreter = false;
break;
} else if (argument.equals("--properties")) {
shouldPrintProperties = true;
shouldRunInterpreter = false;
break;
} else if (argument.equals("--version")) {
setShowVersion(true);
break FOR;
} else if (argument.equals("--bytecode")) {
setShowBytecode(true);
break FOR;
} else {
if (argument.equals("--")) {
// ruby interpreter compatibilty
// Usage: ruby [switches] [--] [programfile] [arguments])
endOfArguments = true;
break;
}
}
default:
throw new MainExitException(1, "jruby: unknown option " + argument);
}
}
}
private void runBinScript() {
String scriptName = grabValue("jruby: provide a bin script to execute");
if (scriptName.equals("irb")) {
scriptName = "jirb";
}
scriptFileName = scriptName;
if (!new File(scriptFileName).exists()) {
try {
String jrubyHome = JRubyFile.create(System.getProperty("user.dir"), JRubyFile.getFileProperty("jruby.home")).getCanonicalPath();
scriptFileName = JRubyFile.create(jrubyHome + JRubyFile.separator + "bin", scriptName).getCanonicalPath();
} catch (IOException io) {
MainExitException mee = new MainExitException(1, "jruby: Can't determine script filename");
mee.setUsageError(true);
throw mee;
}
}
// route 'gem' through ruby code in case we're running out of the complete jar
if (scriptName.equals("gem") || !new File(scriptFileName).exists()) {
requiredLibraries.add("jruby/commands");
inlineScript.append("JRuby::Commands." + scriptName);
inlineScript.append("\n");
hasInlineScript = true;
}
endOfArguments = true;
}
private String grabValue(String errorMessage) {
characterIndex++;
if (characterIndex < arguments[argumentIndex].length()) {
return arguments[argumentIndex].substring(characterIndex);
}
argumentIndex++;
if (argumentIndex < arguments.length) {
return arguments[argumentIndex];
}
MainExitException mee = new MainExitException(1, errorMessage);
mee.setUsageError(true);
throw mee;
}
private String grabOptionalValue() {
characterIndex++;
if (characterIndex < arguments[argumentIndex].length()) {
return arguments[argumentIndex].substring(characterIndex);
}
return null;
}
}
public byte[] inlineScript() {
return inlineScript.toString().getBytes();
}
public List<String> requiredLibraries() {
return requiredLibraries;
}
public List<String> loadPaths() {
return loadPaths;
}
public boolean shouldRunInterpreter() {
if(isShowVersion() && (hasInlineScript || scriptFileName != null)) {
return true;
}
return isShouldRunInterpreter();
}
public boolean shouldPrintUsage() {
return shouldPrintUsage;
}
public boolean shouldPrintProperties() {
return shouldPrintProperties;
}
private boolean isSourceFromStdin() {
return getScriptFileName() == null;
}
public boolean isInlineScript() {
return hasInlineScript;
}
public InputStream getScriptSource() {
try {
// KCode.NONE is used because KCODE does not affect parse in Ruby 1.8
// if Ruby 2.0 encoding pragmas are implemented, this will need to change
if (hasInlineScript) {
return new ByteArrayInputStream(inlineScript());
} else if (isSourceFromStdin()) {
// can't use -v and stdin
if (isShowVersion()) {
return null;
}
return getInput();
} else {
File file = JRubyFile.create(getCurrentDirectory(), getScriptFileName());
return new BufferedInputStream(new FileInputStream(file));
}
} catch (IOException e) {
throw new MainExitException(1, "Error opening script file: " + e.getMessage());
}
}
public String displayedFileName() {
if (hasInlineScript) {
if (scriptFileName != null) {
return scriptFileName;
} else {
return "-e";
}
} else if (isSourceFromStdin()) {
return "-";
} else {
return getScriptFileName();
}
}
private void setScriptFileName(String scriptFileName) {
this.scriptFileName = scriptFileName;
}
public String getScriptFileName() {
return scriptFileName;
}
public boolean isBenchmarking() {
return benchmarking;
}
public boolean isAssumeLoop() {
return assumeLoop;
}
public boolean isAssumePrinting() {
return assumePrinting;
}
public boolean isProcessLineEnds() {
return processLineEnds;
}
public boolean isSplit() {
return split;
}
public boolean isVerbose() {
return verbose == Boolean.TRUE;
}
public Boolean getVerbose() {
return verbose;
}
public boolean isDebug() {
return debug;
}
public boolean isShowVersion() {
return showVersion;
}
public boolean isShowBytecode() {
return showBytecode;
}
public boolean isShowCopyright() {
return showCopyright;
}
protected void setShowVersion(boolean showVersion) {
this.showVersion = showVersion;
}
protected void setShowBytecode(boolean showBytecode) {
this.showBytecode = showBytecode;
}
protected void setShowCopyright(boolean showCopyright) {
this.showCopyright = showCopyright;
}
public boolean isShouldRunInterpreter() {
return shouldRunInterpreter;
}
public boolean isShouldCheckSyntax() {
return shouldCheckSyntax;
}
public boolean isYARVEnabled() {
return yarv;
}
public String getInputFieldSeparator() {
return inputFieldSeparator;
}
public boolean isRubiniusEnabled() {
return rubinius;
}
public boolean isYARVCompileEnabled() {
return yarvCompile;
}
public KCode getKCode() {
return kcode;
}
public String getRecordSeparator() {
return recordSeparator;
}
public int getSafeLevel() {
return safeLevel;
}
public void setRecordSeparator(String recordSeparator) {
this.recordSeparator = recordSeparator;
}
public ClassCache getClassCache() {
return classCache;
}
public void setClassCache(ClassCache classCache) {
this.classCache = classCache;
}
public Map getOptionGlobals() {
return optionGlobals;
}
public boolean isManagementEnabled() {
return managementEnabled;
}
public Set getExcludedMethods() {
return excludedMethods;
}
}
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockBody;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
/** Implementation of the Integer class.
*
* @author jpetersen
*/
@JRubyClass(name="Integer", parent="Numeric", include="Precision")
public abstract class RubyInteger extends RubyNumeric {
public static RubyClass createIntegerClass(Ruby runtime) {
RubyClass integer = runtime.defineClass("Integer", runtime.getNumeric(),
ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setInteger(integer);
integer.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyInteger;
}
};
integer.getSingletonClass().undefineMethod("new");
integer.includeModule(runtime.getPrecision());
integer.defineAnnotatedMethods(RubyInteger.class);
return integer;
}
public RubyInteger(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass);
}
public RubyInteger(Ruby runtime, RubyClass rubyClass, boolean useObjectSpace) {
super(runtime, rubyClass, useObjectSpace);
}
public RubyInteger convertToInteger() {
return this;
}
// conversion
protected RubyFloat toFloat() {
return RubyFloat.newFloat(getRuntime(), getDoubleValue());
}
/* ================
* Instance Methods
* ================
*/
/** int_int_p
*
*/
@JRubyMethod(name = "integer?")
public IRubyObject integer_p() {
return getRuntime().getTrue();
}
/** int_upto
*
*/
@JRubyMethod(name = "upto", frame = true)
public IRubyObject upto(ThreadContext context, IRubyObject to, Block block) {
final Ruby runtime = getRuntime();
if (this instanceof RubyFixnum && to instanceof RubyFixnum) {
RubyFixnum toFixnum = (RubyFixnum) to;
final long toValue = toFixnum.getLongValue();
final long fromValue = getLongValue();
if (block.getBody().getArgumentType() == BlockBody.ZERO_ARGS) {
final IRubyObject nil = runtime.getNil();
for (long i = fromValue; i <= toValue; i++) {
block.yield(context, nil);
}
} else {
for (long i = fromValue; i <= toValue; i++) {
block.yield(context, RubyFixnum.newFixnum(runtime, i));
}
}
} else {
RubyNumeric i = this;
while (true) {
if (i.callMethod(context, MethodIndex.OP_GT, ">", to).isTrue()) {
break;
}
block.yield(context, i);
i = (RubyNumeric) i.callMethod(context, MethodIndex.OP_PLUS, "+", RubyFixnum.one(runtime));
}
}
return this;
}
/** int_downto
*
*/
// TODO: Make callCoerced work in block context...then fix downto, step, and upto.
@JRubyMethod(name = "downto", frame = true)
public IRubyObject downto(ThreadContext context, IRubyObject to, Block block) {
final Ruby runtime = getRuntime();
if (this instanceof RubyFixnum && to instanceof RubyFixnum) {
RubyFixnum toFixnum = (RubyFixnum) to;
final long toValue = toFixnum.getLongValue();
if (block.getBody().getArgumentType() == BlockBody.ZERO_ARGS) {
final IRubyObject nil = runtime.getNil();
for (long i = getLongValue(); i >= toValue; i--) {
block.yield(context, nil);
}
} else {
for (long i = getLongValue(); i >= toValue; i--) {
block.yield(context, RubyFixnum.newFixnum(getRuntime(), i));
}
}
} else {
RubyNumeric i = this;
while (true) {
if (i.callMethod(context, MethodIndex.OP_LT, "<", to).isTrue()) {
break;
}
block.yield(context, i);
i = (RubyNumeric) i.callMethod(context, MethodIndex.OP_MINUS, "-", RubyFixnum.one(getRuntime()));
}
}
return this;
}
@JRubyMethod(name = "times", frame = true)
public IRubyObject times(ThreadContext context, Block block) {
final Ruby runtime = context.getRuntime();
if (this instanceof RubyFixnum) {
final long value = getLongValue();
if (block.getBody().getArgumentType() == BlockBody.ZERO_ARGS) {
final IRubyObject nil = runtime.getNil();
for (long i = 0; i < value; i++) {
block.yield(context, nil);
}
} else {
for (long i = 0; i < value; i++) {
block.yield(context, RubyFixnum.newFixnum(runtime, i));
}
}
} else {
RubyNumeric i = RubyFixnum.zero(runtime);
while (true) {
if (!i.callMethod(context, MethodIndex.OP_LT, "<", this).isTrue()) {
break;
}
block.yield(context, i);
i = (RubyNumeric) i.callMethod(context, MethodIndex.OP_PLUS, "+", RubyFixnum.one(runtime));
}
}
return this;
}
/** int_succ
*
*/
@JRubyMethod(name = {"succ", "next"})
public IRubyObject succ(ThreadContext context) {
if (this instanceof RubyFixnum) {
return RubyFixnum.newFixnum(getRuntime(), getLongValue() + 1L);
} else {
return callMethod(context, MethodIndex.OP_PLUS, "+", RubyFixnum.one(getRuntime()));
}
}
/** int_chr
*
*/
@JRubyMethod(name = "chr")
public RubyString chr() {
if (getLongValue() < 0 || getLongValue() > 0xff) {
throw getRuntime().newRangeError(this.toString() + " out of char range");
}
return RubyString.newString(getRuntime(), new ByteList(new byte[]{(byte)getLongValue()}, false));
}
/** int_to_i
*
*/
@JRubyMethod(name = {"to_i", "to_int", "floor", "ceil", "round", "truncate"})
public RubyInteger to_i() {
return this;
}
/** integer_to_r
*
*/
@JRubyMethod(name = "to_r", compat = CompatVersion.RUBY1_9)
public IRubyObject to_r(ThreadContext context) {
return RubyRational.newRationalCanonicalize(context, this);
}
@JRubyMethod(name = {"odd?"})
public static RubyBoolean odd_p(ThreadContext context, IRubyObject recv) {
if(recv.callMethod(context, "%", recv.getRuntime().newFixnum(2)) != RubyFixnum.zero(recv.getRuntime())) {
return recv.getRuntime().getTrue();
}
return recv.getRuntime().getFalse();
}
@JRubyMethod(name = {"even?"})
public static RubyBoolean even_p(ThreadContext context, IRubyObject recv) {
if(recv.callMethod(context, "%", recv.getRuntime().newFixnum(2)) == RubyFixnum.zero(recv.getRuntime())) {
return recv.getRuntime().getTrue();
}
return recv.getRuntime().getFalse();
}
@JRubyMethod
public static IRubyObject pred(ThreadContext context, IRubyObject recv) {
return recv.callMethod(context, "-", recv.getRuntime().newFixnum(1));
}
/* ================
* Singleton Methods
* ================
*/
/** rb_int_induced_from
*
*/
@JRubyMethod(name = "induced_from", meta = true)
public static IRubyObject induced_from(ThreadContext context, IRubyObject recv, IRubyObject other) {
if (other instanceof RubyFixnum || other instanceof RubyBignum) {
return other;
} else if (other instanceof RubyFloat || other instanceof RubyRational) {
return other.callMethod(context, MethodIndex.TO_I, "to_i");
} else {
throw recv.getRuntime().newTypeError(
"failed to convert " + other.getMetaClass().getName() + " into Integer");
}
}
}
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2006 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Evan Buswell <ebuswell@gmail.com>
* Copyright (C) 2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.EOFException;
import java.io.FileDescriptor;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.Pipe;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.jruby.anno.FrameField;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.posix.util.FieldAccess;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.io.Stream;
import org.jruby.util.io.ModeFlags;
import org.jruby.util.ShellLauncher;
import org.jruby.util.TypeConverter;
import org.jruby.util.io.BadDescriptorException;
import org.jruby.util.io.ChannelStream;
import org.jruby.util.io.InvalidValueException;
import org.jruby.util.io.PipeException;
import org.jruby.util.io.FileExistsException;
import org.jruby.util.io.STDIO;
import org.jruby.util.io.OpenFile;
import org.jruby.util.io.ChannelDescriptor;
import static org.jruby.CompatVersion.*;
/**
*
* @author jpetersen
*/
@JRubyClass(name="IO", include="Enumerable")
public class RubyIO extends RubyObject {
protected OpenFile openFile;
protected List<RubyThread> blockingThreads;
public void registerDescriptor(ChannelDescriptor descriptor) {
getRuntime().getDescriptors().put(new Integer(descriptor.getFileno()), new WeakReference<ChannelDescriptor>(descriptor));
}
public void unregisterDescriptor(int aFileno) {
getRuntime().getDescriptors().remove(new Integer(aFileno));
}
public ChannelDescriptor getDescriptorByFileno(int aFileno) {
Reference<ChannelDescriptor> reference = getRuntime().getDescriptors().get(new Integer(aFileno));
if (reference == null) {
return null;
}
return reference.get();
}
// FIXME can't use static; would interfere with other runtimes in the same JVM
protected static AtomicInteger filenoIndex = new AtomicInteger(2);
public static int getNewFileno() {
return filenoIndex.incrementAndGet();
}
// This should only be called by this and RubyFile.
// It allows this object to be created without a IOHandler.
public RubyIO(Ruby runtime, RubyClass type) {
super(runtime, type);
openFile = new OpenFile();
}
public RubyIO(Ruby runtime, OutputStream outputStream) {
super(runtime, runtime.getIO());
// We only want IO objects with valid streams (better to error now).
if (outputStream == null) {
throw runtime.newIOError("Opening invalid stream");
}
openFile = new OpenFile();
try {
openFile.setMainStream(new ChannelStream(runtime, new ChannelDescriptor(Channels.newChannel(outputStream), getNewFileno(), new FileDescriptor())));
} catch (InvalidValueException e) {
throw getRuntime().newErrnoEINVALError();
}
openFile.setMode(OpenFile.WRITABLE | OpenFile.APPEND);
registerDescriptor(openFile.getMainStream().getDescriptor());
}
public RubyIO(Ruby runtime, InputStream inputStream) {
super(runtime, runtime.getIO());
if (inputStream == null) {
throw runtime.newIOError("Opening invalid stream");
}
openFile = new OpenFile();
try {
openFile.setMainStream(new ChannelStream(runtime, new ChannelDescriptor(Channels.newChannel(inputStream), getNewFileno(), new FileDescriptor())));
} catch (InvalidValueException e) {
throw getRuntime().newErrnoEINVALError();
}
openFile.setMode(OpenFile.READABLE);
registerDescriptor(openFile.getMainStream().getDescriptor());
}
public RubyIO(Ruby runtime, Channel channel) {
super(runtime, runtime.getIO());
// We only want IO objects with valid streams (better to error now).
if (channel == null) {
throw runtime.newIOError("Opening invalid stream");
}
openFile = new OpenFile();
try {
openFile.setMainStream(new ChannelStream(runtime, new ChannelDescriptor(channel, getNewFileno(), new FileDescriptor())));
} catch (InvalidValueException e) {
throw getRuntime().newErrnoEINVALError();
}
openFile.setMode(openFile.getMainStream().getModes().getOpenFileFlags());
registerDescriptor(openFile.getMainStream().getDescriptor());
}
public RubyIO(Ruby runtime, ShellLauncher.POpenProcess process, ModeFlags modes) {
super(runtime, runtime.getIO());
openFile = new OpenFile();
openFile.setMode(modes.getOpenFileFlags() | OpenFile.SYNC);
openFile.setProcess(process);
try {
if (openFile.isReadable()) {
Channel inChannel;
if (process.getInput() != null) {
// NIO-based
inChannel = process.getInput();
} else {
// Stream-based
inChannel = Channels.newChannel(process.getInputStream());
}
ChannelDescriptor main = new ChannelDescriptor(
inChannel,
getNewFileno(),
new FileDescriptor());
main.setCanBeSeekable(false);
openFile.setMainStream(new ChannelStream(getRuntime(), main));
registerDescriptor(main);
}
if (openFile.isWritable()) {
Channel outChannel;
if (process.getOutput() != null) {
// NIO-based
outChannel = process.getOutput();
} else {
outChannel = Channels.newChannel(process.getOutputStream());
}
ChannelDescriptor pipe = new ChannelDescriptor(
outChannel,
getNewFileno(),
new FileDescriptor());
pipe.setCanBeSeekable(false);
if (openFile.getMainStream() != null) {
openFile.setPipeStream(new ChannelStream(getRuntime(), pipe));
} else {
openFile.setMainStream(new ChannelStream(getRuntime(), pipe));
}
registerDescriptor(pipe);
}
} catch (InvalidValueException e) {
throw getRuntime().newErrnoEINVALError();
}
}
public RubyIO(Ruby runtime, STDIO stdio) {
super(runtime, runtime.getIO());
openFile = new OpenFile();
try {
switch (stdio) {
case IN:
openFile.setMainStream(
new ChannelStream(
runtime,
// special constructor that accepts stream, not channel
new ChannelDescriptor(runtime.getIn(), 0, new ModeFlags(ModeFlags.RDONLY), FileDescriptor.in),
FileDescriptor.in));
break;
case OUT:
openFile.setMainStream(
new ChannelStream(
runtime,
new ChannelDescriptor(Channels.newChannel(runtime.getOut()), 1, new ModeFlags(ModeFlags.WRONLY | ModeFlags.APPEND), FileDescriptor.out),
FileDescriptor.out));
openFile.getMainStream().setSync(true);
break;
case ERR:
openFile.setMainStream(
new ChannelStream(
runtime,
new ChannelDescriptor(Channels.newChannel(runtime.getErr()), 2, new ModeFlags(ModeFlags.WRONLY | ModeFlags.APPEND), FileDescriptor.err),
FileDescriptor.err));
openFile.getMainStream().setSync(true);
break;
}
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
}
openFile.setMode(openFile.getMainStream().getModes().getOpenFileFlags());
registerDescriptor(openFile.getMainStream().getDescriptor());
}
public static RubyIO newIO(Ruby runtime, Channel channel) {
return new RubyIO(runtime, channel);
}
public OpenFile getOpenFile() {
return openFile;
}
protected OpenFile getOpenFileChecked() {
openFile.checkClosed(getRuntime());
return openFile;
}
private static ObjectAllocator IO_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyIO(runtime, klass);
}
};
public static RubyClass createIOClass(Ruby runtime) {
RubyClass ioClass = runtime.defineClass("IO", runtime.getObject(), IO_ALLOCATOR);
ioClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyIO;
}
};
ioClass.includeModule(runtime.getEnumerable());
// TODO: Implement tty? and isatty. We have no real capability to
// determine this from java, but if we could set tty status, then
// we could invoke jruby differently to allow stdin to return true
// on this. This would allow things like cgi.rb to work properly.
ioClass.defineAnnotatedMethods(RubyIO.class);
// Constants for seek
ioClass.fastSetConstant("SEEK_SET", runtime.newFixnum(Stream.SEEK_SET));
ioClass.fastSetConstant("SEEK_CUR", runtime.newFixnum(Stream.SEEK_CUR));
ioClass.fastSetConstant("SEEK_END", runtime.newFixnum(Stream.SEEK_END));
return ioClass;
}
public OutputStream getOutStream() {
return getOpenFileChecked().getMainStream().newOutputStream();
}
public InputStream getInStream() {
return getOpenFileChecked().getMainStream().newInputStream();
}
public Channel getChannel() {
if (getOpenFileChecked().getMainStream() instanceof ChannelStream) {
return ((ChannelStream) openFile.getMainStream()).getDescriptor().getChannel();
} else {
return null;
}
}
public Stream getHandler() {
return getOpenFileChecked().getMainStream();
}
@JRubyMethod(name = "reopen", required = 1, optional = 1)
public IRubyObject reopen(ThreadContext context, IRubyObject[] args) throws InvalidValueException {
Ruby runtime = context.getRuntime();
if (args.length < 1) {
throw runtime.newArgumentError("wrong number of arguments");
}
IRubyObject tmp = TypeConverter.convertToTypeWithCheck(args[0], runtime.getIO(),
MethodIndex.getIndex("to_io"), "to_io");
if (!tmp.isNil()) {
try {
RubyIO ios = (RubyIO) tmp;
if (ios.openFile == this.openFile) {
return this;
}
OpenFile originalFile = ios.getOpenFileChecked();
OpenFile selfFile = getOpenFileChecked();
long pos = 0;
if (originalFile.isReadable()) {
pos = originalFile.getMainStream().fgetpos();
}
if (originalFile.getPipeStream() != null) {
originalFile.getPipeStream().fflush();
} else if (originalFile.isWritable()) {
originalFile.getMainStream().fflush();
}
if (selfFile.isWritable()) {
selfFile.getWriteStream().fflush();
}
selfFile.setMode(originalFile.getMode());
selfFile.setProcess(originalFile.getProcess());
selfFile.setLineNumber(originalFile.getLineNumber());
selfFile.setPath(originalFile.getPath());
selfFile.setFinalizer(originalFile.getFinalizer());
ChannelDescriptor selfDescriptor = selfFile.getMainStream().getDescriptor();
ChannelDescriptor originalDescriptor = originalFile.getMainStream().getDescriptor();
// confirm we're not reopening self's channel
if (selfDescriptor.getChannel() != originalDescriptor.getChannel()) {
// check if we're a stdio IO, and ensure we're not badly mutilated
if (selfDescriptor.getFileno() >=0 && selfDescriptor.getFileno() <= 2) {
selfFile.getMainStream().clearerr();
// dup2 new fd into self to preserve fileno and references to it
originalDescriptor.dup2Into(selfDescriptor);
// re-register, since fileno points at something new now
registerDescriptor(selfDescriptor);
} else {
Stream pipeFile = selfFile.getPipeStream();
int mode = selfFile.getMode();
selfFile.getMainStream().fclose();
selfFile.setPipeStream(null);
// TODO: turn off readable? am I reading this right?
// This only seems to be used while duping below, since modes gets
// reset to actual modes afterward
//fptr->mode &= (m & FMODE_READABLE) ? ~FMODE_READABLE : ~FMODE_WRITABLE;
if (pipeFile != null) {
selfFile.setMainStream(ChannelStream.fdopen(runtime, originalDescriptor, new ModeFlags()));
selfFile.setPipeStream(pipeFile);
} else {
selfFile.setMainStream(
new ChannelStream(
runtime,
originalDescriptor.dup2(selfDescriptor.getFileno())));
// re-register the descriptor
registerDescriptor(selfFile.getMainStream().getDescriptor());
// since we're not actually duping the incoming channel into our handler, we need to
// copy the original sync behavior from the other handler
selfFile.getMainStream().setSync(selfFile.getMainStream().isSync());
}
selfFile.setMode(mode);
}
// TODO: anything threads attached to original fd are notified of the close...
// see rb_thread_fd_close
if (originalFile.isReadable() && pos >= 0) {
selfFile.seek(pos, Stream.SEEK_SET);
originalFile.seek(pos, Stream.SEEK_SET);
}
}
if (selfFile.getPipeStream() != null && selfDescriptor.getFileno() != selfFile.getPipeStream().getDescriptor().getFileno()) {
int fd = selfFile.getPipeStream().getDescriptor().getFileno();
if (originalFile.getPipeStream() == null) {
selfFile.getPipeStream().fclose();
selfFile.setPipeStream(null);
} else if (fd != originalFile.getPipeStream().getDescriptor().getFileno()) {
selfFile.getPipeStream().fclose();
ChannelDescriptor newFD2 = originalFile.getPipeStream().getDescriptor().dup2(fd);
selfFile.setPipeStream(ChannelStream.fdopen(runtime, newFD2, getIOModes(runtime, "w")));
// re-register, since fileno points at something new now
registerDescriptor(newFD2);
}
}
// TODO: restore binary mode
// if (fptr->mode & FMODE_BINMODE) {
// rb_io_binmode(io);
// }
// TODO: set our metaclass to target's class (i.e. scary!)
} catch (IOException ex) { // TODO: better error handling
throw runtime.newIOError("could not reopen: " + ex.getMessage());
} catch (BadDescriptorException ex) {
throw runtime.newIOError("could not reopen: " + ex.getMessage());
} catch (PipeException ex) {
throw runtime.newIOError("could not reopen: " + ex.getMessage());
}
} else {
IRubyObject pathString = args[0].convertToString();
// TODO: check safe, taint on incoming string
if (openFile == null) {
openFile = new OpenFile();
}
try {
ModeFlags modes;
if (args.length > 1) {
IRubyObject modeString = args[1].convertToString();
modes = getIOModes(runtime, modeString.toString());
openFile.setMode(modes.getOpenFileFlags());
} else {
modes = getIOModes(runtime, "r");
}
String path = pathString.toString();
// Ruby code frequently uses a platform check to choose "NUL:" on windows
// but since that check doesn't work well on JRuby, we help it out
openFile.setPath(path);
if (openFile.getMainStream() == null) {
try {
openFile.setMainStream(ChannelStream.fopen(runtime, path, modes));
} catch (FileExistsException fee) {
throw runtime.newErrnoEEXISTError(path);
}
registerDescriptor(openFile.getMainStream().getDescriptor());
if (openFile.getPipeStream() != null) {
openFile.getPipeStream().fclose();
unregisterDescriptor(openFile.getPipeStream().getDescriptor().getFileno());
openFile.setPipeStream(null);
}
return this;
} else {
// TODO: This is an freopen in MRI, this is close, but not quite the same
openFile.getMainStream().freopen(path, getIOModes(runtime, openFile.getModeAsString(runtime)));
// re-register
registerDescriptor(openFile.getMainStream().getDescriptor());
if (openFile.getPipeStream() != null) {
// TODO: pipe handler to be reopened with path and "w" mode
}
}
} catch (PipeException pe) {
throw runtime.newErrnoEPIPEError();
} catch (IOException ex) {
throw runtime.newIOErrorFromException(ex);
} catch (BadDescriptorException ex) {
throw runtime.newErrnoEBADFError();
} catch (InvalidValueException e) {
throw runtime.newErrnoEINVALError();
}
}
// A potentially previously close IO is being 'reopened'.
return this;
}
public static ModeFlags getIOModes(Ruby runtime, String modesString) throws InvalidValueException {
return new ModeFlags(getIOModesIntFromString(runtime, modesString));
}
public static int getIOModesIntFromString(Ruby runtime, String modesString) {
int modes = 0;
int length = modesString.length();
if (length == 0) {
throw runtime.newArgumentError("illegal access mode");
}
switch (modesString.charAt(0)) {
case 'r' :
modes |= ModeFlags.RDONLY;
break;
case 'a' :
modes |= ModeFlags.APPEND | ModeFlags.WRONLY | ModeFlags.CREAT;
break;
case 'w' :
modes |= ModeFlags.WRONLY | ModeFlags.TRUNC | ModeFlags.CREAT;
break;
default :
throw runtime.newArgumentError("illegal access mode " + modes);
}
for (int n = 1; n < length; n++) {
switch (modesString.charAt(n)) {
case 'b':
modes |= ModeFlags.BINARY;
break;
case '+':
modes = (modes & ~ModeFlags.ACCMODE) | ModeFlags.RDWR;
break;
default:
throw runtime.newArgumentError("illegal access mode " + modes);
}
}
return modes;
}
private static ByteList getSeparatorFromArgs(Ruby runtime, IRubyObject[] args, int idx) {
IRubyObject sepVal;
if (args.length > idx) {
sepVal = args[idx];
} else {
sepVal = runtime.getRecordSeparatorVar().get();
}
ByteList separator = sepVal.isNil() ? null : sepVal.convertToString().getByteList();
if (separator != null && separator.realSize == 0) {
separator = Stream.PARAGRAPH_DELIMETER;
}
return separator;
}
private ByteList getSeparatorForGets(Ruby runtime, IRubyObject[] args) {
return getSeparatorFromArgs(runtime, args, 0);
}
public IRubyObject getline(Ruby runtime, ByteList separator) {
try {
OpenFile myOpenFile = getOpenFileChecked();
myOpenFile.checkReadable(runtime);
myOpenFile.setReadBuffered();
boolean isParagraph = separator == Stream.PARAGRAPH_DELIMETER;
separator = (separator == Stream.PARAGRAPH_DELIMETER) ?
Stream.PARAGRAPH_SEPARATOR : separator;
if (isParagraph) {
swallow('\n');
}
if (separator == null) {
IRubyObject str = readAll(null);
if (((RubyString)str).getByteList().length() == 0) {
return runtime.getNil();
}
incrementLineno(runtime, myOpenFile);
return str;
} else if (separator.length() == 1) {
return getlineFast(runtime, separator.get(0));
} else {
Stream readStream = myOpenFile.getMainStream();
int c = -1;
int n = -1;
int newline = separator.get(separator.length() - 1) & 0xFF;
ByteList buf = new ByteList(0);
boolean update = false;
while (true) {
do {
readCheck(readStream);
readStream.clearerr();
try {
n = readStream.getline(buf, (byte) newline);
c = buf.length() > 0 ? buf.get(buf.length() - 1) & 0xff : -1;
} catch (EOFException e) {
n = -1;
}
if (n == -1) {
if (!readStream.isBlocking() && (readStream instanceof ChannelStream)) {
if(!(waitReadable(((ChannelStream)readStream).getDescriptor()))) {
throw runtime.newIOError("bad file descriptor: " + openFile.getPath());
}
continue;
} else {
break;
}
}
update = true;
} while (c != newline); // loop until we see the nth separator char
// if we hit EOF, we're done
if (n == -1) {
break;
}
// if we've found the last char of the separator,
// and we've found at least as many characters as separator length,
// and the last n characters of our buffer match the separator, we're done
if (c == newline && buf.length() >= separator.length() &&
0 == ByteList.memcmp(buf.unsafeBytes(), buf.begin + buf.realSize - separator.length(), separator.unsafeBytes(), separator.begin, separator.realSize)) {
break;
}
}
if (isParagraph) {
if (c != -1) {
swallow('\n');
}
}
if (!update) {
return runtime.getNil();
} else {
incrementLineno(runtime, myOpenFile);
RubyString str = RubyString.newString(runtime, buf);
str.setTaint(true);
return str;
}
}
} catch (PipeException ex) {
throw runtime.newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (EOFException e) {
return runtime.getNil();
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
}
}
private void incrementLineno(Ruby runtime, OpenFile myOpenFile) {
int lineno = myOpenFile.getLineNumber() + 1;
myOpenFile.setLineNumber(lineno);
runtime.getGlobalVariables().set("$.", runtime.newFixnum(lineno));
// this is for a range check, near as I can tell
RubyNumeric.int2fix(runtime, myOpenFile.getLineNumber());
}
protected boolean swallow(int term) throws IOException, BadDescriptorException {
Stream readStream = openFile.getMainStream();
int c;
do {
readCheck(readStream);
try {
c = readStream.fgetc();
} catch (EOFException e) {
c = -1;
}
if (c != term) {
readStream.ungetc(c);
return true;
}
} while (c != -1);
return false;
}
public IRubyObject getlineFast(Ruby runtime, int delim) throws IOException, BadDescriptorException {
Stream readStream = openFile.getMainStream();
int c = -1;
ByteList buf = new ByteList(0);
boolean update = false;
do {
readCheck(readStream);
readStream.clearerr();
int n;
try {
n = readStream.getline(buf, (byte) delim);
c = buf.length() > 0 ? buf.get(buf.length() - 1) & 0xff : -1;
} catch (EOFException e) {
n = -1;
}
if (n == -1) {
if (!readStream.isBlocking() && (readStream instanceof ChannelStream)) {
if(!(waitReadable(((ChannelStream)readStream).getDescriptor()))) {
throw runtime.newIOError("bad file descriptor: " + openFile.getPath());
}
continue;
} else {
break;
}
}
update = true;
} while (c != delim);
if (!update) {
return runtime.getNil();
} else {
incrementLineno(runtime, openFile);
RubyString str = RubyString.newString(runtime, buf);
str.setTaint(true);
return str;
}
}
// IO class methods.
@JRubyMethod(name = {"new", "for_fd"}, rest = true, frame = true, meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyClass klass = (RubyClass)recv;
if (block.isGiven()) {
String className = klass.getName();
context.getRuntime().getWarnings().warn(
ID.BLOCK_NOT_ACCEPTED,
className + "::new() does not take block; use " + className + "::open() instead",
className + "::open()");
}
return klass.newInstance(context, args, block);
}
@JRubyMethod(name = "initialize", required = 1, optional = 1, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
int argCount = args.length;
ModeFlags modes;
int fileno = RubyNumeric.fix2int(args[0]);
try {
ChannelDescriptor descriptor = getDescriptorByFileno(fileno);
if (descriptor == null) {
throw getRuntime().newErrnoEBADFError();
}
descriptor.checkOpen();
if (argCount == 2) {
if (args[1] instanceof RubyFixnum) {
modes = new ModeFlags(RubyFixnum.fix2long(args[1]));
} else {
modes = getIOModes(getRuntime(), args[1].convertToString().toString());
}
} else {
// use original modes
modes = descriptor.getOriginalModes();
}
openFile.setMode(modes.getOpenFileFlags());
openFile.setMainStream(fdopen(descriptor, modes));
} catch (BadDescriptorException ex) {
throw getRuntime().newErrnoEBADFError();
} catch (InvalidValueException ive) {
throw getRuntime().newErrnoEINVALError();
}
return this;
}
protected Stream fdopen(ChannelDescriptor existingDescriptor, ModeFlags modes) throws InvalidValueException {
// See if we already have this descriptor open.
// If so then we can mostly share the handler (keep open
// file, but possibly change the mode).
if (existingDescriptor == null) {
// redundant, done above as well
// this seems unlikely to happen unless it's a totally bogus fileno
// ...so do we even need to bother trying to create one?
// IN FACT, we should probably raise an error, yes?
throw getRuntime().newErrnoEBADFError();
// if (mode == null) {
// mode = "r";
// }
//
// try {
// openFile.setMainStream(streamForFileno(getRuntime(), fileno));
// } catch (BadDescriptorException e) {
// throw getRuntime().newErrnoEBADFError();
// } catch (IOException e) {
// throw getRuntime().newErrnoEBADFError();
// }
// //modes = new IOModes(getRuntime(), mode);
//
// registerStream(openFile.getMainStream());
} else {
// We are creating a new IO object that shares the same
// IOHandler (and fileno).
return ChannelStream.fdopen(getRuntime(), existingDescriptor, modes);
}
}
@JRubyMethod(name = "open", required = 1, optional = 2, frame = true, meta = true)
public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
RubyClass klass = (RubyClass)recv;
RubyIO io = (RubyIO)klass.newInstance(context, args, block);
if (block.isGiven()) {
try {
return block.yield(context, io);
} finally {
try {
io.getMetaClass().invoke(context, io, "close", IRubyObject.NULL_ARRAY, CallType.FUNCTIONAL, Block.NULL_BLOCK);
} catch (RaiseException re) {
RubyException rubyEx = re.getException();
if (rubyEx.kind_of_p(context, runtime.getStandardError()).isTrue()) {
// MRI behavior: swallow StandardErorrs
} else {
throw re;
}
}
}
}
return io;
}
// This appears to be some windows-only mode. On a java platform this is a no-op
@JRubyMethod(name = "binmode")
public IRubyObject binmode() {
return this;
}
/** @deprecated will be removed in 1.2 */
protected void checkInitialized() {
if (openFile == null) {
throw getRuntime().newIOError("uninitialized stream");
}
}
/** @deprecated will be removed in 1.2 */
protected void checkClosed() {
if (openFile.getMainStream() == null && openFile.getPipeStream() == null) {
throw getRuntime().newIOError("closed stream");
}
}
@JRubyMethod(name = "syswrite", required = 1)
public IRubyObject syswrite(ThreadContext context, IRubyObject obj) {
Ruby runtime = context.getRuntime();
try {
RubyString string = obj.asString();
OpenFile myOpenFile = getOpenFileChecked();
myOpenFile.checkWritable(runtime);
Stream writeStream = myOpenFile.getWriteStream();
if (myOpenFile.isWriteBuffered()) {
runtime.getWarnings().warn(ID.SYSWRITE_BUFFERED_IO, "syswrite for buffered IO");
}
if (!writeStream.getDescriptor().isWritable()) {
myOpenFile.checkClosed(runtime);
}
int read = writeStream.getDescriptor().write(string.getByteList());
if (read == -1) {
// TODO? I think this ends up propagating from normal Java exceptions
// sys_fail(openFile.getPath())
}
return runtime.newFixnum(read);
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (PipeException ex) {
throw runtime.newErrnoEPIPEError();
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
} catch (IOException e) {
throw runtime.newSystemCallError(e.getMessage());
}
}
@JRubyMethod(name = "write_nonblock", required = 1)
public IRubyObject write_nonblock(ThreadContext context, IRubyObject obj) {
// MRI behavior: always check whether the file is writable
// or not, even if we are to write 0 bytes.
OpenFile myOpenFile = getOpenFileChecked();
try {
myOpenFile.checkWritable(context.getRuntime());
} catch (IOException ex) {
throw context.getRuntime().newIOErrorFromException(ex);
} catch (BadDescriptorException ex) {
throw context.getRuntime().newErrnoEBADFError();
} catch (InvalidValueException ex) {
throw context.getRuntime().newErrnoEINVALError();
} catch (PipeException ex) {
throw context.getRuntime().newErrnoEPIPEError();
}
// TODO: Obviously, we're not doing a non-blocking write here
return write(context, obj);
}
/** io_write
*
*/
@JRubyMethod(name = "write", required = 1)
public IRubyObject write(ThreadContext context, IRubyObject obj) {
Ruby runtime = context.getRuntime();
runtime.secure(4);
RubyString str = obj.asString();
// TODO: Ruby reuses this logic for other "write" behavior by checking if it's an IO and calling write again
if (str.getByteList().length() == 0) {
return runtime.newFixnum(0);
}
try {
OpenFile myOpenFile = getOpenFileChecked();
myOpenFile.checkWritable(runtime);
int written = fwrite(str.getByteList());
if (written == -1) {
// TODO: sys fail
}
// if not sync, we switch to write buffered mode
if (!myOpenFile.isSync()) {
myOpenFile.setWriteBuffered();
}
return runtime.newFixnum(written);
} catch (IOException ex) {
throw runtime.newIOErrorFromException(ex);
} catch (BadDescriptorException ex) {
throw runtime.newErrnoEBADFError();
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (PipeException ex) {
throw runtime.newErrnoEPIPEError();
}
}
protected boolean waitWritable(ChannelDescriptor descriptor) throws IOException {
Channel channel = descriptor.getChannel();
if (channel == null || !(channel instanceof SelectableChannel)) {
return false;
}
Selector selector = Selector.open();
((SelectableChannel) channel).configureBlocking(false);
int real_ops = ((SelectableChannel) channel).validOps() & SelectionKey.OP_WRITE;
SelectionKey key = ((SelectableChannel) channel).keyFor(selector);
if (key == null) {
((SelectableChannel) channel).register(selector, real_ops, descriptor);
} else {
key.interestOps(key.interestOps()|real_ops);
}
while(selector.select() == 0);
for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) {
SelectionKey skey = (SelectionKey) i.next();
if ((skey.interestOps() & skey.readyOps() & (SelectionKey.OP_WRITE)) != 0) {
if(skey.attachment() == descriptor) {
return true;
}
}
}
return false;
}
protected boolean waitReadable(ChannelDescriptor descriptor) throws IOException {
Channel channel = descriptor.getChannel();
if (channel == null || !(channel instanceof SelectableChannel)) {
return false;
}
Selector selector = Selector.open();
((SelectableChannel) channel).configureBlocking(false);
int real_ops = ((SelectableChannel) channel).validOps() & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT);
SelectionKey key = ((SelectableChannel) channel).keyFor(selector);
if (key == null) {
((SelectableChannel) channel).register(selector, real_ops, descriptor);
} else {
key.interestOps(key.interestOps()|real_ops);
}
while(selector.select() == 0);
for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) {
SelectionKey skey = (SelectionKey) i.next();
if ((skey.interestOps() & skey.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) {
if(skey.attachment() == descriptor) {
return true;
}
}
}
return false;
}
protected int fwrite(ByteList buffer) {
int n, r, l, offset = 0;
boolean eagain = false;
Stream writeStream = openFile.getWriteStream();
int len = buffer.length();
if ((n = len) <= 0) return n;
try {
if (openFile.isSync()) {
openFile.fflush(writeStream);
// TODO: why is this guarded?
// if (!rb_thread_fd_writable(fileno(f))) {
// rb_io_check_closed(fptr);
// }
while(offset<len) {
l = n;
// TODO: Something about pipe buffer length here
r = writeStream.getDescriptor().write(buffer,offset,l);
if(r == len) {
return len; //Everything written
}
if (0 <= r) {
offset += r;
n -= r;
eagain = true;
}
if(eagain && waitWritable(writeStream.getDescriptor())) {
openFile.checkClosed(getRuntime());
if(offset >= buffer.length()) {
return -1;
}
eagain = false;
} else {
return -1;
}
}
// TODO: all this stuff...some pipe logic, some async thread stuff
// retry:
// l = n;
// if (PIPE_BUF < l &&
// !rb_thread_critical &&
// !rb_thread_alone() &&
// wsplit_p(fptr)) {
// l = PIPE_BUF;
// }
// TRAP_BEG;
// r = write(fileno(f), RSTRING(str)->ptr+offset, l);
// TRAP_END;
// if (r == n) return len;
// if (0 <= r) {
// offset += r;
// n -= r;
// errno = EAGAIN;
// }
// if (rb_io_wait_writable(fileno(f))) {
// rb_io_check_closed(fptr);
// if (offset < RSTRING(str)->len)
// goto retry;
// }
// return -1L;
}
// TODO: handle errors in buffered write by retrying until finished or file is closed
return writeStream.fwrite(buffer);
// while (errno = 0, offset += (r = fwrite(RSTRING(str)->ptr+offset, 1, n, f)), (n -= r) > 0) {
// if (ferror(f)
// ) {
// if (rb_io_wait_writable(fileno(f))) {
// rb_io_check_closed(fptr);
// clearerr(f);
// if (offset < RSTRING(str)->len)
// continue;
// }
// return -1L;
// }
// }
// return len - n;
} catch (IOException ex) {
throw getRuntime().newIOErrorFromException(ex);
} catch (BadDescriptorException ex) {
throw getRuntime().newErrnoEBADFError();
}
}
/** rb_io_addstr
*
*/
@JRubyMethod(name = "<<", required = 1)
public IRubyObject op_append(ThreadContext context, IRubyObject anObject) {
// Claims conversion is done via 'to_s' in docs.
callMethod(context, "write", anObject);
return this;
}
@JRubyMethod(name = "fileno", alias = "to_i")
public RubyFixnum fileno(ThreadContext context) {
return context.getRuntime().newFixnum(getOpenFileChecked().getMainStream().getDescriptor().getFileno());
}
/** Returns the current line number.
*
* @return the current line number.
*/
@JRubyMethod(name = "lineno")
public RubyFixnum lineno(ThreadContext context) {
return context.getRuntime().newFixnum(getOpenFileChecked().getLineNumber());
}
/** Sets the current line number.
*
* @param newLineNumber The new line number.
*/
@JRubyMethod(name = "lineno=", required = 1)
public RubyFixnum lineno_set(ThreadContext context, IRubyObject newLineNumber) {
getOpenFileChecked().setLineNumber(RubyNumeric.fix2int(newLineNumber));
return context.getRuntime().newFixnum(getOpenFileChecked().getLineNumber());
}
/** Returns the current sync mode.
*
* @return the current sync mode.
*/
@JRubyMethod(name = "sync")
public RubyBoolean sync(ThreadContext context) {
return context.getRuntime().newBoolean(getOpenFileChecked().getMainStream().isSync());
}
/**
* <p>Return the process id (pid) of the process this IO object
* spawned. If no process exists (popen was not called), then
* nil is returned. This is not how it appears to be defined
* but ruby 1.8 works this way.</p>
*
* @return the pid or nil
*/
@JRubyMethod(name = "pid")
public IRubyObject pid(ThreadContext context) {
OpenFile myOpenFile = getOpenFileChecked();
if (myOpenFile.getProcess() == null) {
return context.getRuntime().getNil();
}
// Of course this isn't particularly useful.
int pid = myOpenFile.getProcess().hashCode();
return context.getRuntime().newFixnum(pid);
}
/**
* @deprecated
* @return
*/
public boolean writeDataBuffered() {
return openFile.getMainStream().writeDataBuffered();
}
@JRubyMethod(name = {"pos", "tell"})
public RubyFixnum pos(ThreadContext context) {
try {
return context.getRuntime().newFixnum(getOpenFileChecked().getMainStream().fgetpos());
} catch (InvalidValueException ex) {
throw context.getRuntime().newErrnoEINVALError();
} catch (BadDescriptorException bde) {
throw context.getRuntime().newErrnoEBADFError();
} catch (PipeException e) {
throw context.getRuntime().newErrnoESPIPEError();
} catch (IOException e) {
throw context.getRuntime().newIOError(e.getMessage());
}
}
@JRubyMethod(name = "pos=", required = 1)
public RubyFixnum pos_set(ThreadContext context, IRubyObject newPosition) {
long offset = RubyNumeric.num2long(newPosition);
if (offset < 0) {
throw context.getRuntime().newSystemCallError("Negative seek offset");
}
OpenFile myOpenFile = getOpenFileChecked();
try {
myOpenFile.getMainStream().lseek(offset, Stream.SEEK_SET);
} catch (BadDescriptorException e) {
throw context.getRuntime().newErrnoEBADFError();
} catch (InvalidValueException e) {
throw context.getRuntime().newErrnoEINVALError();
} catch (PipeException e) {
throw context.getRuntime().newErrnoESPIPEError();
} catch (IOException e) {
throw context.getRuntime().newIOError(e.getMessage());
}
myOpenFile.getMainStream().clearerr();
return context.getRuntime().newFixnum(offset);
}
/** Print some objects to the stream.
*
*/
@JRubyMethod(name = "print", rest = true, reads = FrameField.LASTLINE)
public IRubyObject print(ThreadContext context, IRubyObject[] args) {
if (args.length == 0) {
args = new IRubyObject[] { context.getCurrentFrame().getLastLine() };
}
Ruby runtime = context.getRuntime();
IRubyObject fs = runtime.getGlobalVariables().get("$,");
IRubyObject rs = runtime.getGlobalVariables().get("$\\");
for (int i = 0; i < args.length; i++) {
if (i > 0 && !fs.isNil()) {
callMethod(context, "write", fs);
}
if (args[i].isNil()) {
callMethod(context, "write", runtime.newString("nil"));
} else {
callMethod(context, "write", args[i]);
}
}
if (!rs.isNil()) {
callMethod(context, "write", rs);
}
return runtime.getNil();
}
@JRubyMethod(name = "printf", required = 1, rest = true)
public IRubyObject printf(ThreadContext context, IRubyObject[] args) {
callMethod(context, "write", RubyKernel.sprintf(context, this, args));
return context.getRuntime().getNil();
}
@JRubyMethod(name = "putc", required = 1, backtrace = true)
public IRubyObject putc(ThreadContext context, IRubyObject object) {
int c = RubyNumeric.num2chr(object);
try {
getOpenFileChecked().getMainStream().fputc(c);
} catch (BadDescriptorException e) {
return RubyFixnum.zero(context.getRuntime());
} catch (IOException e) {
return RubyFixnum.zero(context.getRuntime());
}
return object;
}
public RubyFixnum seek(ThreadContext context, IRubyObject[] args) {
long offset = RubyNumeric.num2long(args[0]);
int whence = Stream.SEEK_SET;
if (args.length > 1) {
whence = RubyNumeric.fix2int(args[1].convertToInteger());
}
return doSeek(context, offset, whence);
}
@JRubyMethod(name = "seek")
public RubyFixnum seek(ThreadContext context, IRubyObject arg0) {
long offset = RubyNumeric.num2long(arg0);
int whence = Stream.SEEK_SET;
return doSeek(context, offset, whence);
}
@JRubyMethod(name = "seek")
public RubyFixnum seek(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
long offset = RubyNumeric.num2long(arg0);
int whence = RubyNumeric.fix2int(arg1.convertToInteger());
return doSeek(context, offset, whence);
}
private RubyFixnum doSeek(ThreadContext context, long offset, int whence) {
OpenFile myOpenFile = getOpenFileChecked();
try {
myOpenFile.seek(offset, whence);
} catch (BadDescriptorException ex) {
throw context.getRuntime().newErrnoEBADFError();
} catch (InvalidValueException e) {
throw context.getRuntime().newErrnoEINVALError();
} catch (PipeException e) {
throw context.getRuntime().newErrnoESPIPEError();
} catch (IOException e) {
throw context.getRuntime().newIOError(e.getMessage());
}
myOpenFile.getMainStream().clearerr();
return RubyFixnum.zero(context.getRuntime());
}
// This was a getOpt with one mandatory arg, but it did not work
// so I am parsing it for now.
@JRubyMethod(name = "sysseek", required = 1, optional = 1)
public RubyFixnum sysseek(ThreadContext context, IRubyObject[] args) {
long offset = RubyNumeric.num2long(args[0]);
long pos;
int whence = Stream.SEEK_SET;
if (args.length > 1) {
whence = RubyNumeric.fix2int(args[1].convertToInteger());
}
OpenFile myOpenFile = getOpenFileChecked();
try {
if (myOpenFile.isReadable() && myOpenFile.isReadBuffered()) {
throw context.getRuntime().newIOError("sysseek for buffered IO");
}
if (myOpenFile.isWritable() && myOpenFile.isWriteBuffered()) {
context.getRuntime().getWarnings().warn(ID.SYSSEEK_BUFFERED_IO, "sysseek for buffered IO");
}
pos = myOpenFile.getMainStream().getDescriptor().lseek(offset, whence);
} catch (BadDescriptorException ex) {
throw context.getRuntime().newErrnoEBADFError();
} catch (InvalidValueException e) {
throw context.getRuntime().newErrnoEINVALError();
} catch (PipeException e) {
throw context.getRuntime().newErrnoESPIPEError();
} catch (IOException e) {
throw context.getRuntime().newIOError(e.getMessage());
}
myOpenFile.getMainStream().clearerr();
return context.getRuntime().newFixnum(pos);
}
@JRubyMethod(name = "rewind")
public RubyFixnum rewind(ThreadContext context) {
OpenFile myOpenfile = getOpenFileChecked();
try {
myOpenfile.getMainStream().lseek(0L, Stream.SEEK_SET);
myOpenfile.getMainStream().clearerr();
// TODO: This is some goofy global file value from MRI..what to do?
// if (io == current_file) {
// gets_lineno -= fptr->lineno;
// }
} catch (BadDescriptorException e) {
throw context.getRuntime().newErrnoEBADFError();
} catch (InvalidValueException e) {
throw context.getRuntime().newErrnoEINVALError();
} catch (PipeException e) {
throw context.getRuntime().newErrnoESPIPEError();
} catch (IOException e) {
throw context.getRuntime().newIOError(e.getMessage());
}
// Must be back on first line on rewind.
myOpenfile.setLineNumber(0);
return RubyFixnum.zero(context.getRuntime());
}
@JRubyMethod(name = "fsync")
public RubyFixnum fsync(ThreadContext context) {
Ruby runtime = context.getRuntime();
try {
OpenFile myOpenFile = getOpenFileChecked();
myOpenFile.checkWritable(runtime);
myOpenFile.getWriteStream().sync();
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (PipeException ex) {
throw runtime.newErrnoEPIPEError();
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
}
return RubyFixnum.zero(runtime);
}
/** Sets the current sync mode.
*
* @param newSync The new sync mode.
*/
@JRubyMethod(name = "sync=", required = 1)
public IRubyObject sync_set(IRubyObject newSync) {
getOpenFileChecked().setSync(newSync.isTrue());
getOpenFileChecked().getMainStream().setSync(newSync.isTrue());
return this;
}
@JRubyMethod(name = {"eof?", "eof"})
public RubyBoolean eof_p(ThreadContext context) {
Ruby runtime = context.getRuntime();
try {
OpenFile myOpenFile = getOpenFileChecked();
myOpenFile.checkReadable(runtime);
myOpenFile.setReadBuffered();
if (myOpenFile.getMainStream().feof()) {
return runtime.getTrue();
}
if (myOpenFile.getMainStream().readDataBuffered()) {
return runtime.getFalse();
}
readCheck(myOpenFile.getMainStream());
myOpenFile.getMainStream().clearerr();
int c = myOpenFile.getMainStream().fgetc();
if (c != -1) {
myOpenFile.getMainStream().ungetc(c);
return runtime.getFalse();
}
myOpenFile.checkClosed(runtime);
myOpenFile.getMainStream().clearerr();
return runtime.getTrue();
} catch (PipeException ex) {
throw runtime.newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
}
}
@JRubyMethod(name = {"tty?", "isatty"})
public RubyBoolean tty_p(ThreadContext context) {
return context.getRuntime().newBoolean(context.getRuntime().getPosix().isatty(getOpenFileChecked().getMainStream().getDescriptor().getFileDescriptor()));
}
@JRubyMethod(name = "initialize_copy", required = 1)
@Override
public IRubyObject initialize_copy(IRubyObject original){
Ruby runtime = getRuntime();
if (this == original) return this;
RubyIO originalIO = (RubyIO) TypeConverter.convertToTypeWithCheck(original, runtime.getIO(), MethodIndex.TO_IO, "to_io");
OpenFile originalFile = originalIO.getOpenFileChecked();
OpenFile newFile = openFile;
try {
// TODO: I didn't see where MRI has this check, but it seems to be the right place
originalFile.checkClosed(runtime);
if (originalFile.getPipeStream() != null) {
originalFile.getPipeStream().fflush();
originalFile.getMainStream().lseek(0, Stream.SEEK_CUR);
} else if (originalFile.isWritable()) {
originalFile.getMainStream().fflush();
} else {
originalFile.getMainStream().lseek(0, Stream.SEEK_CUR);
}
newFile.setMode(originalFile.getMode());
newFile.setProcess(originalFile.getProcess());
newFile.setLineNumber(originalFile.getLineNumber());
newFile.setPath(originalFile.getPath());
newFile.setFinalizer(originalFile.getFinalizer());
ModeFlags modes;
if (newFile.isReadable()) {
if (newFile.isWritable()) {
if (newFile.getPipeStream() != null) {
modes = new ModeFlags(ModeFlags.RDONLY);
} else {
modes = new ModeFlags(ModeFlags.RDWR);
}
} else {
modes = new ModeFlags(ModeFlags.RDONLY);
}
} else {
if (newFile.isWritable()) {
modes = new ModeFlags(ModeFlags.WRONLY);
} else {
modes = originalFile.getMainStream().getModes();
}
}
ChannelDescriptor descriptor = originalFile.getMainStream().getDescriptor().dup();
newFile.setMainStream(ChannelStream.fdopen(runtime, descriptor, modes));
// TODO: the rest of this...seeking to same position is unnecessary since we share a channel
// but some of this may be needed?
// fseeko(fptr->f, ftello(orig->f), SEEK_SET);
// if (orig->f2) {
// if (fileno(orig->f) != fileno(orig->f2)) {
// fd = ruby_dup(fileno(orig->f2));
// }
// fptr->f2 = rb_fdopen(fd, "w");
// fseeko(fptr->f2, ftello(orig->f2), SEEK_SET);
// }
// if (fptr->mode & FMODE_BINMODE) {
// rb_io_binmode(dest);
// }
// Register the new descriptor
registerDescriptor(newFile.getMainStream().getDescriptor());
} catch (IOException ex) {
throw runtime.newIOError("could not init copy: " + ex);
} catch (BadDescriptorException ex) {
throw runtime.newIOError("could not init copy: " + ex);
} catch (PipeException ex) {
throw runtime.newIOError("could not init copy: " + ex);
} catch (InvalidValueException ex) {
throw runtime.newIOError("could not init copy: " + ex);
}
return this;
}
/** Closes the IO.
*
* @return The IO.
*/
@JRubyMethod(name = "closed?")
public RubyBoolean closed_p(ThreadContext context) {
return context.getRuntime().newBoolean(openFile.getMainStream() == null && openFile.getPipeStream() == null);
}
/**
* <p>Closes all open resources for the IO. It also removes
* it from our magical all open file descriptor pool.</p>
*
* @return The IO.
*/
@JRubyMethod(name = "close")
public IRubyObject close() {
Ruby runtime = getRuntime();
if (runtime.getSafeLevel() >= 4 && isTaint()) {
throw runtime.newSecurityError("Insecure: can't close");
}
openFile.checkClosed(runtime);
return close2(runtime);
}
protected IRubyObject close2(Ruby runtime) {
if (openFile == null) return runtime.getNil();
// These would be used when we notify threads...if we notify threads
interruptBlockingThreads();
ChannelDescriptor main, pipe;
if (openFile.getPipeStream() != null) {
pipe = openFile.getPipeStream().getDescriptor();
} else {
if (openFile.getMainStream() == null) {
return runtime.getNil();
}
pipe = null;
}
main = openFile.getMainStream().getDescriptor();
// cleanup, raising errors if any
openFile.cleanup(runtime, true);
// TODO: notify threads waiting on descriptors/IO? probably not...
if (openFile.getProcess() != null) {
try {
IRubyObject processResult = RubyProcess.RubyStatus.newProcessStatus(runtime, openFile.getProcess().waitFor());
runtime.getGlobalVariables().set("$?", processResult);
} catch (InterruptedException ie) {
// TODO: do something here?
}
}
return runtime.getNil();
}
@JRubyMethod(name = "close_write")
public IRubyObject close_write(ThreadContext context) throws BadDescriptorException {
try {
if (context.getRuntime().getSafeLevel() >= 4 && isTaint()) {
throw context.getRuntime().newSecurityError("Insecure: can't close");
}
OpenFile myOpenFile = getOpenFileChecked();
if (myOpenFile.getPipeStream() == null && myOpenFile.isReadable()) {
throw context.getRuntime().newIOError("closing non-duplex IO for writing");
}
if (myOpenFile.getPipeStream() == null) {
close();
} else{
myOpenFile.getPipeStream().fclose();
myOpenFile.setPipeStream(null);
myOpenFile.setMode(myOpenFile.getMode() & ~OpenFile.WRITABLE);
// TODO
// n is result of fclose; but perhaps having a SysError below is enough?
// if (n != 0) rb_sys_fail(fptr->path);
}
} catch (IOException ioe) {
// hmmmm
}
return this;
}
@JRubyMethod(name = "close_read")
public IRubyObject close_read(ThreadContext context) throws BadDescriptorException {
Ruby runtime = context.getRuntime();
try {
if (runtime.getSafeLevel() >= 4 && isTaint()) {
throw runtime.newSecurityError("Insecure: can't close");
}
OpenFile myOpenFile = getOpenFileChecked();
if (myOpenFile.getPipeStream() == null && myOpenFile.isWritable()) {
throw runtime.newIOError("closing non-duplex IO for reading");
}
if (myOpenFile.getPipeStream() == null) {
close();
} else{
myOpenFile.getMainStream().fclose();
myOpenFile.setMode(myOpenFile.getMode() & ~OpenFile.READABLE);
myOpenFile.setMainStream(myOpenFile.getPipeStream());
myOpenFile.setPipeStream(null);
// TODO
// n is result of fclose; but perhaps having a SysError below is enough?
// if (n != 0) rb_sys_fail(fptr->path);
}
} catch (IOException ioe) {
// I believe Ruby bails out with a "bug" if closing fails
throw runtime.newIOErrorFromException(ioe);
}
return this;
}
/** Flushes the IO output stream.
*
* @return The IO.
*/
@JRubyMethod(name = "flush")
public RubyIO flush() {
try {
getOpenFileChecked().getWriteStream().fflush();
} catch (BadDescriptorException e) {
throw getRuntime().newErrnoEBADFError();
} catch (IOException e) {
throw getRuntime().newIOError(e.getMessage());
}
return this;
}
/** Read a line.
*
*/
@JRubyMethod(name = "gets", optional = 1, writes = FrameField.LASTLINE)
public IRubyObject gets(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
ByteList separator = getSeparatorForGets(runtime, args);
IRubyObject result = getline(runtime, separator);
if (!result.isNil()) context.getCurrentFrame().setLastLine(result);
return result;
}
public boolean getBlocking() {
return ((ChannelStream) openFile.getMainStream()).isBlocking();
}
@JRubyMethod(name = "fcntl", required = 2)
public IRubyObject fcntl(ThreadContext context, IRubyObject cmd, IRubyObject arg) {
// TODO: This version differs from ioctl by checking whether fcntl exists
// and raising notimplemented if it doesn't; perhaps no difference for us?
return ctl(context.getRuntime(), cmd, arg);
}
@JRubyMethod(name = "ioctl", required = 1, optional = 1)
public IRubyObject ioctl(ThreadContext context, IRubyObject[] args) {
IRubyObject cmd = args[0];
IRubyObject arg;
if (args.length == 2) {
arg = args[1];
} else {
arg = context.getRuntime().getNil();
}
return ctl(context.getRuntime(), cmd, arg);
}
public IRubyObject ctl(Ruby runtime, IRubyObject cmd, IRubyObject arg) {
long realCmd = cmd.convertToInteger().getLongValue();
long nArg = 0;
// FIXME: Arg may also be true, false, and nil and still be valid. Strangely enough,
// protocol conversion is not happening in Ruby on this arg?
if (arg.isNil() || arg == runtime.getFalse()) {
nArg = 0;
} else if (arg instanceof RubyFixnum) {
nArg = RubyFixnum.fix2long(arg);
} else if (arg == runtime.getTrue()) {
nArg = 1;
} else {
throw runtime.newNotImplementedError("JRuby does not support string for second fcntl/ioctl argument yet");
}
OpenFile myOpenFile = getOpenFileChecked();
// Fixme: Only F_SETFL is current supported
if (realCmd == 1L) { // cmd is F_SETFL
boolean block = true;
if ((nArg & ModeFlags.NONBLOCK) == ModeFlags.NONBLOCK) {
block = false;
}
try {
myOpenFile.getMainStream().setBlocking(block);
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
}
} else {
throw runtime.newNotImplementedError("JRuby only supports F_SETFL for fcntl/ioctl currently");
}
return runtime.newFixnum(0);
}
private static final ByteList NIL_BYTELIST = ByteList.create("nil");
private static final ByteList RECURSIVE_BYTELIST = ByteList.create("[...]");
@JRubyMethod(name = "puts", rest = true)
public IRubyObject puts(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
assert runtime.getGlobalVariables().getDefaultSeparator() instanceof RubyString;
RubyString separator = (RubyString) runtime.getGlobalVariables().getDefaultSeparator();
if (args.length == 0) {
write(context, separator.getByteList());
return runtime.getNil();
}
for (int i = 0; i < args.length; i++) {
ByteList line;
if (args[i].isNil()) {
line = NIL_BYTELIST;
} else if (runtime.isInspecting(args[i])) {
line = RECURSIVE_BYTELIST;
} else if (args[i] instanceof RubyArray) {
inspectPuts(context, (RubyArray) args[i]);
continue;
} else {
line = args[i].asString().getByteList();
}
write(context, line);
if (line.length() == 0 || !line.endsWith(separator.getByteList())) {
write(context, separator.getByteList());
}
}
return runtime.getNil();
}
protected void write(ThreadContext context, ByteList byteList) {
callMethod(context, "write", RubyString.newStringShared(context.getRuntime(), byteList));
}
private IRubyObject inspectPuts(ThreadContext context, RubyArray array) {
try {
context.getRuntime().registerInspecting(array);
return puts(context, array.toJavaArray());
} finally {
context.getRuntime().unregisterInspecting(array);
}
}
/** Read a line.
*
*/
@JRubyMethod(name = "readline", optional = 1, writes = FrameField.LASTLINE)
public IRubyObject readline(ThreadContext context, IRubyObject[] args) {
IRubyObject line = gets(context, args);
if (line.isNil()) throw context.getRuntime().newEOFError();
return line;
}
/** Read a byte. On EOF returns nil.
*
*/
@JRubyMethod(name = "getc")
public IRubyObject getc() {
try {
OpenFile myOpenFile = getOpenFileChecked();
myOpenFile.checkReadable(getRuntime());
myOpenFile.setReadBuffered();
Stream stream = myOpenFile.getMainStream();
readCheck(stream);
stream.clearerr();
int c = myOpenFile.getMainStream().fgetc();
if (c == -1) {
// TODO: check for ferror, clear it, and try once more up above readCheck
// if (ferror(f)) {
// clearerr(f);
// if (!rb_io_wait_readable(fileno(f)))
// rb_sys_fail(fptr->path);
// goto retry;
// }
return getRuntime().getNil();
}
return getRuntime().newFixnum(c);
} catch (PipeException ex) {
throw getRuntime().newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} catch (BadDescriptorException e) {
throw getRuntime().newErrnoEBADFError();
} catch (EOFException e) {
throw getRuntime().newEOFError();
} catch (IOException e) {
throw getRuntime().newIOError(e.getMessage());
}
}
private void readCheck(Stream stream) {
if (!stream.readDataBuffered()) {
openFile.checkClosed(getRuntime());
}
}
/**
* <p>Pushes char represented by int back onto IOS.</p>
*
* @param number to push back
*/
@JRubyMethod(name = "ungetc", required = 1)
public IRubyObject ungetc(IRubyObject number) {
int ch = RubyNumeric.fix2int(number);
OpenFile myOpenFile = getOpenFileChecked();
if (!myOpenFile.isReadBuffered()) {
throw getRuntime().newIOError("unread stream");
}
try {
myOpenFile.checkReadable(getRuntime());
myOpenFile.setReadBuffered();
if (myOpenFile.getMainStream().ungetc(ch) == -1 && ch != -1) {
throw getRuntime().newIOError("ungetc failed");
}
} catch (PipeException ex) {
throw getRuntime().newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} catch (BadDescriptorException e) {
throw getRuntime().newErrnoEBADFError();
} catch (EOFException e) {
throw getRuntime().newEOFError();
} catch (IOException e) {
throw getRuntime().newIOError(e.getMessage());
}
return getRuntime().getNil();
}
@JRubyMethod(name = "read_nonblock", required = 1, optional = 1)
public IRubyObject read_nonblock(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
openFile.checkClosed(runtime);
if(!(openFile.getMainStream() instanceof ChannelStream)) {
// cryptic for the uninitiated...
throw runtime.newNotImplementedError("read_nonblock only works with Nio based handlers");
}
try {
int maxLength = RubyNumeric.fix2int(args[0]);
if (maxLength < 0) {
throw runtime.newArgumentError("negative length " + maxLength + " given");
}
ByteList buf = ((ChannelStream)openFile.getMainStream()).readnonblock(RubyNumeric.fix2int(args[0]));
IRubyObject strbuf = RubyString.newString(runtime, buf == null ? new ByteList(ByteList.NULL_ARRAY) : buf);
if(args.length > 1) {
args[1].callMethod(context, MethodIndex.OP_LSHIFT, "<<", strbuf);
return args[1];
}
return strbuf;
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
} catch (EOFException e) {
return runtime.getNil();
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
}
}
@JRubyMethod(name = "readpartial", required = 1, optional = 1)
public IRubyObject readpartial(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
openFile.checkClosed(runtime);
if(!(openFile.getMainStream() instanceof ChannelStream)) {
// cryptic for the uninitiated...
throw runtime.newNotImplementedError("readpartial only works with Nio based handlers");
}
try {
int maxLength = RubyNumeric.fix2int(args[0]);
if (maxLength < 0) {
throw runtime.newArgumentError("negative length " + maxLength + " given");
}
ByteList buf = ((ChannelStream)openFile.getMainStream()).readpartial(RubyNumeric.fix2int(args[0]));
IRubyObject strbuf = RubyString.newString(runtime, buf == null ? new ByteList(ByteList.NULL_ARRAY) : buf);
if(args.length > 1) {
args[1].callMethod(context, MethodIndex.OP_LSHIFT, "<<", strbuf);
return args[1];
}
return strbuf;
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
} catch (EOFException e) {
return runtime.getNil();
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
}
}
@JRubyMethod(name = "sysread", required = 1, optional = 1)
public IRubyObject sysread(ThreadContext context, IRubyObject[] args) {
int len = (int)RubyNumeric.num2long(args[0]);
if (len < 0) throw getRuntime().newArgumentError("Negative size");
try {
RubyString str;
ByteList buffer;
if (args.length == 1 || args[1].isNil()) {
if (len == 0) {
return RubyString.newStringShared(getRuntime(), ByteList.EMPTY_BYTELIST);
}
buffer = new ByteList(len);
str = RubyString.newString(getRuntime(), buffer);
} else {
str = args[1].convertToString();
str.modify(len);
if (len == 0) {
return str;
}
buffer = str.getByteList();
}
OpenFile myOpenFile = getOpenFileChecked();
myOpenFile.checkReadable(getRuntime());
if (myOpenFile.getMainStream().readDataBuffered()) {
throw getRuntime().newIOError("sysread for buffered IO");
}
// TODO: Ruby locks the string here
context.getThread().beforeBlockingCall();
myOpenFile.checkClosed(getRuntime());
// TODO: Ruby re-checks that the buffer string hasn't been modified
int bytesRead = myOpenFile.getMainStream().getDescriptor().read(len, str.getByteList());
// TODO: Ruby unlocks the string here
// TODO: Ruby truncates string to specific size here, but our bytelist should handle this already?
if (bytesRead == -1 || (bytesRead == 0 && len > 0)) {
throw getRuntime().newEOFError();
}
str.setTaint(true);
return str;
} catch (BadDescriptorException e) {
throw getRuntime().newErrnoEBADFError();
} catch (InvalidValueException e) {
throw getRuntime().newErrnoEINVALError();
} catch (PipeException e) {
throw getRuntime().newErrnoEPIPEError();
} catch (EOFException e) {
throw getRuntime().newEOFError();
} catch (IOException e) {
// All errors to sysread should be SystemCallErrors, but on a closed stream
// Ruby returns an IOError. Java throws same exception for all errors so
// we resort to this hack...
if ("File not open".equals(e.getMessage())) {
throw getRuntime().newIOError(e.getMessage());
}
throw getRuntime().newSystemCallError(e.getMessage());
} finally {
context.getThread().afterBlockingCall();
}
}
public IRubyObject read(IRubyObject[] args) {
ThreadContext context = getRuntime().getCurrentContext();
switch (args.length) {
case 0: return read(context);
case 1: return read(context, args[0]);
case 2: return read(context, args[0], args[1]);
default: throw getRuntime().newArgumentError(args.length, 2);
}
}
@JRubyMethod(name = "read")
public IRubyObject read(ThreadContext context) {
Ruby runtime = context.getRuntime();
OpenFile myOpenFile = getOpenFileChecked();
try {
myOpenFile.checkReadable(runtime);
myOpenFile.setReadBuffered();
return readAll(getRuntime().getNil());
} catch (PipeException ex) {
throw getRuntime().newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} catch (EOFException ex) {
throw getRuntime().newEOFError();
} catch (IOException ex) {
throw getRuntime().newIOErrorFromException(ex);
} catch (BadDescriptorException ex) {
throw getRuntime().newErrnoEBADFError();
}
}
@JRubyMethod(name = "read")
public IRubyObject read(ThreadContext context, IRubyObject arg0) {
if (arg0.isNil()) {
return read(context);
}
OpenFile myOpenFile = getOpenFileChecked();
int length = RubyNumeric.num2int(arg0);
if (length < 0) {
throw getRuntime().newArgumentError("negative length " + length + " given");
}
RubyString str = null;
return readNotAll(context, myOpenFile, length, str);
}
@JRubyMethod(name = "read")
public IRubyObject read(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
OpenFile myOpenFile = getOpenFileChecked();
if (arg0.isNil()) {
try {
myOpenFile.checkReadable(getRuntime());
myOpenFile.setReadBuffered();
return readAll(arg1);
} catch (PipeException ex) {
throw getRuntime().newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw getRuntime().newErrnoEINVALError();
} catch (EOFException ex) {
throw getRuntime().newEOFError();
} catch (IOException ex) {
throw getRuntime().newIOErrorFromException(ex);
} catch (BadDescriptorException ex) {
throw getRuntime().newErrnoEBADFError();
}
}
int length = RubyNumeric.num2int(arg0);
if (length < 0) {
throw getRuntime().newArgumentError("negative length " + length + " given");
}
RubyString str = null;
// ByteList buffer = null;
if (arg1.isNil()) {
// buffer = new ByteList(length);
// str = RubyString.newString(getRuntime(), buffer);
} else {
str = arg1.convertToString();
str.modify(length);
if (length == 0) {
return str;
}
// buffer = str.getByteList();
}
return readNotAll(context, myOpenFile, length, str);
}
private IRubyObject readNotAll(ThreadContext context, OpenFile myOpenFile, int length, RubyString str) {
Ruby runtime = context.getRuntime();
try {
myOpenFile.checkReadable(runtime);
myOpenFile.setReadBuffered();
if (myOpenFile.getMainStream().feof()) {
return runtime.getNil();
}
// TODO: Ruby locks the string here
// READ_CHECK from MRI io.c
readCheck(myOpenFile.getMainStream());
// TODO: check buffer length again?
// if (RSTRING(str)->len != len) {
// rb_raise(rb_eRuntimeError, "buffer string modified");
// }
// TODO: read into buffer using all the fread logic
// int read = openFile.getMainStream().fread(buffer);
ByteList newBuffer = myOpenFile.getMainStream().fread(length);
// TODO: Ruby unlocks the string here
// TODO: change this to check number read into buffer once that's working
// if (read == 0) {
if (newBuffer == null || newBuffer.length() == 0) {
if (myOpenFile.getMainStream() == null) {
return runtime.getNil();
}
if (myOpenFile.getMainStream().feof()) {
// truncate buffer string to zero, if provided
if (str != null) {
str.setValue(ByteList.EMPTY_BYTELIST.dup());
}
return runtime.getNil();
}
// Removed while working on JRUBY-2386, since fixes for that
// modified EOF logic such that this check is not really valid.
// We expect that an EOFException will be thrown now in EOF
// cases.
// if (length > 0) {
// // I think this is only partly correct; sys fail based on errno in Ruby
// throw getRuntime().newEOFError();
// }
}
// TODO: Ruby truncates string to specific size here, but our bytelist should handle this already?
// FIXME: I don't like the null checks here
if (str == null) {
if (newBuffer == null) {
str = RubyString.newEmptyString(runtime);
} else {
str = RubyString.newString(runtime, newBuffer);
}
} else {
if (newBuffer == null) {
str.empty();
} else {
str.setValue(newBuffer);
}
}
str.setTaint(true);
return str;
} catch (EOFException ex) {
throw runtime.newEOFError();
} catch (PipeException ex) {
throw runtime.newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (IOException ex) {
throw runtime.newIOErrorFromException(ex);
} catch (BadDescriptorException ex) {
throw runtime.newErrnoEBADFError();
}
}
protected IRubyObject readAll(IRubyObject buffer) throws BadDescriptorException, EOFException, IOException {
Ruby runtime = getRuntime();
// TODO: handle writing into original buffer better
RubyString str = null;
if (buffer instanceof RubyString) {
str = (RubyString)buffer;
}
// TODO: ruby locks the string here
// READ_CHECK from MRI io.c
if (openFile.getMainStream().readDataBuffered()) {
openFile.checkClosed(runtime);
}
ByteList newBuffer = openFile.getMainStream().readall();
// TODO same zero-length checks as file above
if (str == null) {
if (newBuffer == null) {
str = RubyString.newEmptyString(runtime);
} else {
str = RubyString.newString(runtime, newBuffer);
}
} else {
if (newBuffer == null) {
str.empty();
} else {
str.setValue(newBuffer);
}
}
str.taint(runtime.getCurrentContext());
return str;
// long bytes = 0;
// long n;
//
// if (siz == 0) siz = BUFSIZ;
// if (NIL_P(str)) {
// str = rb_str_new(0, siz);
// }
// else {
// rb_str_resize(str, siz);
// }
// for (;;) {
// rb_str_locktmp(str);
// READ_CHECK(fptr->f);
// n = io_fread(RSTRING(str)->ptr+bytes, siz-bytes, fptr);
// rb_str_unlocktmp(str);
// if (n == 0 && bytes == 0) {
// if (!fptr->f) break;
// if (feof(fptr->f)) break;
// if (!ferror(fptr->f)) break;
// rb_sys_fail(fptr->path);
// }
// bytes += n;
// if (bytes < siz) break;
// siz += BUFSIZ;
// rb_str_resize(str, siz);
// }
// if (bytes != siz) rb_str_resize(str, bytes);
// OBJ_TAINT(str);
//
// return str;
}
// TODO: There's a lot of complexity here due to error handling and
// nonblocking IO; much of this goes away, but for now I'm just
// having read call ChannelStream.fread directly.
// protected int fread(int len, ByteList buffer) {
// long n = len;
// int c;
// int saved_errno;
//
// while (n > 0) {
// c = read_buffered_data(ptr, n, fptr->f);
// if (c < 0) goto eof;
// if (c > 0) {
// ptr += c;
// if ((n -= c) <= 0) break;
// }
// rb_thread_wait_fd(fileno(fptr->f));
// rb_io_check_closed(fptr);
// clearerr(fptr->f);
// TRAP_BEG;
// c = getc(fptr->f);
// TRAP_END;
// if (c == EOF) {
// eof:
// if (ferror(fptr->f)) {
// switch (errno) {
// case EINTR:
// #if defined(ERESTART)
// case ERESTART:
// #endif
// clearerr(fptr->f);
// continue;
// case EAGAIN:
// #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
// case EWOULDBLOCK:
// #endif
// if (len > n) {
// clearerr(fptr->f);
// }
// saved_errno = errno;
// rb_warning("nonblocking IO#read is obsolete; use IO#readpartial or IO#sysread");
// errno = saved_errno;
// }
// if (len == n) return 0;
// }
// break;
// }
// *ptr++ = c;
// n--;
// }
// return len - n;
//
// }
/** Read a byte. On EOF throw EOFError.
*
*/
@JRubyMethod(name = "readchar")
public IRubyObject readchar() {
IRubyObject c = getc();
if (c.isNil()) throw getRuntime().newEOFError();
return c;
}
@JRubyMethod
public IRubyObject stat(ThreadContext context) {
openFile.checkClosed(context.getRuntime());
return context.getRuntime().newFileStat(getOpenFileChecked().getMainStream().getDescriptor().getFileDescriptor());
}
/**
* <p>Invoke a block for each byte.</p>
*/
@JRubyMethod(name = "each_byte", frame = true)
public IRubyObject each_byte(ThreadContext context, Block block) {
Ruby runtime = context.getRuntime();
try {
OpenFile myOpenFile = getOpenFileChecked();
while (true) {
myOpenFile.checkReadable(runtime);
myOpenFile.setReadBuffered();
// TODO: READ_CHECK from MRI
int c = myOpenFile.getMainStream().fgetc();
if (c == -1) {
// TODO: check for error, clear it, and wait until readable before trying once more
// if (ferror(f)) {
// clearerr(f);
// if (!rb_io_wait_readable(fileno(f)))
// rb_sys_fail(fptr->path);
// continue;
// }
break;
}
assert c < 256;
block.yield(context, getRuntime().newFixnum(c));
}
// TODO: one more check for error
// if (ferror(f)) rb_sys_fail(fptr->path);
return this;
} catch (PipeException ex) {
throw runtime.newErrnoEPIPEError();
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (BadDescriptorException e) {
throw runtime.newErrnoEBADFError();
} catch (EOFException e) {
return runtime.getNil();
} catch (IOException e) {
throw runtime.newIOError(e.getMessage());
}
}
/**
* <p>Invoke a block for each line.</p>
*/
@JRubyMethod(name = {"each_line", "each"}, optional = 1, frame = true)
public RubyIO each_line(ThreadContext context, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
ByteList separator = getSeparatorForGets(runtime, args);
for (IRubyObject line = getline(runtime, separator); !line.isNil();
line = getline(runtime, separator)) {
block.yield(context, line);
}
return this;
}
@JRubyMethod(name = "readlines", optional = 1)
public RubyArray readlines(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
IRubyObject[] separatorArgs = args.length > 0 ? new IRubyObject[] { args[0] } : IRubyObject.NULL_ARRAY;
ByteList separator = getSeparatorForGets(runtime, separatorArgs);
RubyArray result = runtime.newArray();
IRubyObject line;
while (! (line = getline(runtime, separator)).isNil()) {
result.append(line);
}
return result;
}
@JRubyMethod(name = "to_io")
public RubyIO to_io() {
return this;
}
@Override
public String toString() {
return "RubyIO(" + openFile.getMode() + ", " + openFile.getMainStream().getDescriptor().getFileno() + ")";
}
/* class methods for IO */
/** rb_io_s_foreach
*
*/
@JRubyMethod(name = "foreach", required = 1, optional = 1, frame = true, meta = true)
public static IRubyObject foreach(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
int count = args.length;
IRubyObject filename = args[0].convertToString();
runtime.checkSafeString(filename);
ByteList separator = getSeparatorFromArgs(runtime, args, 1);
RubyIO io = (RubyIO)RubyFile.open(context, runtime.getFile(), new IRubyObject[] { filename }, Block.NULL_BLOCK);
if (!io.isNil()) {
try {
IRubyObject str = io.getline(runtime, separator);
while (!str.isNil()) {
block.yield(context, str);
str = io.getline(runtime, separator);
}
} finally {
io.close();
}
}
return runtime.getNil();
}
private static RubyIO convertToIO(ThreadContext context, IRubyObject obj) {
return (RubyIO)TypeConverter.convertToType(obj, context.getRuntime().getIO(), MethodIndex.TO_IO, "to_io");
}
private static boolean registerSelect(ThreadContext context, Selector selector, IRubyObject obj, RubyIO ioObj, int ops) throws IOException {
Channel channel = ioObj.getChannel();
if (channel == null || !(channel instanceof SelectableChannel)) {
return false;
}
((SelectableChannel) channel).configureBlocking(false);
int real_ops = ((SelectableChannel) channel).validOps() & ops;
SelectionKey key = ((SelectableChannel) channel).keyFor(selector);
if (key == null) {
((SelectableChannel) channel).register(selector, real_ops, obj);
} else {
key.interestOps(key.interestOps()|real_ops);
}
return true;
}
@JRubyMethod(name = "select", required = 1, optional = 3, meta = true)
public static IRubyObject select(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return select_static(context, context.getRuntime(), args);
}
private static void checkArrayType(Ruby runtime, IRubyObject obj) {
if (!(obj instanceof RubyArray)) {
throw runtime.newTypeError("wrong argument type "
+ obj.getMetaClass().getName() + " (expected Array)");
}
}
public static IRubyObject select_static(ThreadContext context, Ruby runtime, IRubyObject[] args) {
try {
Set pending = new HashSet();
Set unselectable_reads = new HashSet();
Set unselectable_writes = new HashSet();
Selector selector = Selector.open();
if (!args[0].isNil()) {
// read
checkArrayType(runtime, args[0]);
for (Iterator i = ((RubyArray) args[0]).getList().iterator(); i.hasNext(); ) {
IRubyObject obj = (IRubyObject) i.next();
RubyIO ioObj = convertToIO(context, obj);
if (registerSelect(context, selector, obj, ioObj, SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) {
if (ioObj.writeDataBuffered()) {
pending.add(obj);
}
} else {
if (( ioObj.openFile.getMode() & OpenFile.READABLE ) != 0) {
unselectable_reads.add(obj);
}
}
}
}
if (args.length > 1 && !args[1].isNil()) {
// write
checkArrayType(runtime, args[1]);
for (Iterator i = ((RubyArray) args[1]).getList().iterator(); i.hasNext(); ) {
IRubyObject obj = (IRubyObject) i.next();
RubyIO ioObj = convertToIO(context, obj);
if (!registerSelect(context, selector, obj, ioObj, SelectionKey.OP_WRITE)) {
if (( ioObj.openFile.getMode() & OpenFile.WRITABLE ) != 0) {
unselectable_writes.add(obj);
}
}
}
}
if (args.length > 2 && !args[2].isNil()) {
checkArrayType(runtime, args[2]);
// Java's select doesn't do anything about this, so we leave it be.
}
final boolean has_timeout = ( args.length > 3 && !args[3].isNil() );
long timeout = 0;
if(has_timeout) {
IRubyObject timeArg = args[3];
if (timeArg instanceof RubyFloat) {
timeout = Math.round(((RubyFloat) timeArg).getDoubleValue() * 1000);
} else if (timeArg instanceof RubyFixnum) {
timeout = Math.round(((RubyFixnum) timeArg).getDoubleValue() * 1000);
} else { // TODO: MRI also can hadle Bignum here
throw runtime.newTypeError("can't convert "
+ timeArg.getMetaClass().getName() + " into time interval");
}
if (timeout < 0) {
throw runtime.newArgumentError("negative timeout given");
}
}
if (pending.isEmpty() && unselectable_reads.isEmpty() && unselectable_writes.isEmpty()) {
if (has_timeout) {
if (timeout==0) {
selector.selectNow();
} else {
selector.select(timeout);
}
} else {
selector.select();
}
} else {
selector.selectNow();
}
List r = new ArrayList();
List w = new ArrayList();
List e = new ArrayList();
for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) {
SelectionKey key = (SelectionKey) i.next();
if ((key.interestOps() & key.readyOps()
& (SelectionKey.OP_READ|SelectionKey.OP_ACCEPT|SelectionKey.OP_CONNECT)) != 0) {
r.add(key.attachment());
pending.remove(key.attachment());
}
if ((key.interestOps() & key.readyOps() & (SelectionKey.OP_WRITE)) != 0) {
w.add(key.attachment());
}
}
r.addAll(pending);
r.addAll(unselectable_reads);
w.addAll(unselectable_writes);
// make all sockets blocking as configured again
for (Iterator i = selector.keys().iterator(); i.hasNext(); ) {
SelectionKey key = (SelectionKey) i.next();
SelectableChannel channel = key.channel();
synchronized(channel.blockingLock()) {
RubyIO originalIO = (RubyIO) TypeConverter.convertToType(
(IRubyObject) key.attachment(), runtime.getIO(),
MethodIndex.TO_IO, "to_io");
boolean blocking = originalIO.getBlocking();
key.cancel();
channel.configureBlocking(blocking);
}
}
selector.close();
if (r.size() == 0 && w.size() == 0 && e.size() == 0) {
return runtime.getNil();
}
List ret = new ArrayList();
ret.add(RubyArray.newArray(runtime, r));
ret.add(RubyArray.newArray(runtime, w));
ret.add(RubyArray.newArray(runtime, e));
return RubyArray.newArray(runtime, ret);
} catch(IOException e) {
throw runtime.newIOError(e.getMessage());
}
}
public static IRubyObject read(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
switch (args.length) {
case 0: throw context.getRuntime().newArgumentError(0, 1);
case 1: return read(context, recv, args[0], block);
case 2: return read(context, recv, args[0], args[1], block);
case 3: return read(context, recv, args[0], args[1], args[2], block);
default: throw context.getRuntime().newArgumentError(args.length, 3);
}
}
@JRubyMethod(name = "read", meta = true)
public static IRubyObject read(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
IRubyObject[] fileArguments = new IRubyObject[] {arg0};
RubyIO file = (RubyIO) RubyKernel.open(context, recv, fileArguments, block);
try {
return file.read(context);
} finally {
file.close();
}
}
@JRubyMethod(name = "read", meta = true)
public static IRubyObject read(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
IRubyObject[] fileArguments = new IRubyObject[] {arg0};
RubyIO file = (RubyIO) RubyKernel.open(context, recv, fileArguments, block);
try {
if (!arg1.isNil()) {
return file.read(context, arg1);
} else {
return file.read(context);
}
} finally {
file.close();
}
}
@JRubyMethod(name = "read", meta = true)
public static IRubyObject read(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
IRubyObject[] fileArguments = new IRubyObject[]{arg0};
RubyIO file = (RubyIO) RubyKernel.open(context, recv, fileArguments, block);
if (!arg2.isNil()) {
file.seek(context, arg2);
}
try {
if (!arg1.isNil()) {
return file.read(context, arg1);
} else {
return file.read(context);
}
} finally {
file.close();
}
}
@JRubyMethod(name = "readlines", required = 1, optional = 1, meta = true)
public static RubyArray readlines(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
int count = args.length;
IRubyObject[] fileArguments = new IRubyObject[]{ args[0].convertToString() };
IRubyObject[] separatorArguments = count >= 2 ? new IRubyObject[]{args[1]} : IRubyObject.NULL_ARRAY;
RubyIO file = (RubyIO) RubyKernel.open(context, recv, fileArguments, block);
try {
return file.readlines(context, separatorArguments);
} finally {
file.close();
}
}
@JRubyMethod(name = "popen", required = 1, optional = 1, meta = true)
public static IRubyObject popen(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
int mode;
IRubyObject cmdObj = args[0].convertToString();
runtime.checkSafeString(cmdObj);
if ("-".equals(cmdObj.toString())) {
throw runtime.newNotImplementedError("popen(\"-\") is unimplemented");
}
try {
if (args.length == 1) {
mode = ModeFlags.RDONLY;
} else if (args[1] instanceof RubyFixnum) {
mode = RubyFixnum.num2int(args[1]);
} else {
mode = getIOModesIntFromString(runtime, args[1].convertToString().toString());
}
ModeFlags modes = new ModeFlags(mode);
ShellLauncher.POpenProcess process = ShellLauncher.popen(runtime, cmdObj, modes);
RubyIO io = new RubyIO(runtime, process, modes);
if (block.isGiven()) {
try {
return block.yield(context, io);
} finally {
if (io.openFile.isOpen()) {
io.close();
}
runtime.getGlobalVariables().set("$?", RubyProcess.RubyStatus.newProcessStatus(runtime, (process.waitFor() * 256)));
}
}
return io;
} catch (InvalidValueException ex) {
throw runtime.newErrnoEINVALError();
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
} catch (InterruptedException e) {
throw runtime.newThreadError("unexpected interrupt");
}
}
// NIO based pipe
@JRubyMethod(name = "pipe", meta = true)
public static IRubyObject pipe(ThreadContext context, IRubyObject recv) throws Exception {
// TODO: This isn't an exact port of MRI's pipe behavior, so revisit
Ruby runtime = context.getRuntime();
Pipe pipe = Pipe.open();
RubyIO source = new RubyIO(runtime, pipe.source());
RubyIO sink = new RubyIO(runtime, pipe.sink());
sink.openFile.getMainStream().setSync(true);
return runtime.newArrayNoCopy(new IRubyObject[] { source, sink });
}
@JRubyMethod(name = "copy_stream", meta = true, compat = RUBY1_9)
public static IRubyObject copy_stream(ThreadContext context, IRubyObject recv,
IRubyObject stream1, IRubyObject stream2) throws IOException {
RubyIO io1 = (RubyIO)stream1;
RubyIO io2 = (RubyIO)stream2;
ChannelDescriptor d1 = io1.openFile.getMainStream().getDescriptor();
if (!d1.isSeekable()) {
throw context.getRuntime().newTypeError("only supports file-to-file copy");
}
ChannelDescriptor d2 = io2.openFile.getMainStream().getDescriptor();
if (!d2.isSeekable()) {
throw context.getRuntime().newTypeError("only supports file-to-file copy");
}
FileChannel f1 = (FileChannel)d1.getChannel();
FileChannel f2 = (FileChannel)d2.getChannel();
long size = f1.size();
f1.transferTo(f2.position(), size, f2);
return context.getRuntime().newFixnum(size);
}
/**
* Add a thread to the list of blocking threads for this IO.
*
* @param thread A thread blocking on this IO
*/
public synchronized void addBlockingThread(RubyThread thread) {
if (blockingThreads == null) {
blockingThreads = new ArrayList<RubyThread>(1);
}
blockingThreads.add(thread);
}
/**
* Remove a thread from the list of blocking threads for this IO.
*
* @param thread A thread blocking on this IO
*/
public synchronized void removeBlockingThread(RubyThread thread) {
if (blockingThreads == null) {
return;
}
for (int i = 0; i < blockingThreads.size(); i++) {
if (blockingThreads.get(i) == thread) {
// not using remove(Object) here to avoid the equals() call
blockingThreads.remove(i);
}
}
}
/**
* Fire an IOError in all threads blocking on this IO object
*/
protected synchronized void interruptBlockingThreads() {
if (blockingThreads == null) {
return;
}
for (int i = 0; i < blockingThreads.size(); i++) {
RubyThread thread = blockingThreads.get(i);
// raise will also wake the thread from selection
thread.raise(new IRubyObject[] {getRuntime().newIOError("stream closed").getException()}, Block.NULL_BLOCK);
}
}
}
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2005 Thomas E Enebo <enebo@acm.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.anno.JRubyClass;
import org.jruby.ast.ArgsNode;
import org.jruby.ast.ArgumentNode;
import org.jruby.ast.ListNode;
import org.jruby.ast.LocalAsgnNode;
import org.jruby.javasupport.Java;
import org.jruby.javasupport.JavaObject;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.Library;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.ast.Node;
import org.jruby.compiler.ASTInspector;
import org.jruby.compiler.ASTCompiler;
import org.jruby.compiler.impl.StandardASMCompiler;
import org.jruby.internal.runtime.methods.MethodArgs;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.InterpretedBlock;
import org.jruby.runtime.ThreadContext;
import org.jruby.util.TypeConverter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.util.TraceClassVisitor;
/**
* Module which defines JRuby-specific methods for use.
*/
@JRubyModule(name="JRuby")
public class RubyJRuby {
public static RubyModule createJRuby(Ruby runtime) {
ThreadContext context = runtime.getCurrentContext();
runtime.getKernel().callMethod(context, "require", runtime.newString("java"));
RubyModule jrubyModule = runtime.defineModule("JRuby");
jrubyModule.defineAnnotatedMethods(RubyJRuby.class);
RubyClass compiledScriptClass = jrubyModule.defineClassUnder("CompiledScript",runtime.getObject(), runtime.getObject().getAllocator());
compiledScriptClass.attr_accessor(context, new IRubyObject[]{runtime.newSymbol("name"), runtime.newSymbol("class_name"), runtime.newSymbol("original_script"), runtime.newSymbol("code")});
compiledScriptClass.defineAnnotatedMethods(JRubyCompiledScript.class);
return jrubyModule;
}
public static RubyModule createJRubyExt(Ruby runtime) {
runtime.getKernel().callMethod(runtime.getCurrentContext(),"require", runtime.newString("java"));
RubyModule mJRubyExt = runtime.getOrCreateModule("JRuby").defineModuleUnder("Extensions");
mJRubyExt.defineAnnotatedMethods(JRubyExtensions.class);
runtime.getObject().includeModule(mJRubyExt);
return mJRubyExt;
}
public static class ExtLibrary implements Library {
public void load(Ruby runtime, boolean wrap) throws IOException {
RubyJRuby.createJRubyExt(runtime);
runtime.getMethod().defineAnnotatedMethods(MethodExtensions.class);
}
}
public static class TypeLibrary implements Library {
public void load(Ruby runtime, boolean wrap) throws IOException {
RubyModule jrubyType = runtime.defineModule("Type");
jrubyType.defineAnnotatedMethods(TypeLibrary.class);
}
@JRubyMethod(module = true)
public static IRubyObject coerce_to(ThreadContext context, IRubyObject self, IRubyObject object, IRubyObject clazz, IRubyObject method) {
Ruby ruby = object.getRuntime();
if (!(clazz instanceof RubyClass)) {
throw ruby.newTypeError(clazz, ruby.getClassClass());
}
if (!(method instanceof RubySymbol)) {
throw ruby.newTypeError(method, ruby.getSymbol());
}
RubyClass rubyClass = (RubyClass)clazz;
RubySymbol methodSym = (RubySymbol)method;
return TypeConverter.convertToTypeOrRaise(object, rubyClass, methodSym.asJavaString());
}
}
@JRubyMethod(name = "runtime", frame = true, module = true)
public static IRubyObject runtime(IRubyObject recv, Block unusedBlock) {
return Java.java_to_ruby(recv, JavaObject.wrap(recv.getRuntime(), recv.getRuntime()), Block.NULL_BLOCK);
}
@JRubyMethod(name = "objectspace", frame = true, module = true)
public static IRubyObject getObjectSpaceEnabled(IRubyObject recv, Block b) {
Ruby runtime = recv.getRuntime();
return RubyBoolean.newBoolean(
runtime, runtime.isObjectSpaceEnabled());
}
@JRubyMethod(name = "objectspace=", required = 1, frame = true, module = true)
public static IRubyObject setObjectSpaceEnabled(
IRubyObject recv, IRubyObject arg, Block b) {
Ruby runtime = recv.getRuntime();
runtime.setObjectSpaceEnabled(arg.isTrue());
return runtime.getNil();
}
@JRubyMethod(name = {"parse", "ast_for"}, optional = 3, frame = true, module = true)
public static IRubyObject parse(IRubyObject recv, IRubyObject[] args, Block block) {
if(block.isGiven()) {
if(block.getBody() instanceof org.jruby.runtime.CompiledBlock) {
throw new RuntimeException("Cannot compile an already compiled block. Use -J-Djruby.jit.enabled=false to avoid this problem.");
}
Arity.checkArgumentCount(recv.getRuntime(),args,0,0);
return Java.java_to_ruby(recv, JavaObject.wrap(recv.getRuntime(), ((InterpretedBlock)block.getBody()).getIterNode().getBodyNode()), Block.NULL_BLOCK);
} else {
Arity.checkArgumentCount(recv.getRuntime(),args,1,3);
String filename = "-";
boolean extraPositionInformation = false;
RubyString content = args[0].convertToString();
if(args.length>1) {
filename = args[1].convertToString().toString();
if(args.length>2) {
extraPositionInformation = args[2].isTrue();
}
}
return Java.java_to_ruby(recv, JavaObject.wrap(recv.getRuntime(),
recv.getRuntime().parse(content.getByteList(), filename, null, 0, extraPositionInformation)), Block.NULL_BLOCK);
}
}
@JRubyMethod(name = "compile", optional = 3, frame = true, module = true)
public static IRubyObject compile(IRubyObject recv, IRubyObject[] args, Block block) {
Node node;
String filename;
RubyString content;
if(block.isGiven()) {
Arity.checkArgumentCount(recv.getRuntime(),args,0,0);
if(block.getBody() instanceof org.jruby.runtime.CompiledBlock) {
throw new RuntimeException("Cannot compile an already compiled block. Use -J-Djruby.jit.enabled=false to avoid this problem.");
}
content = RubyString.newEmptyString(recv.getRuntime());
Node bnode = ((InterpretedBlock)block.getBody()).getIterNode().getBodyNode();
node = new org.jruby.ast.RootNode(bnode.getPosition(), block.getBinding().getDynamicScope(), bnode);
filename = "__block_" + node.getPosition().getFile();
} else {
Arity.checkArgumentCount(recv.getRuntime(),args,1,3);
filename = "-";
boolean extraPositionInformation = false;
content = args[0].convertToString();
if(args.length>1) {
filename = args[1].convertToString().toString();
if(args.length>2) {
extraPositionInformation = args[2].isTrue();
}
}
node = recv.getRuntime().parse(content.getByteList(), filename, null, 0, extraPositionInformation);
}
String classname;
if (filename.equals("-e")) {
classname = "__dash_e__";
} else {
classname = filename.replace('\\', '/').replaceAll(".rb", "").replaceAll("-","_dash_");
}
ASTInspector inspector = new ASTInspector();
inspector.inspect(node);
StandardASMCompiler asmCompiler = new StandardASMCompiler(classname, filename);
ASTCompiler compiler = new ASTCompiler();
compiler.compileRoot(node, asmCompiler, inspector);
byte[] bts = asmCompiler.getClassByteArray();
IRubyObject compiledScript = ((RubyModule)recv).fastGetConstant("CompiledScript").callMethod(recv.getRuntime().getCurrentContext(),"new");
compiledScript.callMethod(recv.getRuntime().getCurrentContext(), "name=", recv.getRuntime().newString(filename));
compiledScript.callMethod(recv.getRuntime().getCurrentContext(), "class_name=", recv.getRuntime().newString(classname));
compiledScript.callMethod(recv.getRuntime().getCurrentContext(), "original_script=", content);
compiledScript.callMethod(recv.getRuntime().getCurrentContext(), "code=", Java.java_to_ruby(recv, JavaObject.wrap(recv.getRuntime(), bts), Block.NULL_BLOCK));
return compiledScript;
}
@JRubyMethod(name = "reference", required = 1, module = true)
public static IRubyObject reference(IRubyObject recv, IRubyObject obj) {
return Java.wrap(recv.getRuntime().getJavaSupport().getJavaUtilitiesModule(),
JavaObject.wrap(recv.getRuntime(), obj));
}
@JRubyMethod(name = "dereference", required = 1, module = true)
public static IRubyObject dereference(ThreadContext context, IRubyObject recv, IRubyObject obj) {
if (!(obj.dataGetStruct() instanceof JavaObject)) {
throw context.getRuntime().newTypeError("got " + obj + ", expected wrapped Java object");
}
Object unwrapped = JavaUtil.unwrapJavaObject(obj);
if (!(unwrapped instanceof IRubyObject)) {
throw context.getRuntime().newTypeError("got " + obj + ", expected Java-wrapped Ruby object");
}
return (IRubyObject)unwrapped;
}
@JRubyClass(name="JRuby::CompiledScript")
public static class JRubyCompiledScript {
@JRubyMethod(name = "to_s")
public static IRubyObject compiled_script_to_s(IRubyObject recv) {
return recv.getInstanceVariables().fastGetInstanceVariable("@original_script");
}
@JRubyMethod(name = "inspect")
public static IRubyObject compiled_script_inspect(IRubyObject recv) {
return recv.getRuntime().newString("#<JRuby::CompiledScript " + recv.getInstanceVariables().fastGetInstanceVariable("@name") + ">");
}
@JRubyMethod(name = "inspect_bytecode")
public static IRubyObject compiled_script_inspect_bytecode(IRubyObject recv) {
StringWriter sw = new StringWriter();
ClassReader cr = new ClassReader((byte[])org.jruby.javasupport.JavaUtil.convertRubyToJava(recv.getInstanceVariables().fastGetInstanceVariable("@code"),byte[].class));
TraceClassVisitor cv = new TraceClassVisitor(new PrintWriter(sw));
cr.accept(cv, ClassReader.SKIP_DEBUG);
return recv.getRuntime().newString(sw.toString());
}
}
@JRubyModule(name="JRubyExtensions")
public static class JRubyExtensions {
@JRubyMethod(name = "steal_method", required = 2, module = true)
public static IRubyObject steal_method(IRubyObject recv, IRubyObject type, IRubyObject methodName) {
RubyModule to_add = null;
if(recv instanceof RubyModule) {
to_add = (RubyModule)recv;
} else {
to_add = recv.getSingletonClass();
}
String name = methodName.toString();
if(!(type instanceof RubyModule)) {
throw recv.getRuntime().newArgumentError("First argument must be a module/class");
}
DynamicMethod method = ((RubyModule)type).searchMethod(name);
if(method == null || method.isUndefined()) {
throw recv.getRuntime().newArgumentError("No such method " + name + " on " + type);
}
to_add.addMethod(name, method);
return recv.getRuntime().getNil();
}
@JRubyMethod(name = "steal_methods", required = 1, rest = true, module = true)
public static IRubyObject steal_methods(IRubyObject recv, IRubyObject[] args) {
IRubyObject type = args[0];
for(int i=1;i<args.length;i++) {
steal_method(recv, type, args[i]);
}
return recv.getRuntime().getNil();
}
}
public static class MethodExtensions {
@JRubyMethod(name = "args")
public static IRubyObject methodArgs(IRubyObject recv) {
Ruby ruby = recv.getRuntime();
RubyMethod rubyMethod = (RubyMethod)recv;
DynamicMethod method = rubyMethod.method;
if (method instanceof MethodArgs) {
MethodArgs interpMethod = (MethodArgs)method;
ArgsNode args = interpMethod.getArgsNode();
RubyArray argsArray = RubyArray.newArray(ruby);
RubyArray reqArray = RubyArray.newArray(ruby);
ListNode requiredArgs = args.getArgs();
for (int i = 0; requiredArgs != null && i < requiredArgs.size(); i++) {
ArgumentNode arg = (ArgumentNode)requiredArgs.get(i);
reqArray.append(RubySymbol.newSymbol(ruby, arg.getName()));
}
argsArray.append(reqArray);
RubyArray optArray = RubyArray.newArray(ruby);
ListNode optArgs = args.getOptArgs();
for (int i = 0; optArgs != null && i < optArgs.size(); i++) {
LocalAsgnNode arg = (LocalAsgnNode)optArgs.get(i);
optArray.append(RubySymbol.newSymbol(ruby, arg.getName()));
}
argsArray.append(optArray);
if (args.getRestArgNode() != null) {
argsArray.append(RubySymbol.newSymbol(ruby, args.getRestArgNode().getName()));
} else {
argsArray.append(ruby.getNil());
}
if (args.getBlockArgNode() != null) {
argsArray.append(RubySymbol.newSymbol(ruby, args.getBlockArgNode().getName()));
} else {
argsArray.append(ruby.getNil());
}
return argsArray;
}
throw ruby.newTypeError("Method args are only available for standard interpreted or jitted methods");
}
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Kiel Hodges <jruby-devel@selfsosoft.com>
* Copyright (C) 2006 Evan Buswell <evan@heron.sytes.net>
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
* Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import static org.jruby.anno.FrameField.*;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.evaluator.ASTInterpreter;
import org.jruby.exceptions.JumpException;
import org.jruby.exceptions.MainExitException;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.JumpTarget;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.Frame;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import static org.jruby.runtime.Visibility.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.IAutoloadMethod;
import org.jruby.runtime.load.LoadService;
import org.jruby.util.IdUtil;
import org.jruby.util.ShellLauncher;
import org.jruby.util.TypeConverter;
/**
* Note: For CVS history, see KernelModule.java.
*/
@JRubyModule(name="Kernel")
public class RubyKernel {
public final static Class<?> IRUBY_OBJECT = IRubyObject.class;
public static RubyModule createKernelModule(Ruby runtime) {
RubyModule module = runtime.defineModule("Kernel");
runtime.setKernel(module);
module.defineAnnotatedMethods(RubyKernel.class);
module.defineAnnotatedMethods(RubyObject.class);
runtime.setRespondToMethod(module.searchMethod("respond_to?"));
module.setFlag(RubyObject.USER7_F, false); //Kernel is the only Module that doesn't need an implementor
return module;
}
@JRubyMethod(name = "at_exit", frame = true, module = true, visibility = PRIVATE)
public static IRubyObject at_exit(ThreadContext context, IRubyObject recv, Block block) {
return context.getRuntime().pushExitBlock(context.getRuntime().newProc(Block.Type.PROC, block));
}
@JRubyMethod(name = "autoload?", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject autoload_p(ThreadContext context, final IRubyObject recv, IRubyObject symbol) {
Ruby runtime = context.getRuntime();
RubyModule module = recv instanceof RubyModule ? (RubyModule) recv : runtime.getObject();
String name = module.getName() + "::" + symbol.asJavaString();
IAutoloadMethod autoloadMethod = runtime.getLoadService().autoloadFor(name);
if (autoloadMethod == null) return runtime.getNil();
return runtime.newString(autoloadMethod.file());
}
@JRubyMethod(name = "autoload", required = 2, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject autoload(final IRubyObject recv, IRubyObject symbol, final IRubyObject file) {
Ruby runtime = recv.getRuntime();
final LoadService loadService = runtime.getLoadService();
String nonInternedName = symbol.asJavaString();
if (!IdUtil.isValidConstantName(nonInternedName)) {
throw runtime.newNameError("autoload must be constant name", nonInternedName);
}
RubyString fileString = file.convertToString();
if (fileString.isEmpty()) {
throw runtime.newArgumentError("empty file name");
}
final String baseName = symbol.asJavaString().intern(); // interned, OK for "fast" methods
final RubyModule module = recv instanceof RubyModule ? (RubyModule) recv : runtime.getObject();
String nm = module.getName() + "::" + baseName;
IRubyObject existingValue = module.fastFetchConstant(baseName);
if (existingValue != null && existingValue != RubyObject.UNDEF) return runtime.getNil();
module.fastStoreConstant(baseName, RubyObject.UNDEF);
loadService.addAutoload(nm, new IAutoloadMethod() {
public String file() {
return file.toString();
}
/**
* @see org.jruby.runtime.load.IAutoloadMethod#load(Ruby, String)
*/
public IRubyObject load(Ruby runtime, String name) {
boolean required = loadService.require(file());
// File to be loaded by autoload has already been or is being loaded.
if (!required) return null;
return module.fastGetConstant(baseName);
}
});
return runtime.getNil();
}
@JRubyMethod(name = "method_missing", rest = true, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject method_missing(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
if (args.length == 0 || !(args[0] instanceof RubySymbol)) throw runtime.newArgumentError("no id given");
Visibility lastVis = context.getLastVisibility();
CallType lastCallType = context.getLastCallType();
// create a lightweight thunk
IRubyObject msg = new RubyNameError.RubyNameErrorMessage(runtime,
recv,
args[0],
lastVis,
lastCallType);
final IRubyObject[]exArgs;
final RubyClass exc;
if (lastCallType != CallType.VARIABLE) {
exc = runtime.getNoMethodError();
exArgs = new IRubyObject[]{msg, args[0], RubyArray.newArrayNoCopy(runtime, args, 1)};
} else {
exc = runtime.getNameError();
exArgs = new IRubyObject[]{msg, args[0]};
}
throw new RaiseException((RubyException)exc.newInstance(context, exArgs, Block.NULL_BLOCK));
}
@JRubyMethod(name = "open", required = 1, optional = 2, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
String arg = args[0].convertToString().toString();
Ruby runtime = context.getRuntime();
if (arg.startsWith("|")) {
String command = arg.substring(1);
// exec process, create IO with process
return RubyIO.popen(context, runtime.getIO(), new IRubyObject[] {runtime.newString(command)}, block);
}
return RubyFile.open(context, runtime.getFile(), args, block);
}
@JRubyMethod(name = "getc", module = true, visibility = PRIVATE)
public static IRubyObject getc(ThreadContext context, IRubyObject recv) {
context.getRuntime().getWarnings().warn(ID.DEPRECATED_METHOD, "getc is obsolete; use STDIN.getc instead", "getc", "STDIN.getc");
IRubyObject defin = context.getRuntime().getGlobalVariables().get("$stdin");
return defin.callMethod(context, "getc");
}
@JRubyMethod(name = "gets", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject gets(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return RubyArgsFile.gets(context, context.getRuntime().getGlobalVariables().get("$<"), args);
}
@JRubyMethod(name = "abort", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject abort(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if(args.length == 1) {
context.getRuntime().getGlobalVariables().get("$stderr").callMethod(context,"puts",args[0]);
}
throw new MainExitException(1,true);
}
@JRubyMethod(name = "Array", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_array(ThreadContext context, IRubyObject recv, IRubyObject object) {
IRubyObject value = object.checkArrayType();
if (value.isNil()) {
if (object.getMetaClass().searchMethod("to_a").getImplementationClass() != context.getRuntime().getKernel()) {
value = object.callMethod(context, MethodIndex.TO_A, "to_a");
if (!(value instanceof RubyArray)) throw context.getRuntime().newTypeError("`to_a' did not return Array");
return value;
} else {
return context.getRuntime().newArray(object);
}
}
return value;
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv) {
return RuntimeHelpers.invoke(context, context.getRuntime().getComplex(), "convert");
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return RuntimeHelpers.invoke(context, context.getRuntime().getComplex(), "convert", arg);
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return RuntimeHelpers.invoke(context, context.getRuntime().getComplex(), "convert", arg0, arg1);
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv) {
return RuntimeHelpers.invoke(context, context.getRuntime().getRational(), "convert");
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return RuntimeHelpers.invoke(context, context.getRuntime().getRational(), "convert", arg);
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return RuntimeHelpers.invoke(context, context.getRuntime().getRational(), "convert", arg0, arg1);
}
@JRubyMethod(name = "Float", module = true, visibility = PRIVATE)
public static IRubyObject new_float(IRubyObject recv, IRubyObject object) {
if(object instanceof RubyFixnum){
return RubyFloat.newFloat(object.getRuntime(), ((RubyFixnum)object).getDoubleValue());
}else if(object instanceof RubyFloat){
return object;
}else if(object instanceof RubyBignum){
return RubyFloat.newFloat(object.getRuntime(), RubyBignum.big2dbl((RubyBignum)object));
}else if(object instanceof RubyString){
if(((RubyString)object).getByteList().realSize == 0){ // rb_cstr_to_dbl case
throw recv.getRuntime().newArgumentError("invalid value for Float(): " + object.inspect());
}
return RubyNumeric.str2fnum(recv.getRuntime(),(RubyString)object,true);
}else if(object.isNil()){
throw recv.getRuntime().newTypeError("can't convert nil into Float");
} else {
RubyFloat rFloat = (RubyFloat)TypeConverter.convertToType(object, recv.getRuntime().getFloat(), MethodIndex.TO_F, "to_f");
if (Double.isNaN(rFloat.getDoubleValue())) throw recv.getRuntime().newArgumentError("invalid value for Float()");
return rFloat;
}
}
@JRubyMethod(name = "Integer", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_integer(ThreadContext context, IRubyObject recv, IRubyObject object) {
if (object instanceof RubyFloat) {
double val = ((RubyFloat)object).getDoubleValue();
if (val > (double) RubyFixnum.MAX && val < (double) RubyFixnum.MIN) {
return RubyNumeric.dbl2num(context.getRuntime(),((RubyFloat)object).getDoubleValue());
}
} else if (object instanceof RubyFixnum || object instanceof RubyBignum) {
return object;
} else if (object instanceof RubyString) {
return RubyNumeric.str2inum(context.getRuntime(),(RubyString)object,0,true);
}
IRubyObject tmp = TypeConverter.convertToType(object, context.getRuntime().getInteger(), MethodIndex.TO_INT, "to_int", false);
if (tmp.isNil()) return object.convertToInteger(MethodIndex.TO_I, "to_i");
return tmp;
}
@JRubyMethod(name = "String", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_string(ThreadContext context, IRubyObject recv, IRubyObject object) {
return TypeConverter.convertToType(object, context.getRuntime().getString(), MethodIndex.TO_S, "to_s");
}
@JRubyMethod(name = "p", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject p(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
IRubyObject defout = runtime.getGlobalVariables().get("$>");
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
defout.callMethod(context, "write", RubyObject.inspect(context, args[i]));
defout.callMethod(context, "write", runtime.newString("\n"));
}
}
if (defout instanceof RubyFile) {
((RubyFile)defout).flush();
}
return context.getRuntime().getNil();
}
/** rb_f_putc
*/
@JRubyMethod(name = "putc", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject putc(ThreadContext context, IRubyObject recv, IRubyObject ch) {
IRubyObject defout = context.getRuntime().getGlobalVariables().get("$>");
return defout.callMethod(context, "putc", ch);
}
@JRubyMethod(name = "puts", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject defout = context.getRuntime().getGlobalVariables().get("$>");
defout.callMethod(context, "puts", args);
return context.getRuntime().getNil();
}
@JRubyMethod(name = "print", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject print(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject defout = context.getRuntime().getGlobalVariables().get("$>");
defout.callMethod(context, "print", args);
return context.getRuntime().getNil();
}
@JRubyMethod(name = "printf", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject printf(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length != 0) {
IRubyObject defout = context.getRuntime().getGlobalVariables().get("$>");
if (!(args[0] instanceof RubyString)) {
defout = args[0];
args = ArgsUtil.popArray(args);
}
defout.callMethod(context, "write", RubyKernel.sprintf(recv, args));
}
return context.getRuntime().getNil();
}
@JRubyMethod(name = "readline", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject readline(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject line = gets(context, recv, args);
if (line.isNil()) throw context.getRuntime().newEOFError();
return line;
}
@JRubyMethod(name = "readlines", optional = 1, module = true, visibility = PRIVATE)
public static RubyArray readlines(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return RubyArgsFile.readlines(context, context.getRuntime().getGlobalVariables().get("$<"), args);
}
/** Returns value of $_.
*
* @throws TypeError if $_ is not a String or nil.
* @return value of $_ as String.
*/
private static RubyString getLastlineString(ThreadContext context, Ruby runtime) {
IRubyObject line = context.getPreviousFrame().getLastLine();
if (line.isNil()) {
throw runtime.newTypeError("$_ value need to be String (nil given).");
} else if (!(line instanceof RubyString)) {
throw runtime.newTypeError("$_ value need to be String (" + line.getMetaClass().getName() + " given).");
} else {
return (RubyString) line;
}
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject sub_bang(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return getLastlineString(context, context.getRuntime()).sub_bang(context, args, block);
}
@JRubyMethod(name = "sub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE)
public static IRubyObject sub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
return getLastlineString(context, context.getRuntime()).sub_bang(context, arg0, block);
}
@JRubyMethod(name = "sub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE)
public static IRubyObject sub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
return getLastlineString(context, context.getRuntime()).sub_bang(context, arg0, arg1, block);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.sub_bang(context, args, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "sub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.sub_bang(context, arg0, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "sub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.sub_bang(context, arg0, arg1, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject gsub_bang(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return getLastlineString(context, context.getRuntime()).gsub_bang(context, args, block);
}
@JRubyMethod(name = "gsub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject gsub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
return getLastlineString(context, context.getRuntime()).gsub_bang(context, arg0, block);
}
@JRubyMethod(name = "gsub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject gsub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
return getLastlineString(context, context.getRuntime()).gsub_bang(context, arg0, arg1, block);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.gsub_bang(context, args, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "gsub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.gsub_bang(context, arg0, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "gsub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.gsub_bang(context, arg0, arg1, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "chop!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject chop_bang(ThreadContext context, IRubyObject recv, Block block) {
return getLastlineString(context, context.getRuntime()).chop_bang();
}
@JRubyMethod(name = "chop", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject chop(ThreadContext context, IRubyObject recv, Block block) {
RubyString str = getLastlineString(context, context.getRuntime());
if (str.getByteList().realSize > 0) {
str = (RubyString) str.dup();
str.chop_bang();
context.getPreviousFrame().setLastLine(str);
}
return str;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the zero or one-arg versions.
*/
public static IRubyObject chomp_bang(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return getLastlineString(context, context.getRuntime()).chomp_bang(args);
}
@JRubyMethod(name = "chomp!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject chomp_bang(ThreadContext context, IRubyObject recv) {
return getLastlineString(context, context.getRuntime()).chomp_bang();
}
@JRubyMethod(name = "chomp!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject chomp_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
return getLastlineString(context, context.getRuntime()).chomp_bang(arg0);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the zero or one-arg versions.
*/
public static IRubyObject chomp(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyString str = getLastlineString(context, context.getRuntime());
RubyString dup = (RubyString) str.dup();
if (dup.chomp_bang(args).isNil()) {
return str;
}
context.getPreviousFrame().setLastLine(dup);
return dup;
}
@JRubyMethod(name = "chomp", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject chomp(ThreadContext context, IRubyObject recv) {
RubyString str = getLastlineString(context, context.getRuntime());
RubyString dup = (RubyString) str.dup();
if (dup.chomp_bang().isNil()) {
return str;
}
context.getPreviousFrame().setLastLine(dup);
return dup;
}
@JRubyMethod(name = "chomp", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE)
public static IRubyObject chomp(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
RubyString str = getLastlineString(context, context.getRuntime());
RubyString dup = (RubyString) str.dup();
if (dup.chomp_bang(arg0).isNil()) {
return str;
}
context.getPreviousFrame().setLastLine(dup);
return dup;
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
*
* @param context The thread context for the current thread
* @param recv The receiver of the method (usually a class that has included Kernel)
* @return
* @deprecated Use the versions with zero, one, or two args.
*/
public static IRubyObject split(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return getLastlineString(context, context.getRuntime()).split(context, args);
}
@JRubyMethod(name = "split", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = {LASTLINE, BACKREF})
public static IRubyObject split(ThreadContext context, IRubyObject recv) {
return getLastlineString(context, context.getRuntime()).split(context);
}
@JRubyMethod(name = "split", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = {LASTLINE, BACKREF})
public static IRubyObject split(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
return getLastlineString(context, context.getRuntime()).split(context, arg0);
}
@JRubyMethod(name = "split", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = {LASTLINE, BACKREF})
public static IRubyObject split(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return getLastlineString(context, context.getRuntime()).split(context, arg0, arg1);
}
@JRubyMethod(name = "scan", required = 1, frame = true, module = true, visibility = PRIVATE, reads = {LASTLINE, BACKREF}, writes = {LASTLINE, BACKREF})
public static IRubyObject scan(ThreadContext context, IRubyObject recv, IRubyObject pattern, Block block) {
return getLastlineString(context, context.getRuntime()).scan(context, pattern, block);
}
@JRubyMethod(name = "select", required = 1, optional = 3, module = true, visibility = PRIVATE)
public static IRubyObject select(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return RubyIO.select_static(context, context.getRuntime(), args);
}
@JRubyMethod(name = "sleep", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject sleep(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
long milliseconds;
if (args.length == 0) {
// Zero sleeps forever
milliseconds = 0;
} else {
if (!(args[0] instanceof RubyNumeric)) {
throw context.getRuntime().newTypeError("can't convert " + args[0].getMetaClass().getName() + "into time interval");
}
milliseconds = (long) (args[0].convertToFloat().getDoubleValue() * 1000);
if (milliseconds < 0) {
throw context.getRuntime().newArgumentError("time interval must be positive");
} else if (milliseconds == 0) {
// Explicit zero in MRI returns immediately
return context.getRuntime().newFixnum(0);
}
}
long startTime = System.currentTimeMillis();
RubyThread rubyThread = context.getThread();
do {
long loopStartTime = System.currentTimeMillis();
try {
rubyThread.sleep(milliseconds);
} catch (InterruptedException iExcptn) {
}
milliseconds -= (System.currentTimeMillis() - loopStartTime);
} while (milliseconds > 0);
return context.getRuntime().newFixnum(Math.round((System.currentTimeMillis() - startTime) / 1000.0));
}
// FIXME: Add at_exit and finalizers to exit, then make exit_bang not call those.
@JRubyMethod(name = "exit", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject exit(IRubyObject recv, IRubyObject[] args) {
exit(recv.getRuntime(), args, false);
return recv.getRuntime().getNil(); // not reached
}
@JRubyMethod(name = "exit!", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject exit_bang(IRubyObject recv, IRubyObject[] args) {
exit(recv.getRuntime(), args, true);
return recv.getRuntime().getNil(); // not reached
}
private static void exit(Ruby runtime, IRubyObject[] args, boolean hard) {
runtime.secure(4);
int status = 1;
if (args.length > 0) {
RubyObject argument = (RubyObject)args[0];
if (argument instanceof RubyFixnum) {
status = RubyNumeric.fix2int(argument);
} else {
status = argument.isFalse() ? 1 : 0;
}
}
if (hard) {
throw new MainExitException(status, true);
} else {
throw runtime.newSystemExit(status);
}
}
/** Returns an Array with the names of all global variables.
*
*/
@JRubyMethod(name = "global_variables", module = true, visibility = PRIVATE)
public static RubyArray global_variables(ThreadContext context, IRubyObject recv) {
Ruby runtime = context.getRuntime();
RubyArray globalVariables = runtime.newArray();
for (String globalVariableName : runtime.getGlobalVariables().getNames()) {
globalVariables.append(runtime.newString(globalVariableName));
}
return globalVariables;
}
/** Returns an Array with the names of all local variables.
*
*/
@JRubyMethod(name = "local_variables", module = true, visibility = PRIVATE)
public static RubyArray local_variables(ThreadContext context, IRubyObject recv) {
final Ruby runtime = context.getRuntime();
RubyArray localVariables = runtime.newArray();
for (String name: context.getCurrentScope().getAllNamesInScope()) {
if (IdUtil.isLocal(name)) localVariables.append(runtime.newString(name));
}
return localVariables;
}
@JRubyMethod(name = "binding", frame = true, module = true, visibility = PRIVATE)
public static RubyBinding binding(ThreadContext context, IRubyObject recv, Block block) {
return RubyBinding.newBinding(context.getRuntime());
}
@JRubyMethod(name = {"block_given?", "iterator?"}, frame = true, module = true, visibility = PRIVATE)
public static RubyBoolean block_given_p(ThreadContext context, IRubyObject recv, Block block) {
return context.getRuntime().newBoolean(context.getPreviousFrame().getBlock().isGiven());
}
@Deprecated
public static IRubyObject sprintf(IRubyObject recv, IRubyObject[] args) {
return sprintf(recv.getRuntime().getCurrentContext(), recv, args);
}
@JRubyMethod(name = {"sprintf", "format"}, required = 1, rest = true, module = true, visibility = PRIVATE)
public static IRubyObject sprintf(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length == 0) {
throw context.getRuntime().newArgumentError("sprintf must have at least one argument");
}
RubyString str = RubyString.stringValue(args[0]);
RubyArray newArgs = context.getRuntime().newArrayNoCopy(args);
newArgs.shift();
return str.op_format(context, newArgs);
}
@JRubyMethod(name = {"raise", "fail"}, optional = 3, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject raise(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
// FIXME: Pass block down?
Ruby runtime = context.getRuntime();
if (args.length == 0) {
IRubyObject lastException = runtime.getGlobalVariables().get("$!");
if (lastException.isNil()) {
throw new RaiseException(runtime, runtime.getRuntimeError(), "", false);
}
throw new RaiseException((RubyException) lastException);
}
IRubyObject exception;
if (args.length == 1) {
if (args[0] instanceof RubyString) {
throw new RaiseException((RubyException)runtime.getRuntimeError().newInstance(context, args, block));
}
if (!args[0].respondsTo("exception")) {
throw runtime.newTypeError("exception class/object expected");
}
exception = args[0].callMethod(context, "exception");
} else {
if (!args[0].respondsTo("exception")) {
throw runtime.newTypeError("exception class/object expected");
}
exception = args[0].callMethod(context, "exception", args[1]);
}
if (!runtime.fastGetClass("Exception").isInstance(exception)) {
throw runtime.newTypeError("exception object expected");
}
if (args.length == 3) {
((RubyException) exception).set_backtrace(args[2]);
}
if (runtime.getDebug().isTrue()) {
printExceptionSummary(context, runtime, (RubyException) exception);
}
throw new RaiseException((RubyException) exception);
}
private static void printExceptionSummary(ThreadContext context, Ruby runtime, RubyException rEx) {
Frame currentFrame = context.getCurrentFrame();
String msg = String.format("Exception `%s' at %s:%s - %s\n",
rEx.getMetaClass(),
currentFrame.getFile(), currentFrame.getLine() + 1,
rEx.to_s());
IRubyObject errorStream = runtime.getGlobalVariables().get("$stderr");
errorStream.callMethod(context, "write", runtime.newString(msg));
}
/**
* Require.
* MRI allows to require ever .rb files or ruby extension dll (.so or .dll depending on system).
* we allow requiring either .rb files or jars.
* @param recv ruby object used to call require (any object will do and it won't be used anyway).
* @param name the name of the file to require
**/
@JRubyMethod(name = "require", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject require(IRubyObject recv, IRubyObject name, Block block) {
Ruby runtime = recv.getRuntime();
if (runtime.getLoadService().require(name.convertToString().toString())) {
return runtime.getTrue();
}
return runtime.getFalse();
}
@JRubyMethod(name = "load", required = 1, optional = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject load(IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = recv.getRuntime();
RubyString file = args[0].convertToString();
boolean wrap = args.length == 2 ? args[1].isTrue() : false;
runtime.getLoadService().load(file.getByteList().toString(), wrap);
return runtime.getTrue();
}
@JRubyMethod(name = "eval", required = 1, optional = 3, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject eval(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
// string to eval
RubyString src = args[0].convertToString();
runtime.checkSafeString(src);
IRubyObject scope = args.length > 1 && !args[1].isNil() ? args[1] : null;
String file;
if (args.length > 2) {
file = args[2].convertToString().toString();
} else if (scope == null) {
file = "(eval)";
} else {
file = null;
}
int line;
if (args.length > 3) {
line = (int) args[3].convertToInteger().getLongValue();
} else if (scope == null) {
line = 0;
} else {
line = -1;
}
if (scope == null) scope = RubyBinding.newBindingForEval(context);
return ASTInterpreter.evalWithBinding(context, src, scope, file, line);
}
@JRubyMethod(name = "callcc", frame = true, module = true, visibility = PRIVATE)
public static IRubyObject callcc(ThreadContext context, IRubyObject recv, Block block) {
Ruby runtime = context.getRuntime();
runtime.getWarnings().warn(ID.EMPTY_IMPLEMENTATION, "Kernel#callcc: Continuations are not implemented in JRuby and will not work", "Kernel#callcc");
IRubyObject cc = runtime.getContinuation().callMethod(context, "new");
cc.dataWrapStruct(block);
return block.yield(context, cc);
}
@JRubyMethod(name = "caller", optional = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject caller(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
int level = args.length > 0 ? RubyNumeric.fix2int(args[0]) : 1;
if (level < 0) {
throw context.getRuntime().newArgumentError("negative level(" + level + ')');
}
return context.createCallerBacktrace(context.getRuntime(), level);
}
@JRubyMethod(name = "catch", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject rbCatch(ThreadContext context, IRubyObject recv, IRubyObject tag, Block block) {
CatchTarget target = new CatchTarget(tag.asJavaString());
try {
context.pushCatch(target);
return block.yield(context, tag);
} catch (JumpException.ThrowJump tj) {
if (tj.getTarget() == target) return (IRubyObject) tj.getValue();
throw tj;
} finally {
context.popCatch();
}
}
public static class CatchTarget implements JumpTarget {
private final String tag;
public CatchTarget(String tag) { this.tag = tag; }
public String getTag() { return tag; }
}
@JRubyMethod(name = "throw", required = 1, frame = true, optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject rbThrow(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
String tag = args[0].asJavaString();
CatchTarget[] catches = context.getActiveCatches();
String message = "uncaught throw `" + tag + "'";
// Ordering of array traversal not important, just intuitive
for (int i = catches.length - 1 ; i >= 0 ; i--) {
if (tag.equals(catches[i].getTag())) {
//Catch active, throw for catch to handle
throw new JumpException.ThrowJump(catches[i], args.length > 1 ? args[1] : runtime.getNil());
}
}
// No catch active for this throw
RubyThread currentThread = context.getThread();
if (currentThread == runtime.getThreadService().getMainThread()) {
throw runtime.newNameError(message, tag);
} else {
throw runtime.newThreadError(message + " in thread 0x" + Integer.toHexString(RubyInteger.fix2int(currentThread.id())));
}
}
@JRubyMethod(name = "trap", required = 1, frame = true, optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject trap(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
context.getRuntime().getLoadService().require("jsignal");
return RuntimeHelpers.invoke(context, recv, "__jtrap", args, block);
}
@JRubyMethod(name = "warn", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject warn(ThreadContext context, IRubyObject recv, IRubyObject message) {
Ruby runtime = context.getRuntime();
if (!runtime.getVerbose().isNil()) {
IRubyObject out = runtime.getGlobalVariables().get("$stderr");
RuntimeHelpers.invoke(context, out, "puts", message);
}
return runtime.getNil();
}
@JRubyMethod(name = "set_trace_func", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject set_trace_func(ThreadContext context, IRubyObject recv, IRubyObject trace_func, Block block) {
if (trace_func.isNil()) {
context.getRuntime().setTraceFunction(null);
} else if (!(trace_func instanceof RubyProc)) {
throw context.getRuntime().newTypeError("trace_func needs to be Proc.");
} else {
context.getRuntime().setTraceFunction((RubyProc) trace_func);
}
return trace_func;
}
@JRubyMethod(name = "trace_var", required = 1, optional = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject trace_var(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
if (args.length == 0) throw context.getRuntime().newArgumentError(0, 1);
RubyProc proc = null;
String var = args.length > 1 ? args[0].toString() : null;
// ignore if it's not a global var
if (var.charAt(0) != '$') return context.getRuntime().getNil();
if (args.length == 1) proc = RubyProc.newProc(context.getRuntime(), block, Block.Type.PROC);
if (args.length == 2) {
proc = (RubyProc)TypeConverter.convertToType(args[1], context.getRuntime().getProc(), 0, "to_proc", true);
}
context.getRuntime().getGlobalVariables().setTraceVar(var, proc);
return context.getRuntime().getNil();
}
@JRubyMethod(name = "untrace_var", required = 1, optional = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject untrace_var(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
if (args.length == 0) throw context.getRuntime().newArgumentError(0, 1);
String var = args.length >= 1 ? args[0].toString() : null;
// ignore if it's not a global var
if (var.charAt(0) != '$') return context.getRuntime().getNil();
if (args.length > 1) {
ArrayList<IRubyObject> success = new ArrayList<IRubyObject>();
for (int i = 1; i < args.length; i++) {
if (context.getRuntime().getGlobalVariables().untraceVar(var, args[i])) {
success.add(args[i]);
}
}
return RubyArray.newArray(context.getRuntime(), success);
} else {
context.getRuntime().getGlobalVariables().untraceVar(var);
}
return context.getRuntime().getNil();
}
@JRubyMethod(name = "singleton_method_added", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject singleton_method_added(ThreadContext context, IRubyObject recv, IRubyObject symbolId, Block block) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "singleton_method_removed", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject singleton_method_removed(ThreadContext context, IRubyObject recv, IRubyObject symbolId, Block block) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "singleton_method_undefined", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject singleton_method_undefined(ThreadContext context, IRubyObject recv, IRubyObject symbolId, Block block) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = {"proc", "lambda"}, frame = true, module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_8)
public static RubyProc proc(ThreadContext context, IRubyObject recv, Block block) {
return context.getRuntime().newProc(Block.Type.LAMBDA, block);
}
@Deprecated
public static RubyProc proc(IRubyObject recv, Block block) {
return recv.getRuntime().newProc(Block.Type.LAMBDA, block);
}
@JRubyMethod(name = {"lambda"}, frame = true, module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static RubyProc lambda(ThreadContext context, IRubyObject recv, Block block) {
return context.getRuntime().newProc(Block.Type.LAMBDA, block);
}
@JRubyMethod(name = {"proc"}, frame = true, module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static RubyProc proc_1_9(ThreadContext context, IRubyObject recv, Block block) {
return context.getRuntime().newProc(Block.Type.PROC, block);
}
@JRubyMethod(name = "loop", frame = true, module = true, visibility = PRIVATE)
public static IRubyObject loop(ThreadContext context, IRubyObject recv, Block block) {
while (true) {
block.yield(context, context.getRuntime().getNil());
context.pollThreadEvents();
}
}
@JRubyMethod(name = "test", required = 2, optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject test(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length == 0) throw context.getRuntime().newArgumentError("wrong number of arguments");
int cmd;
if (args[0] instanceof RubyFixnum) {
cmd = (int)((RubyFixnum) args[0]).getLongValue();
} else if (args[0] instanceof RubyString &&
((RubyString) args[0]).getByteList().length() > 0) {
// MRI behavior: use first byte of string value if len > 0
cmd = ((RubyString) args[0]).getByteList().charAt(0);
} else {
cmd = (int) args[0].convertToInteger().getLongValue();
}
// MRI behavior: raise ArgumentError for 'unknown command' before
// checking number of args.
switch(cmd) {
case 'A': case 'b': case 'c': case 'C': case 'd': case 'e': case 'f': case 'g': case 'G':
case 'k': case 'M': case 'l': case 'o': case 'O': case 'p': case 'r': case 'R': case 's':
case 'S': case 'u': case 'w': case 'W': case 'x': case 'X': case 'z': case '=': case '<':
case '>': case '-':
break;
default:
throw context.getRuntime().newArgumentError("unknown command ?" + (char) cmd);
}
// MRI behavior: now check arg count
switch(cmd) {
case '-': case '=': case '<': case '>':
if (args.length != 3) throw context.getRuntime().newArgumentError(args.length, 3);
break;
default:
if (args.length != 2) throw context.getRuntime().newArgumentError(args.length, 2);
break;
}
switch (cmd) {
case 'A': // ?A | Time | Last access time for file1
return context.getRuntime().newFileStat(args[1].convertToString().toString(), false).atime();
case 'b': // ?b | boolean | True if file1 is a block device
return RubyFileTest.blockdev_p(recv, args[1]);
case 'c': // ?c | boolean | True if file1 is a character device
return RubyFileTest.chardev_p(recv, args[1]);
case 'C': // ?C | Time | Last change time for file1
return context.getRuntime().newFileStat(args[1].convertToString().toString(), false).ctime();
case 'd': // ?d | boolean | True if file1 exists and is a directory
return RubyFileTest.directory_p(recv, args[1]);
case 'e': // ?e | boolean | True if file1 exists
return RubyFileTest.exist_p(recv, args[1]);
case 'f': // ?f | boolean | True if file1 exists and is a regular file
return RubyFileTest.file_p(recv, args[1]);
case 'g': // ?g | boolean | True if file1 has the \CF{setgid} bit
return RubyFileTest.setgid_p(recv, args[1]);
case 'G': // ?G | boolean | True if file1 exists and has a group ownership equal to the caller's group
return RubyFileTest.grpowned_p(recv, args[1]);
case 'k': // ?k | boolean | True if file1 exists and has the sticky bit set
return RubyFileTest.sticky_p(recv, args[1]);
case 'M': // ?M | Time | Last modification time for file1
return context.getRuntime().newFileStat(args[1].convertToString().toString(), false).mtime();
case 'l': // ?l | boolean | True if file1 exists and is a symbolic link
return RubyFileTest.symlink_p(recv, args[1]);
case 'o': // ?o | boolean | True if file1 exists and is owned by the caller's effective uid
return RubyFileTest.owned_p(recv, args[1]);
case 'O': // ?O | boolean | True if file1 exists and is owned by the caller's real uid
return RubyFileTest.rowned_p(recv, args[1]);
case 'p': // ?p | boolean | True if file1 exists and is a fifo
return RubyFileTest.pipe_p(recv, args[1]);
case 'r': // ?r | boolean | True if file1 is readable by the effective uid/gid of the caller
return RubyFileTest.readable_p(recv, args[1]);
case 'R': // ?R | boolean | True if file is readable by the real uid/gid of the caller
// FIXME: Need to implement an readable_real_p in FileTest
return RubyFileTest.readable_p(recv, args[1]);
case 's': // ?s | int/nil | If file1 has nonzero size, return the size, otherwise nil
return RubyFileTest.size_p(recv, args[1]);
case 'S': // ?S | boolean | True if file1 exists and is a socket
return RubyFileTest.socket_p(recv, args[1]);
case 'u': // ?u | boolean | True if file1 has the setuid bit set
return RubyFileTest.setuid_p(recv, args[1]);
case 'w': // ?w | boolean | True if file1 exists and is writable by effective uid/gid
return RubyFileTest.writable_p(recv, args[1]);
case 'W': // ?W | boolean | True if file1 exists and is writable by the real uid/gid
// FIXME: Need to implement an writable_real_p in FileTest
return RubyFileTest.writable_p(recv, args[1]);
case 'x': // ?x | boolean | True if file1 exists and is executable by the effective uid/gid
return RubyFileTest.executable_p(recv, args[1]);
case 'X': // ?X | boolean | True if file1 exists and is executable by the real uid/gid
return RubyFileTest.executable_real_p(recv, args[1]);
case 'z': // ?z | boolean | True if file1 exists and has a zero length
return RubyFileTest.zero_p(recv, args[1]);
case '=': // ?= | boolean | True if the modification times of file1 and file2 are equal
return context.getRuntime().newFileStat(args[1].convertToString().toString(), false).mtimeEquals(args[2]);
case '<': // ?< | boolean | True if the modification time of file1 is prior to that of file2
return context.getRuntime().newFileStat(args[1].convertToString().toString(), false).mtimeLessThan(args[2]);
case '>': // ?> | boolean | True if the modification time of file1 is after that of file2
return context.getRuntime().newFileStat(args[1].convertToString().toString(), false).mtimeGreaterThan(args[2]);
case '-': // ?- | boolean | True if file1 and file2 are identical
return RubyFileTest.identical_p(recv, args[1], args[2]);
default:
throw new InternalError("unreachable code reached!");
}
}
@JRubyMethod(name = "`", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject backquote(ThreadContext context, IRubyObject recv, IRubyObject aString) {
Ruby runtime = context.getRuntime();
ByteArrayOutputStream output = new ByteArrayOutputStream();
RubyString string = aString.convertToString();
int resultCode = ShellLauncher.runAndWait(runtime, new IRubyObject[] {string}, output);
runtime.getGlobalVariables().set("$?", RubyProcess.RubyStatus.newProcessStatus(runtime, resultCode));
return RubyString.newString(runtime, output.toByteArray());
}
@JRubyMethod(name = "srand", optional = 1, module = true, visibility = PRIVATE)
public static RubyInteger srand(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
long oldRandomSeed = runtime.getRandomSeed();
if (args.length > 0) {
RubyInteger integerSeed = args[0].convertToInteger(MethodIndex.TO_INT, "to_int");
runtime.setRandomSeed(integerSeed.getLongValue());
} else {
// Not sure how well this works, but it works much better than
// just currentTimeMillis by itself.
runtime.setRandomSeed(System.currentTimeMillis() ^
recv.hashCode() ^ runtime.incrementRandomSeedSequence() ^
runtime.getRandom().nextInt(Math.max(1, Math.abs((int)runtime.getRandomSeed()))));
}
runtime.getRandom().setSeed(runtime.getRandomSeed());
return runtime.newFixnum(oldRandomSeed);
}
@JRubyMethod(name = "rand", optional = 1, module = true, visibility = PRIVATE)
public static RubyNumeric rand(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
long ceil;
if (args.length == 0) {
ceil = 0;
} else if (args.length == 1) {
if (args[0] instanceof RubyBignum) {
byte[] bigCeilBytes = ((RubyBignum) args[0]).getValue().toByteArray();
BigInteger bigCeil = new BigInteger(bigCeilBytes).abs();
byte[] randBytes = new byte[bigCeilBytes.length];
runtime.getRandom().nextBytes(randBytes);
BigInteger result = new BigInteger(randBytes).abs().mod(bigCeil);
return new RubyBignum(runtime, result);
}
RubyInteger integerCeil = (RubyInteger)RubyKernel.new_integer(context, recv, args[0]);
ceil = Math.abs(integerCeil.getLongValue());
} else {
throw runtime.newArgumentError("wrong # of arguments(" + args.length + " for 1)");
}
if (ceil == 0) {
return RubyFloat.newFloat(runtime, runtime.getRandom().nextDouble());
}
if (ceil > Integer.MAX_VALUE) {
return runtime.newFixnum(Math.abs(runtime.getRandom().nextLong()) % ceil);
}
return runtime.newFixnum(runtime.getRandom().nextInt((int) ceil));
}
@JRubyMethod(name = "syscall", required = 1, optional = 9, module = true, visibility = PRIVATE)
public static IRubyObject syscall(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
throw context.getRuntime().newNotImplementedError("Kernel#syscall is not implemented in JRuby");
}
@JRubyMethod(name = {"system"}, required = 1, rest = true, module = true, visibility = PRIVATE)
public static RubyBoolean system(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int resultCode;
try {
resultCode = ShellLauncher.runAndWait(runtime, args);
} catch (Exception e) {
resultCode = 127;
}
runtime.getGlobalVariables().set("$?", RubyProcess.RubyStatus.newProcessStatus(runtime, resultCode));
return runtime.newBoolean(resultCode == 0);
}
@JRubyMethod(name = {"exec"}, required = 1, rest = true, module = true, visibility = PRIVATE)
public static IRubyObject exec(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
int resultCode;
try {
// TODO: exec should replace the current process.
// This could be possible with JNA.
resultCode = ShellLauncher.execAndWait(runtime, args);
} catch (Exception e) {
throw runtime.newErrnoENOENTError("cannot execute");
}
return exit(recv, new IRubyObject[] {runtime.newFixnum(resultCode)});
}
@JRubyMethod(name = "fork", module = true, visibility = PRIVATE)
public static IRubyObject fork(ThreadContext context, IRubyObject recv, Block block) {
Ruby runtime = context.getRuntime();
if (!RubyInstanceConfig.FORK_ENABLED) {
throw runtime.newNotImplementedError("fork is unsafe and disabled by default on JRuby");
}
if (block.isGiven()) {
int pid = runtime.getPosix().fork();
if (pid == 0) {
try {
block.yield(context, runtime.getNil());
} catch (RaiseException re) {
if (re.getException() instanceof RubySystemExit) {
throw re;
}
return exit_bang(recv, new IRubyObject[] {RubyFixnum.minus_one(runtime)});
} catch (Throwable t) {
return exit_bang(recv, new IRubyObject[] {RubyFixnum.minus_one(runtime)});
}
return exit_bang(recv, new IRubyObject[] {RubyFixnum.zero(runtime)});
} else {
return runtime.newFixnum(pid);
}
} else {
int result = runtime.getPosix().fork();
if (result == -1) {
return runtime.getNil();
}
return runtime.newFixnum(result);
}
}
@JRubyMethod(frame = true, module = true)
public static IRubyObject tap(ThreadContext context, IRubyObject recv, Block block) {
block.yield(context, recv);
return recv;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Charles O Nutter <headius@headius.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyClass(name="LocalJumpError",parent="StandardError")
public class RubyLocalJumpError extends RubyException {
private static ObjectAllocator LOCALJUMPERROR_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyLocalJumpError(runtime, klass);
}
};
public static RubyClass createLocalJumpErrorClass(Ruby runtime, RubyClass standardErrorClass) {
RubyClass nameErrorClass = runtime.defineClass("LocalJumpError", standardErrorClass, LOCALJUMPERROR_ALLOCATOR);
nameErrorClass.defineAnnotatedMethods(RubyLocalJumpError.class);
return nameErrorClass;
}
private RubyLocalJumpError(Ruby runtime, RubyClass exceptionClass) {
super(runtime, exceptionClass);
}
public RubyLocalJumpError(Ruby runtime, RubyClass exceptionClass, String message, String reason, IRubyObject exitValue) {
super(runtime, exceptionClass, message);
fastSetInternalVariable("reason", runtime.newSymbol(reason));
fastSetInternalVariable("exit_value", exitValue);
}
@JRubyMethod(name = "reason")
public IRubyObject reason() {
return fastGetInternalVariable("reason");
}
@JRubyMethod(name = "exit_value")
public IRubyObject exit_value() {
return fastGetInternalVariable("exit_value");
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2007 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2003 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Block;
import org.jruby.runtime.Constants;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.IOInputStream;
import org.jruby.util.IOOutputStream;
/**
* Marshal module
*
* @author Anders
*/
@JRubyModule(name="Marshal")
public class RubyMarshal {
public static RubyModule createMarshalModule(Ruby runtime) {
RubyModule module = runtime.defineModule("Marshal");
runtime.setMarshal(module);
module.defineAnnotatedMethods(RubyMarshal.class);
module.defineConstant("MAJOR_VERSION", runtime.newFixnum(Constants.MARSHAL_MAJOR));
module.defineConstant("MINOR_VERSION", runtime.newFixnum(Constants.MARSHAL_MINOR));
return module;
}
@JRubyMethod(name = "dump", required = 1, optional = 2, frame = true, module = true)
public static IRubyObject dump(IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
if (args.length < 1) {
throw recv.getRuntime().newArgumentError("wrong # of arguments(at least 1)");
}
IRubyObject objectToDump = args[0];
IRubyObject io = null;
int depthLimit = -1;
if (args.length >= 2) {
if (args[1].respondsTo("write")) {
io = args[1];
} else if (args[1] instanceof RubyFixnum) {
depthLimit = (int) ((RubyFixnum) args[1]).getLongValue();
} else {
throw recv.getRuntime().newTypeError("Instance of IO needed");
}
if (args.length == 3) {
depthLimit = (int) ((RubyFixnum) args[2]).getLongValue();
}
}
try {
if (io != null) {
dumpToStream(objectToDump, outputStream(io), depthLimit);
return io;
}
ByteArrayOutputStream stringOutput = new ByteArrayOutputStream();
dumpToStream(objectToDump, stringOutput, depthLimit);
return RubyString.newString(recv.getRuntime(), new ByteList(stringOutput.toByteArray(),false));
} catch (IOException ioe) {
throw recv.getRuntime().newIOErrorFromException(ioe);
}
}
private static OutputStream outputStream(IRubyObject out) {
setBinmodeIfPossible(out);
if (out instanceof RubyIO) {
return ((RubyIO) out).getOutStream();
}
return new IOOutputStream(out);
}
private static void setBinmodeIfPossible(IRubyObject io) {
if (io.respondsTo("binmode")) {
io.callMethod(io.getRuntime().getCurrentContext(), "binmode");
}
}
@JRubyMethod(name = {"load", "restore"}, required = 1, optional = 1, frame = true, module = true)
public static IRubyObject load(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
try {
if (args.length < 1) {
throw recv.getRuntime().newArgumentError("wrong number of arguments (0 for 1)");
}
if (args.length > 2) {
throw recv.getRuntime().newArgumentError("wrong number of arguments (" + args.length + " for 2)");
}
IRubyObject in = null;
IRubyObject proc = null;
switch (args.length) {
case 2:
proc = args[1];
case 1:
in = args[0];
}
InputStream rawInput;
if (in != null && in.respondsTo("read")) {
rawInput = inputStream(in);
} else if (in != null && in.respondsTo("to_str")) {
RubyString inString = (RubyString) RuntimeHelpers.invoke(context, in, "to_str");
ByteList bytes = inString.getByteList();
rawInput = new ByteArrayInputStream(bytes.unsafeBytes(), bytes.begin(), bytes.length());
} else {
throw recv.getRuntime().newTypeError("instance of IO needed");
}
UnmarshalStream input = new UnmarshalStream(recv.getRuntime(), rawInput, proc);
return input.unmarshalObject();
} catch (EOFException ee) {
throw recv.getRuntime().newEOFError();
} catch (IOException ioe) {
throw recv.getRuntime().newIOErrorFromException(ioe);
}
}
private static InputStream inputStream(IRubyObject in) {
setBinmodeIfPossible(in);
if (in instanceof RubyIO) {
return ((RubyIO) in).getInStream();
}
return new IOInputStream(in);
}
private static void dumpToStream(IRubyObject object, OutputStream rawOutput, int depthLimit)
throws IOException
{
MarshalStream output = new MarshalStream(object.getRuntime(), rawOutput, depthLimit);
output.dumpObject(object);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.Iterator;
import org.joni.NameEntry;
import org.joni.Regex;
import org.joni.Region;
import org.joni.exception.JOniException;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
/**
* @author olabini
*/
@JRubyClass(name="MatchData")
public class RubyMatchData extends RubyObject {
Region regs; // captures
int begin; // begin and end are used when not groups defined
int end;
RubyString str;
Regex pattern;
public static RubyClass createMatchDataClass(Ruby runtime) {
// TODO: Is NOT_ALLOCATABLE_ALLOCATOR ok here, since you can't actually instantiate MatchData directly?
RubyClass matchDataClass = runtime.defineClass("MatchData", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setMatchData(matchDataClass);
runtime.defineGlobalConstant("MatchingData", matchDataClass);
matchDataClass.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyMatchData;
}
};
matchDataClass.getMetaClass().undefineMethod("new");
matchDataClass.defineAnnotatedMethods(RubyMatchData.class);
return matchDataClass;
}
public RubyMatchData(Ruby runtime) {
super(runtime, runtime.getMatchData());
}
public final static int MATCH_BUSY = USER2_F;
// rb_match_busy
public final void use() {
flags |= MATCH_BUSY;
}
public final boolean used() {
return (flags & MATCH_BUSY) != 0;
}
private RubyArray match_array(Ruby runtime, int start) {
if (regs == null) {
if (start != 0) return runtime.newEmptyArray();
if (begin == -1) {
return getRuntime().newArray(runtime.getNil());
} else {
RubyString ss = str.makeShared(runtime, begin, end - begin);
if (isTaint()) ss.setTaint(true);
return getRuntime().newArray(ss);
}
} else {
RubyArray arr = getRuntime().newArray(regs.numRegs - start);
for (int i=start; i<regs.numRegs; i++) {
if (regs.beg[i] == -1) {
arr.append(getRuntime().getNil());
} else {
RubyString ss = str.makeShared(runtime, regs.beg[i], regs.end[i] - regs.beg[i]);
if (isTaint()) ss.setTaint(true);
arr.append(ss);
}
}
return arr;
}
}
public IRubyObject group(long n) {
return RubyRegexp.nth_match((int)n, this);
}
public IRubyObject group(int n) {
return RubyRegexp.nth_match(n, this);
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
if (pattern == null) return anyToString();
RubyString result = getRuntime().newString();
result.cat((byte)'#').cat((byte)'<');
result.append(getMetaClass().getRealClass().to_s());
NameEntry[]names = new NameEntry[regs == null ? 1 : regs.numRegs];
if (pattern.numberOfNames() > 0) {
for (Iterator<NameEntry> i = pattern.namedBackrefIterator(); i.hasNext();) {
NameEntry e = i.next();
for (int num : e.getBackRefs()) names[num] = e;
}
}
for (int i=0; i<names.length; i++) {
result.cat((byte)' ');
if (i > 0) {
NameEntry e = names[i];
if (e != null) {
result.cat(e.name, e.nameP, e.nameEnd - e.nameP);
} else {
result.cat((byte)('0' + i));
}
result.cat((byte)':');
}
IRubyObject v = RubyRegexp.nth_match(i, this);
if (v.isNil()) {
result.cat("nil".getBytes());
} else {
result.append(v.inspect());
}
}
return result.cat((byte)'>');
}
/** match_to_a
*
*/
@JRubyMethod(name = "to_a")
@Override
public RubyArray to_a() {
return match_array(getRuntime(), 0);
}
@JRubyMethod(name = "values_at", required = 1, rest = true)
public IRubyObject values_at(IRubyObject[] args) {
return to_a().values_at(args);
}
@JRubyMethod(name = "select", frame = true)
public IRubyObject select(ThreadContext context, Block block) {
return block.yield(context, to_a());
}
/** match_captures
*
*/
@JRubyMethod(name = "captures")
public IRubyObject captures(ThreadContext context) {
return match_array(context.getRuntime(), 1);
}
private int nameToBackrefNumber(RubyString str) {
ByteList value = str.getByteList();
try {
return pattern.nameToBackrefNumber(value.bytes, value.begin, value.begin + value.realSize, regs);
} catch (JOniException je) {
throw getRuntime().newIndexError(je.getMessage());
}
}
final int backrefNumber(IRubyObject obj) {
if (obj instanceof RubySymbol) {
return nameToBackrefNumber((RubyString)((RubySymbol)obj).id2name());
} else if (obj instanceof RubyString) {
return nameToBackrefNumber((RubyString)obj);
} else {
return RubyNumeric.num2int(obj);
}
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public IRubyObject op_aref(IRubyObject[] args) {
switch (args.length) {
case 1:
return op_aref(args[0]);
case 2:
return op_aref(args[0], args[1]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** match_aref
*
*/
@JRubyMethod(name = "[]")
public IRubyObject op_aref(IRubyObject idx) {
IRubyObject result = op_arefCommon(idx);
return result == null ? ((RubyArray)to_a()).aref(idx) : result;
}
/** match_aref
*
*/
@JRubyMethod(name = "[]")
public IRubyObject op_aref(IRubyObject idx, IRubyObject rest) {
IRubyObject result;
return !rest.isNil() || (result = op_arefCommon(idx)) == null ? ((RubyArray)to_a()).aref(idx, rest) : result;
}
private IRubyObject op_arefCommon(IRubyObject idx) {
if (idx instanceof RubyFixnum) {
int num = RubyNumeric.fix2int(idx);
if (num >= 0) return RubyRegexp.nth_match(num, this);
} else {
if (idx instanceof RubySymbol) {
return RubyRegexp.nth_match(nameToBackrefNumber((RubyString)((RubySymbol)idx).id2name()), this);
} else if (idx instanceof RubyString) {
return RubyRegexp.nth_match(nameToBackrefNumber((RubyString)idx), this);
}
}
return null;
}
/** match_size
*
*/
@JRubyMethod(name = {"size", "length"})
public IRubyObject size() {
return regs == null ? RubyFixnum.one(getRuntime()) : RubyFixnum.newFixnum(getRuntime(), regs.numRegs);
}
/** match_begin
*
*/
@JRubyMethod(name = "begin", required = 1)
public IRubyObject begin(IRubyObject index) {
int i = backrefNumber(index);
if (regs == null) {
if (i != 0) throw getRuntime().newIndexError("index " + i + " out of matches");
if (begin < 0) return getRuntime().getNil();
return RubyFixnum.newFixnum(getRuntime(), begin);
} else {
if (i < 0 || regs.numRegs <= i) throw getRuntime().newIndexError("index " + i + " out of matches");
if (regs.beg[i] < 0) return getRuntime().getNil();
return RubyFixnum.newFixnum(getRuntime(), regs.beg[i]);
}
}
/** match_end
*
*/
@JRubyMethod(name = "end", required = 1)
public IRubyObject end(IRubyObject index) {
int i = backrefNumber(index);
if (regs == null) {
if (i != 0) throw getRuntime().newIndexError("index " + i + " out of matches");
if (end < 0) return getRuntime().getNil();
return RubyFixnum.newFixnum(getRuntime(), end);
} else {
if (i < 0 || regs.numRegs <= i) throw getRuntime().newIndexError("index " + i + " out of matches");
if (regs.end[i] < 0) return getRuntime().getNil();
return RubyFixnum.newFixnum(getRuntime(), regs.end[i]);
}
}
/** match_offset
*
*/
@JRubyMethod(name = "offset", required = 1)
public IRubyObject offset(IRubyObject index) {
int i = backrefNumber(index);
Ruby runtime = getRuntime();
if (regs == null) {
if (i != 0) throw getRuntime().newIndexError("index " + i + " out of matches");
if (begin < 0) return runtime.newArray(runtime.getNil(), runtime.getNil());
return runtime.newArray(RubyFixnum.newFixnum(runtime, begin),RubyFixnum.newFixnum(runtime, end));
} else {
if (i < 0 || regs.numRegs <= i) throw runtime.newIndexError("index " + i + " out of matches");
if (regs.beg[i] < 0) return runtime.newArray(runtime.getNil(), runtime.getNil());
return runtime.newArray(RubyFixnum.newFixnum(runtime, regs.beg[i]),RubyFixnum.newFixnum(runtime, regs.end[i]));
}
}
/** match_pre_match
*
*/
@JRubyMethod(name = "pre_match")
public IRubyObject pre_match(ThreadContext context) {
RubyString ss;
if (regs == null) {
if(begin == -1) return context.getRuntime().getNil();
ss = str.makeShared(context.getRuntime(), 0, begin);
} else {
if(regs.beg[0] == -1) return context.getRuntime().getNil();
ss = str.makeShared(context.getRuntime(), 0, regs.beg[0]);
}
if (isTaint()) ss.setTaint(true);
return ss;
}
/** match_post_match
*
*/
@JRubyMethod(name = "post_match")
public IRubyObject post_match(ThreadContext context) {
RubyString ss;
if (regs == null) {
if (begin == -1) return context.getRuntime().getNil();
ss = str.makeShared(context.getRuntime(), end, str.getByteList().length() - end);
} else {
if (regs.beg[0] == -1) return context.getRuntime().getNil();
ss = str.makeShared(context.getRuntime(), regs.end[0], str.getByteList().length() - regs.end[0]);
}
if(isTaint()) ss.setTaint(true);
return ss;
}
/** match_to_s
*
*/
@JRubyMethod(name = "to_s")
public IRubyObject to_s() {
IRubyObject ss = RubyRegexp.last_match(this);
if (ss.isNil()) ss = RubyString.newEmptyString(getRuntime());
if (isTaint()) ss.setTaint(true);
return ss;
}
/** match_string
*
*/
@JRubyMethod(name = "string")
public IRubyObject string() {
return str; //str is frozen
}
@JRubyMethod(name = "initialize_copy", required = 1)
public IRubyObject initialize_copy(IRubyObject original) {
if (this == original) return this;
if (!(getMetaClass() == original.getMetaClass())){ // MRI also does a pointer comparison here
throw getRuntime().newTypeError("wrong argument class");
}
RubyMatchData origMatchData = (RubyMatchData)original;
str = origMatchData.str;
regs = origMatchData.regs;
return this;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001-2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyModule(name="Math")
public class RubyMath {
/** Create the Math module and add it to the Ruby runtime.
*
*/
public static RubyModule createMathModule(Ruby runtime) {
RubyModule result = runtime.defineModule("Math");
runtime.setMath(result);
result.defineConstant("E", RubyFloat.newFloat(runtime, Math.E));
result.defineConstant("PI", RubyFloat.newFloat(runtime, Math.PI));
result.defineAnnotatedMethods(RubyMath.class);
return result;
}
private static void domainCheck(IRubyObject recv, double value, String msg) {
if (Double.isNaN(value)) {
throw recv.getRuntime().newErrnoEDOMError(msg);
}
}
private static double chebylevSerie(double x, double coef[]) {
double b0, b1, b2, twox;
int i;
b1 = 0.0;
b0 = 0.0;
b2 = 0.0;
twox = 2.0 * x;
for (i = coef.length-1; i >= 0; i--) {
b2 = b1;
b1 = b0;
b0 = twox * b1 - b2 + coef[i];
}
return 0.5*(b0 - b2);
}
private static double sign(double x, double y) {
double abs = ((x < 0) ? -x : x);
return (y < 0.0) ? -abs : abs;
}
@JRubyMethod(name = "atan2", required = 2, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat atan2(IRubyObject recv, IRubyObject x, IRubyObject y) {
double valuea = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double valueb = ((RubyFloat)RubyKernel.new_float(recv,y)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(), Math.atan2(valuea, valueb));
}
@JRubyMethod(name = "cos", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat cos(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),Math.cos(value));
}
@JRubyMethod(name = "sin", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat sin(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),Math.sin(value));
}
@JRubyMethod(name = "tan", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat tan(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),Math.tan(value));
}
@JRubyMethod(name = "asin", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat asin(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result = Math.asin(value);
domainCheck(recv, result, "asin");
return RubyFloat.newFloat(recv.getRuntime(),result);
}
@JRubyMethod(name = "acos", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat acos(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result = Math.acos(value);
domainCheck(recv, result, "acos");
return RubyFloat.newFloat(recv.getRuntime(), result);
}
@JRubyMethod(name = "atan", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat atan(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),Math.atan(value));
}
@JRubyMethod(name = "cosh", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat cosh(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),(Math.exp(value) + Math.exp(-value)) / 2.0);
}
@JRubyMethod(name = "sinh", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat sinh(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),(Math.exp(value) - Math.exp(-value)) / 2.0);
}
@JRubyMethod(name = "tanh", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat tanh(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(), Math.tanh(value));
}
@JRubyMethod(name = "acosh", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat acosh(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result;
if (Double.isNaN(value) || value < 1) {
result = Double.NaN;
} else if (value < 94906265.62) {
result = Math.log(value + Math.sqrt(value * value - 1.0));
} else{
result = 0.69314718055994530941723212145818 + Math.log(value);
}
domainCheck(recv, result, "acosh");
return RubyFloat.newFloat(recv.getRuntime(),result);
}
private static final double ASINH_COEF[] = {
-.12820039911738186343372127359268e+0,
-.58811761189951767565211757138362e-1,
.47274654322124815640725249756029e-2,
-.49383631626536172101360174790273e-3,
.58506207058557412287494835259321e-4,
-.74669983289313681354755069217188e-5,
.10011693583558199265966192015812e-5,
-.13903543858708333608616472258886e-6,
.19823169483172793547317360237148e-7,
-.28847468417848843612747272800317e-8,
.42672965467159937953457514995907e-9,
-.63976084654366357868752632309681e-10,
.96991686089064704147878293131179e-11,
-.14844276972043770830246658365696e-11,
.22903737939027447988040184378983e-12,
-.35588395132732645159978942651310e-13,
.55639694080056789953374539088554e-14,
-.87462509599624678045666593520162e-15,
.13815248844526692155868802298129e-15,
-.21916688282900363984955142264149e-16,
.34904658524827565638313923706880e-17
};
@JRubyMethod(name = "asinh", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat asinh(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double y = Math.abs(value);
double result;
if (Double.isNaN(value)) {
result = Double.NaN;
} else if (y <= 1.05367e-08) {
result = value;
} else if (y <= 1.0) {
result = value * (1.0 + chebylevSerie(2.0 * value * value - 1.0, ASINH_COEF));
} else if (y < 94906265.62) {
result = Math.log(value + Math.sqrt(value * value + 1.0));
} else {
result = 0.69314718055994530941723212145818 + Math.log(y);
if (value < 0) result *= -1;
}
return RubyFloat.newFloat(recv.getRuntime(),result);
}
private static final double ATANH_COEF[] = {
.9439510239319549230842892218633e-1,
.4919843705578615947200034576668e-1,
.2102593522455432763479327331752e-2,
.1073554449776116584640731045276e-3,
.5978267249293031478642787517872e-5,
.3505062030889134845966834886200e-6,
.2126374343765340350896219314431e-7,
.1321694535715527192129801723055e-8,
.8365875501178070364623604052959e-10,
.5370503749311002163881434587772e-11,
.3486659470157107922971245784290e-12,
.2284549509603433015524024119722e-13,
.1508407105944793044874229067558e-14,
.1002418816804109126136995722837e-15,
.6698674738165069539715526882986e-17,
.4497954546494931083083327624533e-18
};
@JRubyMethod(name = "atanh", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat atanh(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double y = Math.abs(value);
double result;
if (Double.isNaN(value)) {
result = Double.NaN;
} else if (y < 1.82501e-08) {
result = value;
} else if (y <= 0.5) {
result = value * (1.0 + chebylevSerie(8.0 * value * value - 1.0, ATANH_COEF));
} else if (y < 1.0) {
result = 0.5 * Math.log((1.0 + value) / (1.0 - value));
} else if (y == 1.0) {
result = value * Double.POSITIVE_INFINITY;
} else {
result = Double.NaN;
}
domainCheck(recv, result, "atanh");
return RubyFloat.newFloat(recv.getRuntime(),result);
}
@JRubyMethod(name = "exp", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat exp(IRubyObject recv, IRubyObject exponent) {
double value = ((RubyFloat)RubyKernel.new_float(recv,exponent)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),Math.exp(value));
}
/** Returns the natural logarithm of x.
*
*/
@JRubyMethod(name = "log", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat log(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result = Math.log(value);
domainCheck(recv, result, "log");
return RubyFloat.newFloat(recv.getRuntime(),result);
}
/** Returns the base 10 logarithm of x.
*
*/
@JRubyMethod(name = "log10", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat log10(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result = Math.log(value) / Math.log(10);
domainCheck(recv, result, "log10");
return RubyFloat.newFloat(recv.getRuntime(),result);
}
@JRubyMethod(name = "sqrt", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat sqrt(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result;
if (value < 0) {
result = Double.NaN;
} else{
result = Math.sqrt(value);
}
domainCheck(recv, result, "sqrt");
return RubyFloat.newFloat(recv.getRuntime(), result);
}
@JRubyMethod(name = "hypot", required = 2, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat hypot(IRubyObject recv, IRubyObject x, IRubyObject y) {
double valuea = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double valueb = ((RubyFloat)RubyKernel.new_float(recv,y)).getDoubleValue();
double result;
if (Math.abs(valuea) > Math.abs(valueb)) {
result = valueb / valuea;
result = Math.abs(valuea) * Math.sqrt(1 + result * result);
} else if (valueb != 0) {
result = valuea / valueb;
result = Math.abs(valueb) * Math.sqrt(1 + result * result);
} else {
result = 0;
}
return RubyFloat.newFloat(recv.getRuntime(),result);
}
/*
* x = mantissa * 2 ** exponent
*
* Where mantissa is in the range of [.5, 1)
*
*/
@JRubyMethod(name = "frexp", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyArray frexp(IRubyObject recv, IRubyObject other) {
double mantissa = ((RubyFloat)RubyKernel.new_float(recv,other)).getDoubleValue();
short sign = 1;
long exponent = 0;
if (mantissa != 0.0) {
// Make mantissa same sign so we only have one code path.
if (mantissa < 0) {
mantissa = -mantissa;
sign = -1;
}
// Increase value to hit lower range.
for (; mantissa < 0.5; mantissa *= 2.0, exponent -=1) { }
// Decrease value to hit upper range.
for (; mantissa >= 1.0; mantissa *= 0.5, exponent +=1) { }
}
return RubyArray.newArray(recv.getRuntime(),
RubyFloat.newFloat(recv.getRuntime(), sign * mantissa),
RubyNumeric.int2fix(recv.getRuntime(), exponent));
}
/*
* r = x * 2 ** y
*/
@JRubyMethod(name = "ldexp", required = 2, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat ldexp(IRubyObject recv, IRubyObject mantissa, IRubyObject exponent) {
double mantissaValue = ((RubyFloat)RubyKernel.new_float(recv, mantissa)).getDoubleValue();
return RubyFloat.newFloat(recv.getRuntime(),mantissaValue * Math.pow(2.0, RubyNumeric.num2int(exponent)));
}
private static final double ERFC_COEF[] = {
-.490461212346918080399845440334e-1,
-.142261205103713642378247418996e0,
.100355821875997955757546767129e-1,
-.576876469976748476508270255092e-3,
.274199312521960610344221607915e-4,
-.110431755073445076041353812959e-5,
.384887554203450369499613114982e-7,
-.118085825338754669696317518016e-8,
.323342158260509096464029309534e-10,
-.799101594700454875816073747086e-12,
.179907251139614556119672454866e-13,
-.371863548781869263823168282095e-15,
.710359900371425297116899083947e-17,
-.126124551191552258324954248533e-18
};
@JRubyMethod(name = "erf", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat erf(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result;
double y = Math.abs(value);
if (y <= 1.49012e-08) {
result = 2 * value / 1.77245385090551602729816748334;
} else if (y <= 1) {
result = value * (1 + chebylevSerie(2 * value * value - 1, ERFC_COEF));
} else if (y < 6.013687357) {
result = sign(1 - erfc(recv, RubyFloat.newFloat(recv.getRuntime(),y)).getDoubleValue(), value);
} else {
result = sign(1, value);
}
return RubyFloat.newFloat(recv.getRuntime(),result);
}
private static final double ERFC2_COEF[] = {
-.69601346602309501127391508262e-1,
-.411013393626208934898221208467e-1,
.391449586668962688156114370524e-2,
-.490639565054897916128093545077e-3,
.715747900137703638076089414183e-4,
-.115307163413123283380823284791e-4,
.199467059020199763505231486771e-5,
-.364266647159922287393611843071e-6,
.694437261000501258993127721463e-7,
-.137122090210436601953460514121e-7,
.278838966100713713196386034809e-8,
-.581416472433116155186479105032e-9,
.123892049175275318118016881795e-9,
-.269063914530674343239042493789e-10,
.594261435084791098244470968384e-11,
-.133238673575811957928775442057e-11,
.30280468061771320171736972433e-12,
-.696664881494103258879586758895e-13,
.162085454105392296981289322763e-13,
-.380993446525049199987691305773e-14,
.904048781597883114936897101298e-15,
-.2164006195089607347809812047e-15,
.522210223399585498460798024417e-16,
-.126972960236455533637241552778e-16,
.310914550427619758383622741295e-17,
-.766376292032038552400956671481e-18,
.190081925136274520253692973329e-18
};
private static final double ERFCC_COEF[] = {
.715179310202924774503697709496e-1,
-.265324343376067157558893386681e-1,
.171115397792085588332699194606e-2,
-.163751663458517884163746404749e-3,
.198712935005520364995974806758e-4,
-.284371241276655508750175183152e-5,
.460616130896313036969379968464e-6,
-.822775302587920842057766536366e-7,
.159214187277090112989358340826e-7,
-.329507136225284321486631665072e-8,
.72234397604005554658126115389e-9,
-.166485581339872959344695966886e-9,
.401039258823766482077671768814e-10,
-.100481621442573113272170176283e-10,
.260827591330033380859341009439e-11,
-.699111056040402486557697812476e-12,
.192949233326170708624205749803e-12,
-.547013118875433106490125085271e-13,
.158966330976269744839084032762e-13,
-.47268939801975548392036958429e-14,
.14358733767849847867287399784e-14,
-.444951056181735839417250062829e-15,
.140481088476823343737305537466e-15,
-.451381838776421089625963281623e-16,
.147452154104513307787018713262e-16,
-.489262140694577615436841552532e-17,
.164761214141064673895301522827e-17,
-.562681717632940809299928521323e-18,
.194744338223207851429197867821e-18
};
@JRubyMethod(name = "erfc", required = 1, module = true, visibility = Visibility.PRIVATE)
public static RubyFloat erfc(IRubyObject recv, IRubyObject x) {
double value = ((RubyFloat)RubyKernel.new_float(recv,x)).getDoubleValue();
double result;
double y = Math.abs(value);
if (value <= -6.013687357) {
result = 2;
} else if (y < 1.49012e-08) {
result = 1 - 2 * value / 1.77245385090551602729816748334;
} else {
double ysq = y*y;
if (y < 1) {
result = 1 - value * (1 + chebylevSerie(2 * ysq - 1, ERFC_COEF));
} else if (y <= 4.0) {
result = Math.exp(-ysq)/y*(0.5+chebylevSerie((8.0 / ysq - 5.0) / 3.0, ERFC2_COEF));
if (value < 0) result = 2.0 - result;
if (value < 0) result = 2.0 - result;
if (value < 0) result = 2.0 - result;
} else {
result = Math.exp(-ysq) / y * (0.5 + chebylevSerie(8.0 / ysq - 1, ERFCC_COEF));
if (value < 0) result = 2.0 - result;
}
}
return RubyFloat.newFloat(recv.getRuntime(),result);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.exceptions.JumpException;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.MethodBlock;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
* The RubyMethod class represents a RubyMethod object.
*
* You can get such a method by calling the "method" method of an object.
*
* Note: This was renamed from Method.java
*
* @author jpetersen
* @since 0.2.3
*/
@JRubyClass(name="Method")
public class RubyMethod extends RubyObject {
protected RubyModule implementationModule;
protected String methodName;
protected RubyModule originModule;
protected String originName;
protected DynamicMethod method;
protected IRubyObject receiver;
protected RubyMethod(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass);
}
/** Create the RubyMethod class and add it to the Ruby runtime.
*
*/
public static RubyClass createMethodClass(Ruby runtime) {
// TODO: NOT_ALLOCATABLE_ALLOCATOR is probably ok here. Confirm. JRUBY-415
RubyClass methodClass = runtime.defineClass("Method", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setMethod(methodClass);
methodClass.defineAnnotatedMethods(RubyMethod.class);
return methodClass;
}
public static RubyMethod newMethod(
RubyModule implementationModule,
String methodName,
RubyModule originModule,
String originName,
DynamicMethod method,
IRubyObject receiver) {
Ruby runtime = implementationModule.getRuntime();
RubyMethod newMethod = new RubyMethod(runtime, runtime.getMethod());
newMethod.implementationModule = implementationModule;
newMethod.methodName = methodName;
newMethod.originModule = originModule;
newMethod.originName = originName;
newMethod.method = method.getRealMethod();
newMethod.receiver = receiver;
return newMethod;
}
/** Call the method.
*
*/
@JRubyMethod(name = {"call", "[]"})
public IRubyObject call(ThreadContext context, Block block) {
return method.call(context, receiver, implementationModule, methodName, block);
}
@JRubyMethod(name = {"call", "[]"})
public IRubyObject call(ThreadContext context, IRubyObject arg, Block block) {
return method.call(context, receiver, implementationModule, methodName, arg, block);
}
@JRubyMethod(name = {"call", "[]"})
public IRubyObject call(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
return method.call(context, receiver, implementationModule, methodName, arg0, arg1, block);
}
@JRubyMethod(name = {"call", "[]"})
public IRubyObject call(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
return method.call(context, receiver, implementationModule, methodName, arg0, arg1, arg2, block);
}
@JRubyMethod(name = {"call", "[]"}, rest = true)
public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) {
return method.call(context, receiver, implementationModule, methodName, args, block);
}
/** Returns the number of arguments a method accepted.
*
* @return the number of arguments of a method.
*/
@JRubyMethod(name = "arity")
public RubyFixnum arity() {
return getRuntime().newFixnum(method.getArity().getValue());
}
@JRubyMethod(name = "==", required = 1)
@Override
public RubyBoolean op_equal(ThreadContext context, IRubyObject other) {
if (!(other instanceof RubyMethod)) return context.getRuntime().getFalse();
RubyMethod otherMethod = (RubyMethod)other;
return context.getRuntime().newBoolean(implementationModule == otherMethod.implementationModule &&
originModule == otherMethod.originModule &&
receiver == otherMethod.receiver &&
method.getRealMethod() == otherMethod.method.getRealMethod());
}
@JRubyMethod(name = "clone")
@Override
public RubyMethod rbClone() {
return newMethod(implementationModule, methodName, originModule, originName, method, receiver);
}
/** Create a Proc object.
*
*/
@JRubyMethod(name = "to_proc", frame = true)
public IRubyObject to_proc(ThreadContext context, Block unusedBlock) {
Ruby runtime = context.getRuntime();
CallbackFactory f = runtime.callbackFactory(RubyMethod.class);
Block block = MethodBlock.createMethodBlock(context, context.getCurrentScope(),
f.getBlockMethod("bmcall"), this, runtime.getTopSelf());
while (true) {
try {
// FIXME: We should not be regenerating this over and over
return mproc(context, block);
} catch (JumpException.BreakJump bj) {
return (IRubyObject) bj.getValue();
} catch (JumpException.ReturnJump rj) {
return (IRubyObject) rj.getValue();
} catch (JumpException.RetryJump rj) {
// Execute iterateMethod again.
}
}
}
/** Create a Proc object which is called like a ruby method.
*
* Used by the RubyMethod#to_proc method.
*
*/
private IRubyObject mproc(ThreadContext context, Block block) {
try {
context.preMproc();
return RubyKernel.proc(context, context.getRuntime().getNil(), block);
} finally {
context.postMproc();
}
}
/** Delegate a block call to a bound method call.
*
* Used by the RubyMethod#to_proc method.
*
*/
public static IRubyObject bmcall(IRubyObject blockArg, IRubyObject arg1,
IRubyObject self, Block unusedBlock) {
ThreadContext context = blockArg.getRuntime().getCurrentContext();
if (blockArg instanceof RubyArray) {
// ENEBO: Very wrong
return ((RubyMethod) arg1).call(context, ((RubyArray) blockArg).toJavaArray(), Block.NULL_BLOCK);
}
// ENEBO: Very wrong
return ((RubyMethod) arg1).call(context, new IRubyObject[] { blockArg }, Block.NULL_BLOCK);
}
@JRubyMethod(name = "unbind", frame = true)
public RubyUnboundMethod unbind(Block unusedBlock) {
RubyUnboundMethod unboundMethod =
RubyUnboundMethod.newUnboundMethod(implementationModule, methodName, originModule, originName, method);
unboundMethod.infectBy(this);
return unboundMethod;
}
@JRubyMethod(name = {"inspect", "to_s"})
@Override
public IRubyObject inspect() {
StringBuilder buf = new StringBuilder("#<");
char delimeter = '#';
buf.append(getMetaClass().getRealClass().getName()).append(": ");
if (implementationModule.isSingleton()) {
IRubyObject attached = ((MetaClass) implementationModule).getAttached();
if (receiver == null) {
buf.append(implementationModule.inspect().toString());
} else if (receiver == attached) {
buf.append(attached.inspect().toString());
delimeter = '.';
} else {
buf.append(receiver.inspect().toString());
buf.append('(').append(attached.inspect().toString()).append(')');
delimeter = '.';
}
} else {
buf.append(originModule.getName());
if (implementationModule != originModule) {
buf.append('(').append(implementationModule.getName()).append(')');
}
}
buf.append(delimeter).append(methodName).append('>');
RubyString str = getRuntime().newString(buf.toString());
str.setTaint(isTaint());
return str;
}
}
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006-2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 William N Dortch <bill.dortch@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyConstant;
import org.jruby.anno.JavaMethodDescriptor;
import org.jruby.anno.TypePopulator;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.compiler.ASTInspector;
import org.jruby.internal.runtime.methods.AliasMethod;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.internal.runtime.methods.FullFunctionCallbackMethod;
import org.jruby.internal.runtime.methods.SimpleCallbackMethod;
import org.jruby.internal.runtime.methods.MethodMethod;
import org.jruby.internal.runtime.methods.ProcMethod;
import org.jruby.internal.runtime.methods.UndefinedMethod;
import org.jruby.internal.runtime.methods.WrapperMethod;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CacheMap;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import static org.jruby.runtime.Visibility.*;
import static org.jruby.anno.FrameField.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.callback.Callback;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ClassProvider;
import org.jruby.util.IdUtil;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.methods.JavaMethod;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodFactory;
import org.jruby.runtime.MethodIndex;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Module")
public class RubyModule extends RubyObject {
private static final boolean DEBUG = false;
public static RubyClass createModuleClass(Ruby runtime, RubyClass moduleClass) {
moduleClass.index = ClassIndex.MODULE;
moduleClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyModule;
}
};
moduleClass.defineAnnotatedMethods(RubyModule.class);
moduleClass.defineAnnotatedMethods(ModuleKernelMethods.class);
return moduleClass;
}
public static class ModuleKernelMethods {
@JRubyMethod
public static IRubyObject autoload(IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return RubyKernel.autoload(recv, arg0, arg1);
}
@JRubyMethod(name = "autoload?")
public static IRubyObject autoload_p(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
return RubyKernel.autoload_p(context, recv, arg0);
}
}
static ObjectAllocator MODULE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyModule(runtime, klass);
}
};
@Override
public int getNativeTypeIndex() {
return ClassIndex.MODULE;
}
@Override
public boolean isModule() {
return true;
}
@Override
public boolean isClass() {
return false;
}
public boolean isSingleton() {
return false;
}
// superClass may be null.
protected RubyClass superClass;
public int index;
public static class KindOf {
public static final KindOf DEFAULT_KIND_OF = new KindOf();
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj.getMetaClass().hasModuleInHierarchy(type);
}
}
public boolean isInstance(IRubyObject object) {
return kindOf.isKindOf(object, this);
}
public KindOf kindOf = KindOf.DEFAULT_KIND_OF;
public final int id;
// Containing class...The parent of Object is null. Object should always be last in chain.
public RubyModule parent;
// ClassId is the name of the class/module sans where it is located.
// If it is null, then it an anonymous class.
protected String classId;
// CONSTANT TABLE
// Lock used for variableTable/constantTable writes. The RubyObject variableTable
// write methods are overridden here to use this lock rather than Java
// synchronization for faster concurrent writes for modules/classes.
protected final ReentrantLock variableWriteLock = new ReentrantLock();
protected transient volatile ConstantTableEntry[] constantTable =
new ConstantTableEntry[CONSTANT_TABLE_DEFAULT_CAPACITY];
protected transient int constantTableSize;
protected transient int constantTableThreshold =
(int)(CONSTANT_TABLE_DEFAULT_CAPACITY * CONSTANT_TABLE_LOAD_FACTOR);
private final Map<String, DynamicMethod> methods = new ConcurrentHashMap<String, DynamicMethod>(12, 0.75f, 1);
// ClassProviders return Java class/module (in #defineOrGetClassUnder and
// #defineOrGetModuleUnder) when class/module is opened using colon syntax.
private transient List<ClassProvider> classProviders;
/** separate path for MetaClass construction
*
*/
protected RubyModule(Ruby runtime, RubyClass metaClass, boolean objectSpace) {
super(runtime, metaClass, objectSpace);
id = runtime.allocModuleId();
// if (parent == null) parent = runtime.getObject();
setFlag(USER7_F, !isClass());
}
/** used by MODULE_ALLOCATOR and RubyClass constructors
*
*/
protected RubyModule(Ruby runtime, RubyClass metaClass) {
this(runtime, metaClass, runtime.isObjectSpaceEnabled());
}
/** standard path for Module construction
*
*/
protected RubyModule(Ruby runtime) {
this(runtime, runtime.getModule());
}
public boolean needsImplementer() {
return getFlag(USER7_F);
}
/** rb_module_new
*
*/
public static RubyModule newModule(Ruby runtime) {
return new RubyModule(runtime);
}
/** rb_module_new/rb_define_module_id/rb_name_class/rb_set_class_path
*
*/
public static RubyModule newModule(Ruby runtime, String name, RubyModule parent, boolean setParent) {
RubyModule module = newModule(runtime);
module.setBaseName(name);
if (setParent) module.setParent(parent);
parent.setConstant(name, module);
return module;
}
// synchronized method per JRUBY-1173 (unsafe Double-Checked Locking)
// FIXME: synchronization is still wrong in CP code
public synchronized void addClassProvider(ClassProvider provider) {
if (classProviders == null) {
List<ClassProvider> cp = Collections.synchronizedList(new ArrayList<ClassProvider>());
cp.add(provider);
classProviders = cp;
} else {
synchronized(classProviders) {
if (!classProviders.contains(provider)) {
classProviders.add(provider);
}
}
}
}
public void removeClassProvider(ClassProvider provider) {
if (classProviders != null) {
classProviders.remove(provider);
}
}
private RubyClass searchProvidersForClass(String name, RubyClass superClazz) {
if (classProviders != null) {
synchronized(classProviders) {
RubyClass clazz;
for (ClassProvider classProvider: classProviders) {
if ((clazz = classProvider.defineClassUnder(this, name, superClazz)) != null) {
return clazz;
}
}
}
}
return null;
}
private RubyModule searchProvidersForModule(String name) {
if (classProviders != null) {
synchronized(classProviders) {
RubyModule module;
for (ClassProvider classProvider: classProviders) {
if ((module = classProvider.defineModuleUnder(this, name)) != null) {
return module;
}
}
}
}
return null;
}
/** Getter for property superClass.
* @return Value of property superClass.
*/
public RubyClass getSuperClass() {
return superClass;
}
protected void setSuperClass(RubyClass superClass) {
this.superClass = superClass;
}
public RubyModule getParent() {
return parent;
}
public void setParent(RubyModule parent) {
this.parent = parent;
}
public Map<String, DynamicMethod> getMethods() {
return methods;
}
// note that addMethod now does its own put, so any change made to
// functionality here should be made there as well
private void putMethod(String name, DynamicMethod method) {
getMethods().put(name, method);
}
/**
* Is this module one that in an included one (e.g. an IncludedModuleWrapper).
*/
public boolean isIncluded() {
return false;
}
public RubyModule getNonIncludedClass() {
return this;
}
public String getBaseName() {
return classId;
}
public void setBaseName(String name) {
classId = name;
}
private volatile String bareName;
private volatile String fullName;
/**
* Generate a fully-qualified class name or a #-style name for anonymous and singleton classes.
*
* Ruby C equivalent = "classname"
*
* @return The generated class name
*/
public String getName() {
if (fullName == null) {
fullName = calculateFullName();
}
return fullName;
}
private String calculateFullName() {
if (getBaseName() == null) {
if (bareName == null) {
if (isClass()) {
bareName = "#<" + "Class" + ":01x" + Integer.toHexString(System.identityHashCode(this)) + ">";
} else {
bareName = "#<" + "Module" + ":01x" + Integer.toHexString(System.identityHashCode(this)) + ">";
}
}
return bareName;
}
String result = getBaseName();
RubyClass objectClass = getRuntime().getObject();
for (RubyModule p = this.getParent(); p != null && p != objectClass; p = p.getParent()) {
String pName = p.getBaseName();
// This is needed when the enclosing class or module is a singleton.
// In that case, we generated a name such as null::Foo, which broke
// Marshalling, among others. The correct thing to do in this situation
// is to insert the generate the name of form #<Class:01xasdfasd> if
// it's a singleton module/class, which this code accomplishes.
if(pName == null) {
pName = p.getName();
}
result = pName + "::" + result;
}
return result;
}
/**
* Create a wrapper to use for including the specified module into this one.
*
* Ruby C equivalent = "include_class_new"
*
* @return The module wrapper
*/
public IncludedModuleWrapper newIncludeClass(RubyClass superClazz) {
IncludedModuleWrapper includedModule = new IncludedModuleWrapper(getRuntime(), superClazz, this);
// include its parent (and in turn that module's parents)
if (getSuperClass() != null) {
includedModule.includeModule(getSuperClass());
}
return includedModule;
}
/**
* Finds a class that is within the current module (or class).
*
* @param name to be found in this module (or class)
* @return the class or null if no such class
*/
public RubyClass getClass(String name) {
IRubyObject module;
if ((module = getConstantAt(name)) instanceof RubyClass) {
return (RubyClass)module;
}
return null;
}
public RubyClass fastGetClass(String internedName) {
IRubyObject module;
if ((module = fastGetConstantAt(internedName)) instanceof RubyClass) {
return (RubyClass)module;
}
return null;
}
/**
* Include a new module in this module or class.
*
* @param arg The module to include
*/
public synchronized void includeModule(IRubyObject arg) {
assert arg != null;
testFrozen("module");
if (!isTaint()) {
getRuntime().secure(4);
}
if (!(arg instanceof RubyModule)) {
throw getRuntime().newTypeError("Wrong argument type " + arg.getMetaClass().getName() +
" (expected Module).");
}
RubyModule module = (RubyModule) arg;
// Make sure the module we include does not already exist
if (isSame(module)) {
return;
}
infectBy(module);
doIncludeModule(module);
}
public void defineMethod(String name, Callback method) {
Visibility visibility = name.equals("initialize") ?
PRIVATE : PUBLIC;
addMethod(name, new FullFunctionCallbackMethod(this, method, visibility));
}
public void defineAnnotatedMethod(Class clazz, String name) {
// FIXME: This is probably not very efficient, since it loads all methods for each call
boolean foundMethod = false;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals(name) && defineAnnotatedMethod(method, MethodFactory.createFactory(getRuntime().getJRubyClassLoader()))) {
foundMethod = true;
}
}
if (!foundMethod) {
throw new RuntimeException("No JRubyMethod present for method " + name + "on class " + clazz.getName());
}
}
public void defineAnnotatedConstants(Class clazz) {
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if(Modifier.isStatic(field.getModifiers())) {
defineAnnotatedConstant(field);
}
}
}
public boolean defineAnnotatedConstant(Field field) {
JRubyConstant jrubyConstant = field.getAnnotation(JRubyConstant.class);
if (jrubyConstant == null) return false;
String[] names = jrubyConstant.value();
if(names.length == 0) {
names = new String[]{field.getName()};
}
Class tp = field.getType();
IRubyObject realVal;
try {
if(tp == Integer.class || tp == Integer.TYPE || tp == Short.class || tp == Short.TYPE || tp == Byte.class || tp == Byte.TYPE) {
realVal = RubyNumeric.int2fix(getRuntime(), field.getInt(null));
} else if(tp == Boolean.class || tp == Boolean.TYPE) {
realVal = field.getBoolean(null) ? getRuntime().getTrue() : getRuntime().getFalse();
} else {
realVal = getRuntime().getNil();
}
} catch(Exception e) {
realVal = getRuntime().getNil();
}
for(String name : names) {
this.fastSetConstant(name, realVal);
}
return true;
}
public void defineAnnotatedMethods(Class clazz) {
defineAnnotatedMethodsIndividually(clazz);
}
public static class MethodClumper {
Map<String, List<JavaMethodDescriptor>> annotatedMethods = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> staticAnnotatedMethods = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> annotatedMethods1_8 = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> staticAnnotatedMethods1_8 = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> annotatedMethods1_9 = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> staticAnnotatedMethods1_9 = new HashMap<String, List<JavaMethodDescriptor>>();
public void clump(Class cls) {
Method[] declaredMethods = cls.getDeclaredMethods();
for (Method method: declaredMethods) {
JRubyMethod anno = method.getAnnotation(JRubyMethod.class);
if (anno == null) continue;
JavaMethodDescriptor desc = new JavaMethodDescriptor(method);
String name = anno.name().length == 0 ? method.getName() : anno.name()[0];
List<JavaMethodDescriptor> methodDescs;
Map<String, List<JavaMethodDescriptor>> methodsHash = null;
if (desc.isStatic) {
if (anno.compat() == CompatVersion.RUBY1_8) {
methodsHash = staticAnnotatedMethods1_8;
} else if (anno.compat() == CompatVersion.RUBY1_9) {
methodsHash = staticAnnotatedMethods1_9;
} else {
methodsHash = staticAnnotatedMethods;
}
} else {
if (anno.compat() == CompatVersion.RUBY1_8) {
methodsHash = annotatedMethods1_8;
} else if (anno.compat() == CompatVersion.RUBY1_9) {
methodsHash = annotatedMethods1_9;
} else {
methodsHash = annotatedMethods;
}
}
methodDescs = methodsHash.get(name);
if (methodDescs == null) {
methodDescs = new ArrayList<JavaMethodDescriptor>();
methodsHash.put(name, methodDescs);
}
methodDescs.add(desc);
}
}
public Map<String, List<JavaMethodDescriptor>> getAnnotatedMethods() {
return annotatedMethods;
}
public Map<String, List<JavaMethodDescriptor>> getAnnotatedMethods1_8() {
return annotatedMethods1_8;
}
public Map<String, List<JavaMethodDescriptor>> getAnnotatedMethods1_9() {
return annotatedMethods1_9;
}
public Map<String, List<JavaMethodDescriptor>> getStaticAnnotatedMethods() {
return staticAnnotatedMethods;
}
public Map<String, List<JavaMethodDescriptor>> getStaticAnnotatedMethods1_8() {
return staticAnnotatedMethods1_8;
}
public Map<String, List<JavaMethodDescriptor>> getStaticAnnotatedMethods1_9() {
return staticAnnotatedMethods1_9;
}
}
public void defineAnnotatedMethodsIndividually(Class clazz) {
String x = clazz.getSimpleName();
TypePopulator populator = null;
if (RubyInstanceConfig.FULL_TRACE_ENABLED) {
// we need full traces, use default (slow) populator
if (DEBUG) System.out.println("trace mode, using default populator");
populator = TypePopulator.DEFAULT;
} else {
try {
String qualifiedName = "org.jruby.gen." + clazz.getCanonicalName().replace('.', '$');
if (DEBUG) System.out.println("looking for " + qualifiedName + "$Populator");
Class populatorClass = Class.forName(qualifiedName + "$Populator");
populator = (TypePopulator)populatorClass.newInstance();
} catch (Throwable t) {
if (DEBUG) System.out.println("Could not find it, using default populator");
populator = TypePopulator.DEFAULT;
}
}
populator.populate(this, clazz);
}
@Deprecated
private void defineAnnotatedMethodsIndexed(Class clazz) {
MethodFactory methodFactory = MethodFactory.createFactory(getRuntime().getJRubyClassLoader());
methodFactory.defineIndexedAnnotatedMethods(this, clazz, methodDefiningCallback);
}
private static MethodFactory.MethodDefiningCallback methodDefiningCallback = new MethodFactory.MethodDefiningCallback() {
public void define(RubyModule module, JavaMethodDescriptor desc, DynamicMethod dynamicMethod) {
JRubyMethod jrubyMethod = desc.anno;
if (jrubyMethod.frame()) {
for (String name : jrubyMethod.name()) {
ASTInspector.FRAME_AWARE_METHODS.add(name);
}
}
if(jrubyMethod.compat() == CompatVersion.BOTH ||
module.getRuntime().getInstanceConfig().getCompatVersion() == jrubyMethod.compat()) {
RubyModule singletonClass;
if (jrubyMethod.meta()) {
singletonClass = module.getSingletonClass();
dynamicMethod.setImplementationClass(singletonClass);
String baseName;
if (jrubyMethod.name().length == 0) {
baseName = desc.name;
singletonClass.addMethod(baseName, dynamicMethod);
} else {
baseName = jrubyMethod.name()[0];
for (String name : jrubyMethod.name()) {
singletonClass.addMethod(name, dynamicMethod);
}
}
if (jrubyMethod.alias().length > 0) {
for (String alias : jrubyMethod.alias()) {
singletonClass.defineAlias(alias, baseName);
}
}
} else {
String baseName;
if (jrubyMethod.name().length == 0) {
baseName = desc.name;
module.addMethod(baseName, dynamicMethod);
} else {
baseName = jrubyMethod.name()[0];
for (String name : jrubyMethod.name()) {
module.addMethod(name, dynamicMethod);
}
}
if (jrubyMethod.alias().length > 0) {
for (String alias : jrubyMethod.alias()) {
module.defineAlias(alias, baseName);
}
}
if (jrubyMethod.module()) {
singletonClass = module.getSingletonClass();
// module/singleton methods are all defined public
DynamicMethod moduleMethod = dynamicMethod.dup();
moduleMethod.setVisibility(PUBLIC);
if (jrubyMethod.name().length == 0) {
baseName = desc.name;
singletonClass.addMethod(desc.name, moduleMethod);
} else {
baseName = jrubyMethod.name()[0];
for (String name : jrubyMethod.name()) {
singletonClass.addMethod(name, moduleMethod);
}
}
if (jrubyMethod.alias().length > 0) {
for (String alias : jrubyMethod.alias()) {
singletonClass.defineAlias(alias, baseName);
}
}
}
}
}
}
};
public boolean defineAnnotatedMethod(String name, List<JavaMethodDescriptor> methods, MethodFactory methodFactory) {
JavaMethodDescriptor desc = methods.get(0);
if (methods.size() == 1) {
return defineAnnotatedMethod(desc, methodFactory);
} else {
DynamicMethod dynamicMethod = methodFactory.getAnnotatedMethod(this, methods);
methodDefiningCallback.define(this, desc, dynamicMethod);
return true;
}
}
public boolean defineAnnotatedMethod(Method method, MethodFactory methodFactory) {
JRubyMethod jrubyMethod = method.getAnnotation(JRubyMethod.class);
if (jrubyMethod == null) return false;
if(jrubyMethod.compat() == CompatVersion.BOTH ||
getRuntime().getInstanceConfig().getCompatVersion() == jrubyMethod.compat()) {
JavaMethodDescriptor desc = new JavaMethodDescriptor(method);
DynamicMethod dynamicMethod = methodFactory.getAnnotatedMethod(this, desc);
methodDefiningCallback.define(this, desc, dynamicMethod);
return true;
}
return false;
}
public boolean defineAnnotatedMethod(JavaMethodDescriptor desc, MethodFactory methodFactory) {
JRubyMethod jrubyMethod = desc.anno;
if (jrubyMethod == null) return false;
if(jrubyMethod.compat() == CompatVersion.BOTH ||
getRuntime().getInstanceConfig().getCompatVersion() == jrubyMethod.compat()) {
DynamicMethod dynamicMethod = methodFactory.getAnnotatedMethod(this, desc);
methodDefiningCallback.define(this, desc, dynamicMethod);
return true;
}
return false;
}
public void defineFastMethod(String name, Callback method) {
Visibility visibility = name.equals("initialize") ?
PRIVATE : PUBLIC;
addMethod(name, new SimpleCallbackMethod(this, method, visibility));
}
public void defineFastMethod(String name, Callback method, Visibility visibility) {
addMethod(name, new SimpleCallbackMethod(this, method, visibility));
}
public void definePrivateMethod(String name, Callback method) {
addMethod(name, new FullFunctionCallbackMethod(this, method, PRIVATE));
}
public void defineFastPrivateMethod(String name, Callback method) {
addMethod(name, new SimpleCallbackMethod(this, method, PRIVATE));
}
public void defineFastProtectedMethod(String name, Callback method) {
addMethod(name, new SimpleCallbackMethod(this, method, PROTECTED));
}
public void undefineMethod(String name) {
addMethod(name, UndefinedMethod.getInstance());
}
/** rb_undef
*
*/
public void undef(ThreadContext context, String name) {
Ruby runtime = context.getRuntime();
if (this == runtime.getObject()) runtime.secure(4);
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw new SecurityException("Insecure: can't undef");
}
testFrozen("module");
if (name.equals("__id__") || name.equals("__send__")) {
runtime.getWarnings().warn(ID.UNDEFINING_BAD, "undefining `"+ name +"' may cause serious problem");
}
DynamicMethod method = searchMethod(name);
if (method.isUndefined()) {
String s0 = " class";
RubyModule c = this;
if (c.isSingleton()) {
IRubyObject obj = ((MetaClass)c).getAttached();
if (obj != null && obj instanceof RubyModule) {
c = (RubyModule) obj;
s0 = "";
}
} else if (c.isModule()) {
s0 = " module";
}
throw runtime.newNameError("Undefined method " + name + " for" + s0 + " '" + c.getName() + "'", name);
}
addMethod(name, UndefinedMethod.getInstance());
if (isSingleton()) {
IRubyObject singleton = ((MetaClass)this).getAttached();
singleton.callMethod(context, "singleton_method_undefined", runtime.newSymbol(name));
} else {
callMethod(context, "method_undefined", runtime.newSymbol(name));
}
}
@JRubyMethod(name = "include?", required = 1)
public IRubyObject include_p(ThreadContext context, IRubyObject arg) {
if (!arg.isModule()) {
throw context.getRuntime().newTypeError(arg, context.getRuntime().getModule());
}
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if ((p instanceof IncludedModuleWrapper) && ((IncludedModuleWrapper) p).getNonIncludedClass() == arg) {
return context.getRuntime().getTrue();
}
}
return context.getRuntime().getFalse();
}
// TODO: Consider a better way of synchronizing
public void addMethod(String name, DynamicMethod method) {
Ruby runtime = getRuntime();
if (this == runtime.getObject()) runtime.secure(4);
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw runtime.newSecurityError("Insecure: can't define method");
}
testFrozen("class/module");
// We can safely reference methods here instead of doing getMethods() since if we
// are adding we are not using a IncludedModuleWrapper.
synchronized(getMethods()) {
// If we add a method which already is cached in this class, then we should update the
// cachemap so it stays up to date.
DynamicMethod existingMethod = getMethods().put(name, method);
if (existingMethod != null) {
runtime.getCacheMap().remove(existingMethod);
}
}
}
public void removeMethod(ThreadContext context, String name) {
Ruby runtime = context.getRuntime();
if (this == runtime.getObject()) runtime.secure(4);
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw runtime.newSecurityError("Insecure: can't remove method");
}
testFrozen("class/module");
// We can safely reference methods here instead of doing getMethods() since if we
// are adding we are not using a IncludedModuleWrapper.
synchronized(getMethods()) {
DynamicMethod method = (DynamicMethod) getMethods().remove(name);
if (method == null) {
throw runtime.newNameError("method '" + name + "' not defined in " + getName(), name);
}
runtime.getCacheMap().remove(method);
}
if (isSingleton()) {
IRubyObject singleton = ((MetaClass)this).getAttached();
singleton.callMethod(context, "singleton_method_removed", runtime.newSymbol(name));
} else {
callMethod(context, "method_removed", runtime.newSymbol(name));
}
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public DynamicMethod searchMethod(String name) {
DynamicMethod method = getMethods().get(name);
if (method != null) return method;
return superClass == null ? UndefinedMethod.getInstance() : superClass.searchMethod(name);
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public DynamicMethod retrieveMethod(String name) {
return getMethods().get(name);
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public RubyModule findImplementer(RubyModule clazz) {
for (RubyModule searchModule = this; searchModule != null; searchModule = searchModule.getSuperClass()) {
if (searchModule.isSame(clazz)) {
return searchModule;
}
}
return null;
}
public void addModuleFunction(String name, DynamicMethod method) {
addMethod(name, method);
getSingletonClass().addMethod(name, method);
}
/** rb_define_module_function
*
*/
public void defineModuleFunction(String name, Callback method) {
definePrivateMethod(name, method);
getSingletonClass().defineMethod(name, method);
}
/** rb_define_module_function
*
*/
public void definePublicModuleFunction(String name, Callback method) {
defineMethod(name, method);
getSingletonClass().defineMethod(name, method);
}
/** rb_define_module_function
*
*/
public void defineFastModuleFunction(String name, Callback method) {
defineFastPrivateMethod(name, method);
getSingletonClass().defineFastMethod(name, method);
}
/** rb_define_module_function
*
*/
public void defineFastPublicModuleFunction(String name, Callback method) {
defineFastMethod(name, method);
getSingletonClass().defineFastMethod(name, method);
}
/** rb_alias
*
*/
public synchronized void defineAlias(String name, String oldName) {
testFrozen("module");
if (oldName.equals(name)) {
return;
}
Ruby runtime = getRuntime();
if (this == runtime.getObject()) {
runtime.secure(4);
}
DynamicMethod method = searchMethod(oldName);
DynamicMethod oldMethod = searchMethod(name);
if (method.isUndefined()) {
if (isModule()) {
method = runtime.getObject().searchMethod(oldName);
}
if (method.isUndefined()) {
throw runtime.newNameError("undefined method `" + oldName + "' for " +
(isModule() ? "module" : "class") + " `" + getName() + "'", oldName);
}
}
CacheMap cacheMap = runtime.getCacheMap();
cacheMap.remove(method);
cacheMap.remove(oldMethod);
if (oldMethod != oldMethod.getRealMethod()) {
cacheMap.remove(oldMethod.getRealMethod());
}
putMethod(name, new AliasMethod(this, method, oldName));
}
public synchronized void defineAliases(List<String> aliases, String oldName) {
testFrozen("module");
Ruby runtime = getRuntime();
if (this == runtime.getObject()) {
runtime.secure(4);
}
DynamicMethod method = searchMethod(oldName);
if (method.isUndefined()) {
if (isModule()) {
method = runtime.getObject().searchMethod(oldName);
}
if (method.isUndefined()) {
throw runtime.newNameError("undefined method `" + oldName + "' for " +
(isModule() ? "module" : "class") + " `" + getName() + "'", oldName);
}
}
CacheMap cacheMap = runtime.getCacheMap();
cacheMap.remove(method);
for (String name: aliases) {
if (oldName.equals(name)) continue;
DynamicMethod oldMethod = searchMethod(name);
cacheMap.remove(oldMethod);
if (oldMethod != oldMethod.getRealMethod()) {
cacheMap.remove(oldMethod.getRealMethod());
}
putMethod(name, new AliasMethod(this, method, oldName));
}
}
/** this method should be used only by interpreter or compiler
*
*/
public RubyClass defineOrGetClassUnder(String name, RubyClass superClazz) {
// This method is intended only for defining new classes in Ruby code,
// so it uses the allocator of the specified superclass or default to
// the Object allocator. It should NOT be used to define classes that require a native allocator.
Ruby runtime = getRuntime();
IRubyObject classObj = getConstantAt(name);
RubyClass clazz;
if (classObj != null) {
if (!(classObj instanceof RubyClass)) throw runtime.newTypeError(name + " is not a class");
clazz = (RubyClass)classObj;
if (superClazz != null) {
RubyClass tmp = clazz.getSuperClass();
while (tmp != null && tmp.isIncluded()) tmp = tmp.getSuperClass(); // need to skip IncludedModuleWrappers
if (tmp != null) tmp = tmp.getRealClass();
if (tmp != superClazz) throw runtime.newTypeError("superclass mismatch for class " + name);
// superClazz = null;
}
if (runtime.getSafeLevel() >= 4) throw runtime.newTypeError("extending class prohibited");
} else if (classProviders != null && (clazz = searchProvidersForClass(name, superClazz)) != null) {
// reopen a java class
} else {
if (superClazz == null) superClazz = runtime.getObject();
clazz = RubyClass.newClass(runtime, superClazz, name, superClazz.getAllocator(), this, true);
}
return clazz;
}
/** this method should be used only by interpreter or compiler
*
*/
public RubyModule defineOrGetModuleUnder(String name) {
// This method is intended only for defining new modules in Ruby code
Ruby runtime = getRuntime();
IRubyObject moduleObj = getConstantAt(name);
RubyModule module;
if (moduleObj != null) {
if (!moduleObj.isModule()) throw runtime.newTypeError(name + " is not a module");
if (runtime.getSafeLevel() >= 4) throw runtime.newSecurityError("extending module prohibited");
module = (RubyModule)moduleObj;
} else if (classProviders != null && (module = searchProvidersForModule(name)) != null) {
// reopen a java module
} else {
module = RubyModule.newModule(runtime, name, this, true);
}
return module;
}
/** rb_define_class_under
* this method should be used only as an API to define/open nested classes
*/
public RubyClass defineClassUnder(String name, RubyClass superClass, ObjectAllocator allocator) {
return getRuntime().defineClassUnder(name, superClass, allocator, this);
}
/** rb_define_module_under
* this method should be used only as an API to define/open nested module
*/
public RubyModule defineModuleUnder(String name) {
return getRuntime().defineModuleUnder(name, this);
}
// FIXME: create AttrReaderMethod, AttrWriterMethod, for faster attr access
private void addAccessor(ThreadContext context, String internedName, boolean readable, boolean writeable) {
assert internedName == internedName.intern() : internedName + " is not interned";
final Ruby runtime = context.getRuntime();
// Check the visibility of the previous frame, which will be the frame in which the class is being eval'ed
Visibility attributeScope = context.getCurrentVisibility();
if (attributeScope == PRIVATE) {
//FIXME warning
} else if (attributeScope == MODULE_FUNCTION) {
attributeScope = PRIVATE;
// FIXME warning
}
final String variableName = ("@" + internedName).intern();
if (readable) {
// FIXME: should visibility be set to current visibility?
addMethod(internedName, new JavaMethod(this, PUBLIC) {
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
if (args.length != 0) Arity.raiseArgumentError(runtime, args.length, 0, 0);
IRubyObject variable = self.getInstanceVariables().fastGetInstanceVariable(variableName);
return variable == null ? runtime.getNil() : variable;
}
@Override
public Arity getArity() {
return Arity.noArguments();
}
});
callMethod(context, "method_added", runtime.fastNewSymbol(internedName));
}
if (writeable) {
internedName = (internedName + "=").intern();
// FIXME: should visibility be set to current visibility?
addMethod(internedName, new JavaMethod(this, PUBLIC) {
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
// ENEBO: Can anyone get args to be anything but length 1?
if (args.length != 1) Arity.raiseArgumentError(runtime, args.length, 1, 1);
return self.getInstanceVariables().fastSetInstanceVariable(variableName, args[0]);
}
@Override
public Arity getArity() {
return Arity.singleArgument();
}
});
callMethod(context, "method_added", runtime.fastNewSymbol(internedName));
}
}
/** set_method_visibility
*
*/
public void setMethodVisibility(IRubyObject[] methods, Visibility visibility) {
if (getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw getRuntime().newSecurityError("Insecure: can't change method visibility");
}
for (int i = 0; i < methods.length; i++) {
exportMethod(methods[i].asJavaString(), visibility);
}
}
/** rb_export_method
*
*/
public void exportMethod(String name, Visibility visibility) {
if (this == getRuntime().getObject()) {
getRuntime().secure(4);
}
DynamicMethod method = searchMethod(name);
if (method.isUndefined()) {
throw getRuntime().newNameError("undefined method '" + name + "' for " +
(isModule() ? "module" : "class") + " '" + getName() + "'", name);
}
if (method.getVisibility() != visibility) {
if (this == method.getImplementationClass()) {
method.setVisibility(visibility);
} else {
// FIXME: Why was this using a FullFunctionCallbackMethod before that did callSuper?
addMethod(name, new WrapperMethod(this, method, visibility));
}
}
}
/**
* MRI: rb_method_boundp
*
*/
public boolean isMethodBound(String name, boolean checkVisibility) {
DynamicMethod method = searchMethod(name);
if (!method.isUndefined()) {
return !(checkVisibility && method.getVisibility() == PRIVATE);
}
return false;
}
public IRubyObject newMethod(IRubyObject receiver, String name, boolean bound) {
DynamicMethod method = searchMethod(name);
if (method.isUndefined()) {
throw getRuntime().newNameError("undefined method `" + name +
"' for class `" + this.getName() + "'", name);
}
RubyModule implementationModule = method.getImplementationClass();
RubyModule originModule = this;
while (originModule != implementationModule && originModule.isSingleton()) {
originModule = ((MetaClass)originModule).getRealClass();
}
RubyMethod newMethod = null;
if (bound) {
newMethod = RubyMethod.newMethod(implementationModule, name, originModule, name, method, receiver);
} else {
newMethod = RubyUnboundMethod.newUnboundMethod(implementationModule, name, originModule, name, method);
}
newMethod.infectBy(this);
return newMethod;
}
@JRubyMethod(name = "define_method", frame = true, visibility = PRIVATE, reads = VISIBILITY)
public IRubyObject define_method(ThreadContext context, IRubyObject arg0, Block block) {
Ruby runtime = context.getRuntime();
String name = arg0.asJavaString().intern();
DynamicMethod newMethod = null;
Visibility visibility = context.getCurrentVisibility();
if (visibility == MODULE_FUNCTION) visibility = PRIVATE;
RubyProc proc = runtime.newProc(Block.Type.LAMBDA, block);
// a normal block passed to define_method changes to do arity checking; make it a lambda
proc.getBlock().type = Block.Type.LAMBDA;
newMethod = createProcMethod(name, visibility, proc);
RuntimeHelpers.addInstanceMethod(this, name, newMethod, context.getPreviousVisibility(), context, runtime);
return proc;
}
@JRubyMethod(name = "define_method", frame = true, visibility = PRIVATE, reads = VISIBILITY)
public IRubyObject define_method(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
Ruby runtime = context.getRuntime();
IRubyObject body;
String name = arg0.asJavaString().intern();
DynamicMethod newMethod = null;
Visibility visibility = context.getCurrentVisibility();
if (visibility == MODULE_FUNCTION) visibility = PRIVATE;
if (runtime.getProc().isInstance(arg1)) {
// double-testing args.length here, but it avoids duplicating the proc-setup code in two places
RubyProc proc = (RubyProc)arg1;
body = proc;
newMethod = createProcMethod(name, visibility, proc);
} else if (runtime.getMethod().isInstance(arg1)) {
RubyMethod method = (RubyMethod)arg1;
body = method;
newMethod = new MethodMethod(this, method.unbind(null), visibility);
} else {
throw runtime.newTypeError("wrong argument type " + arg1.getType().getName() + " (expected Proc/Method)");
}
RuntimeHelpers.addInstanceMethod(this, name, newMethod, context.getPreviousVisibility(), context, runtime);
return body;
}
@Deprecated
public IRubyObject define_method(ThreadContext context, IRubyObject[] args, Block block) {
switch (args.length) {
case 1:
return define_method(context, args[0], block);
case 2:
return define_method(context, args[0], args[1], block);
default:
throw context.getRuntime().newArgumentError("wrong # of arguments(" + args.length + " for 2)");
}
}
private DynamicMethod createProcMethod(String name, Visibility visibility, RubyProc proc) {
Block block = proc.getBlock();
block.getBinding().getFrame().setKlazz(this);
block.getBinding().getFrame().setName(name);
StaticScope scope = block.getBody().getStaticScope();
// for zsupers in define_method (blech!) we tell the proc scope to act as the "argument" scope
scope.setArgumentScope(true);
Arity arity = block.arity();
// just using required is broken...but no more broken than before zsuper refactoring
scope.setRequiredArgs(arity.required());
if(!arity.isFixed()) {
scope.setRestArg(arity.required());
}
return new ProcMethod(this, proc, visibility);
}
@Deprecated
public IRubyObject executeUnder(ThreadContext context, Callback method, IRubyObject[] args, Block block) {
context.preExecuteUnder(this, block);
try {
return method.execute(this, args, block);
} finally {
context.postExecuteUnder();
}
}
@JRubyMethod(name = "name")
public RubyString name() {
return getRuntime().newString(getBaseName() == null ? "" : getName());
}
protected IRubyObject cloneMethods(RubyModule clone) {
RubyModule realType = this.getNonIncludedClass();
for (Map.Entry<String, DynamicMethod> entry : getMethods().entrySet()) {
DynamicMethod method = entry.getValue();
// Do not clone cached methods
// FIXME: MRI copies all methods here
if (method.getImplementationClass() == realType || method instanceof UndefinedMethod) {
// A cloned method now belongs to a new class. Set it.
// TODO: Make DynamicMethod immutable
DynamicMethod clonedMethod = method.dup();
clonedMethod.setImplementationClass(clone);
clone.putMethod(entry.getKey(), clonedMethod);
}
}
return clone;
}
/** rb_mod_init_copy
*
*/
@JRubyMethod(name = "initialize_copy", required = 1)
@Override
public IRubyObject initialize_copy(IRubyObject original) {
super.initialize_copy(original);
RubyModule originalModule = (RubyModule)original;
if (!getMetaClass().isSingleton()) setMetaClass(originalModule.getSingletonClassClone());
setSuperClass(originalModule.getSuperClass());
if (originalModule.hasVariables()){
syncVariables(originalModule.getVariableList());
}
originalModule.cloneMethods(this);
return this;
}
/** rb_mod_included_modules
*
*/
@JRubyMethod(name = "included_modules")
public RubyArray included_modules(ThreadContext context) {
RubyArray ary = context.getRuntime().newArray();
for (RubyModule p = getSuperClass(); p != null; p = p.getSuperClass()) {
if (p.isIncluded()) {
ary.append(p.getNonIncludedClass());
}
}
return ary;
}
/** rb_mod_ancestors
*
*/
@JRubyMethod(name = "ancestors")
public RubyArray ancestors(ThreadContext context) {
return context.getRuntime().newArray(getAncestorList());
}
@Deprecated
public RubyArray ancestors() {
return getRuntime().newArray(getAncestorList());
}
public List<IRubyObject> getAncestorList() {
ArrayList<IRubyObject> list = new ArrayList<IRubyObject>();
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if(!p.isSingleton()) {
list.add(p.getNonIncludedClass());
}
}
return list;
}
public boolean hasModuleInHierarchy(RubyModule type) {
// XXX: This check previously used callMethod("==") to check for equality between classes
// when scanning the hierarchy. However the == check may be safe; we should only ever have
// one instance bound to a given type/constant. If it's found to be unsafe, examine ways
// to avoid the == call.
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (p.getNonIncludedClass() == type) return true;
}
return false;
}
@Override
public int hashCode() {
return id;
}
@JRubyMethod(name = "hash")
@Override
public RubyFixnum hash() {
return getRuntime().newFixnum(id);
}
/** rb_mod_to_s
*
*/
@JRubyMethod(name = "to_s")
@Override
public IRubyObject to_s() {
if(isSingleton()){
IRubyObject attached = ((MetaClass)this).getAttached();
StringBuilder buffer = new StringBuilder("#<Class:");
if (attached != null) { // FIXME: figure out why we get null sometimes
if(attached instanceof RubyClass || attached instanceof RubyModule){
buffer.append(attached.inspect());
}else{
buffer.append(attached.anyToString());
}
}
buffer.append(">");
return getRuntime().newString(buffer.toString());
}
return getRuntime().newString(getName());
}
/** rb_mod_eqq
*
*/
@JRubyMethod(name = "===", required = 1)
@Override
public RubyBoolean op_eqq(ThreadContext context, IRubyObject obj) {
return context.getRuntime().newBoolean(isInstance(obj));
}
@JRubyMethod(name = "==", required = 1)
@Override
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
return super.op_equal(context, other);
}
/** rb_mod_freeze
*
*/
@JRubyMethod(name = "freeze")
@Override
public IRubyObject freeze(ThreadContext context) {
to_s();
return super.freeze(context);
}
/** rb_mod_le
*
*/
@JRubyMethod(name = "<=", required = 1)
public IRubyObject op_le(IRubyObject obj) {
if (!(obj instanceof RubyModule)) {
throw getRuntime().newTypeError("compared with non class/module");
}
if (isKindOfModule((RubyModule) obj)) {
return getRuntime().getTrue();
} else if (((RubyModule) obj).isKindOfModule(this)) {
return getRuntime().getFalse();
}
return getRuntime().getNil();
}
/** rb_mod_lt
*
*/
@JRubyMethod(name = "<", required = 1)
public IRubyObject op_lt(IRubyObject obj) {
return obj == this ? getRuntime().getFalse() : op_le(obj);
}
/** rb_mod_ge
*
*/
@JRubyMethod(name = ">=", required = 1)
public IRubyObject op_ge(IRubyObject obj) {
if (!(obj instanceof RubyModule)) {
throw getRuntime().newTypeError("compared with non class/module");
}
return ((RubyModule) obj).op_le(this);
}
/** rb_mod_gt
*
*/
@JRubyMethod(name = ">", required = 1)
public IRubyObject op_gt(IRubyObject obj) {
return this == obj ? getRuntime().getFalse() : op_ge(obj);
}
/** rb_mod_cmp
*
*/
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(IRubyObject obj) {
if (this == obj) return getRuntime().newFixnum(0);
if (!(obj instanceof RubyModule)) return getRuntime().getNil();
RubyModule module = (RubyModule) obj;
if (module.isKindOfModule(this)) {
return getRuntime().newFixnum(1);
} else if (this.isKindOfModule(module)) {
return getRuntime().newFixnum(-1);
}
return getRuntime().getNil();
}
public boolean isKindOfModule(RubyModule type) {
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (p.isSame(type)) {
return true;
}
}
return false;
}
protected boolean isSame(RubyModule module) {
return this == module;
}
/** rb_mod_initialize
*
*/
@JRubyMethod(name = "initialize", frame = true, visibility = PRIVATE)
public IRubyObject initialize(Block block) {
if (block.isGiven()) {
// class and module bodies default to public, so make the block's visibility public. JRUBY-1185.
block.getBinding().setVisibility(PUBLIC);
block.yield(getRuntime().getCurrentContext(), this, this, this, false);
}
return getRuntime().getNil();
}
public void addReadWriteAttribute(ThreadContext context, String name) {
addAccessor(context, name.intern(), true, true);
}
public void addReadAttribute(ThreadContext context, String name) {
addAccessor(context, name.intern(), true, false);
}
public void addWriteAttribute(ThreadContext context, String name) {
addAccessor(context, name.intern(), false, true);
}
/** rb_mod_attr
*
*/
@JRubyMethod(name = "attr", required = 1, optional = 1, visibility = PRIVATE, reads = VISIBILITY)
public IRubyObject attr(ThreadContext context, IRubyObject[] args) {
boolean writeable = args.length > 1 ? args[1].isTrue() : false;
addAccessor(context, args[0].asJavaString().intern(), true, writeable);
return getRuntime().getNil();
}
/**
* @deprecated
*/
public IRubyObject attr_reader(IRubyObject[] args) {
return attr_reader(getRuntime().getCurrentContext(), args);
}
/** rb_mod_attr_reader
*
*/
@JRubyMethod(name = "attr_reader", rest = true, visibility = PRIVATE, reads = VISIBILITY)
public IRubyObject attr_reader(ThreadContext context, IRubyObject[] args) {
for (int i = 0; i < args.length; i++) {
addAccessor(context, args[i].asJavaString().intern(), true, false);
}
return context.getRuntime().getNil();
}
/** rb_mod_attr_writer
*
*/
@JRubyMethod(name = "attr_writer", rest = true, visibility = PRIVATE, reads = VISIBILITY)
public IRubyObject attr_writer(ThreadContext context, IRubyObject[] args) {
for (int i = 0; i < args.length; i++) {
addAccessor(context, args[i].asJavaString().intern(), false, true);
}
return context.getRuntime().getNil();
}
/**
* @deprecated
*/
public IRubyObject attr_accessor(IRubyObject[] args) {
return attr_accessor(getRuntime().getCurrentContext(), args);
}
/** rb_mod_attr_accessor
*
*/
@JRubyMethod(name = "attr_accessor", rest = true, visibility = PRIVATE, reads = VISIBILITY)
public IRubyObject attr_accessor(ThreadContext context, IRubyObject[] args) {
for (int i = 0; i < args.length; i++) {
// This is almost always already interned, since it will be called with a symbol in most cases
// but when created from Java code, we might get an argument that needs to be interned.
// addAccessor has as a precondition that the string MUST be interned
addAccessor(context, args[i].asJavaString().intern(), true, true);
}
return context.getRuntime().getNil();
}
/**
* Get a list of all instance methods names of the provided visibility unless not is true, then
* get all methods which are not the provided
*
* @param args passed into one of the Ruby instance_method methods
* @param visibility to find matching instance methods against
* @param not if true only find methods not matching supplied visibility
* @return a RubyArray of instance method names
*/
private RubyArray instance_methods(IRubyObject[] args, final Visibility visibility, boolean not) {
boolean includeSuper = args.length > 0 ? args[0].isTrue() : true;
RubyArray ary = getRuntime().newArray();
Set<String> seen = new HashSet<String>();
for (RubyModule type = this; type != null; type = type.getSuperClass()) {
RubyModule realType = type.getNonIncludedClass();
for (Iterator iter = type.getMethods().entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
DynamicMethod method = (DynamicMethod) entry.getValue();
String methodName = (String) entry.getKey();
if (! seen.contains(methodName)) {
seen.add(methodName);
if (method.getImplementationClass() == realType &&
(!not && method.getVisibility() == visibility || (not && method.getVisibility() != visibility)) &&
! method.isUndefined()) {
ary.append(getRuntime().newString(methodName));
}
}
}
if (!includeSuper) {
break;
}
}
return ary;
}
@JRubyMethod(name = "instance_methods", optional = 1)
public RubyArray instance_methods(IRubyObject[] args) {
return instance_methods(args, PRIVATE, true);
}
@JRubyMethod(name = "public_instance_methods", optional = 1)
public RubyArray public_instance_methods(IRubyObject[] args) {
return instance_methods(args, PUBLIC, false);
}
@JRubyMethod(name = "instance_method", required = 1)
public IRubyObject instance_method(IRubyObject symbol) {
return newMethod(null, symbol.asJavaString(), false);
}
/** rb_class_protected_instance_methods
*
*/
@JRubyMethod(name = "protected_instance_methods", optional = 1)
public RubyArray protected_instance_methods(IRubyObject[] args) {
return instance_methods(args, PROTECTED, false);
}
/** rb_class_private_instance_methods
*
*/
@JRubyMethod(name = "private_instance_methods", optional = 1)
public RubyArray private_instance_methods(IRubyObject[] args) {
return instance_methods(args, PRIVATE, false);
}
/** rb_mod_append_features
*
*/
@JRubyMethod(name = "append_features", required = 1, visibility = PRIVATE)
public RubyModule append_features(IRubyObject module) {
if (!(module instanceof RubyModule)) {
// MRI error message says Class, even though Module is ok
throw getRuntime().newTypeError(module,getRuntime().getClassClass());
}
((RubyModule) module).includeModule(this);
return this;
}
/** rb_mod_extend_object
*
*/
@JRubyMethod(name = "extend_object", required = 1, visibility = PRIVATE)
public IRubyObject extend_object(IRubyObject obj) {
obj.getSingletonClass().includeModule(this);
return obj;
}
/** rb_mod_include
*
*/
@JRubyMethod(name = "include", required = 1, rest = true, visibility = PRIVATE)
public RubyModule include(IRubyObject[] modules) {
ThreadContext context = getRuntime().getCurrentContext();
// MRI checks all types first:
for (int i = modules.length; --i >= 0; ) {
IRubyObject obj = modules[i];
if (!obj.isModule()) throw context.getRuntime().newTypeError(obj, context.getRuntime().getModule());
}
for (int i = modules.length - 1; i >= 0; i--) {
modules[i].callMethod(context, "append_features", this);
modules[i].callMethod(context, "included", this);
}
return this;
}
@JRubyMethod(name = "included", required = 1)
public IRubyObject included(ThreadContext context, IRubyObject other) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "extended", required = 1, frame = true)
public IRubyObject extended(ThreadContext context, IRubyObject other, Block block) {
return context.getRuntime().getNil();
}
private void setVisibility(ThreadContext context, IRubyObject[] args, Visibility visibility) {
if (context.getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw context.getRuntime().newSecurityError("Insecure: can't change method visibility");
}
if (args.length == 0) {
// Note: we change current frames visibility here because the methods which call
// this method are all "fast" (e.g. they do not created their own frame).
context.setCurrentVisibility(visibility);
} else {
setMethodVisibility(args, visibility);
}
}
/** rb_mod_public
*
*/
@JRubyMethod(name = "public", rest = true, visibility = PRIVATE, writes = VISIBILITY)
public RubyModule rbPublic(ThreadContext context, IRubyObject[] args) {
setVisibility(context, args, PUBLIC);
return this;
}
/** rb_mod_protected
*
*/
@JRubyMethod(name = "protected", rest = true, visibility = PRIVATE, writes = VISIBILITY)
public RubyModule rbProtected(ThreadContext context, IRubyObject[] args) {
setVisibility(context, args, PROTECTED);
return this;
}
/** rb_mod_private
*
*/
@JRubyMethod(name = "private", rest = true, visibility = PRIVATE, writes = VISIBILITY)
public RubyModule rbPrivate(ThreadContext context, IRubyObject[] args) {
setVisibility(context, args, PRIVATE);
return this;
}
/** rb_mod_modfunc
*
*/
@JRubyMethod(name = "module_function", rest = true, visibility = PRIVATE, writes = VISIBILITY)
public RubyModule module_function(ThreadContext context, IRubyObject[] args) {
if (context.getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw context.getRuntime().newSecurityError("Insecure: can't change method visibility");
}
if (args.length == 0) {
context.setCurrentVisibility(MODULE_FUNCTION);
} else {
setMethodVisibility(args, PRIVATE);
for (int i = 0; i < args.length; i++) {
String name = args[i].asJavaString().intern();
DynamicMethod method = searchMethod(name);
assert !method.isUndefined() : "undefined method '" + name + "'";
getSingletonClass().addMethod(name, new WrapperMethod(getSingletonClass(), method, PUBLIC));
callMethod(context, "singleton_method_added", context.getRuntime().fastNewSymbol(name));
}
}
return this;
}
@JRubyMethod(name = "method_added", required = 1, visibility = PRIVATE)
public IRubyObject method_added(ThreadContext context, IRubyObject nothing) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "method_removed", required = 1, visibility = PRIVATE)
public IRubyObject method_removed(ThreadContext context, IRubyObject nothing) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "method_undefined", required = 1, visibility = PRIVATE)
public IRubyObject method_undefined(ThreadContext context, IRubyObject nothing) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "method_defined?", required = 1)
public RubyBoolean method_defined_p(ThreadContext context, IRubyObject symbol) {
return isMethodBound(symbol.asJavaString(), true) ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
@JRubyMethod(name = "public_method_defined?", required = 1)
public IRubyObject public_method_defined(ThreadContext context, IRubyObject symbol) {
DynamicMethod method = searchMethod(symbol.asJavaString());
return context.getRuntime().newBoolean(!method.isUndefined() && method.getVisibility() == PUBLIC);
}
@JRubyMethod(name = "protected_method_defined?", required = 1)
public IRubyObject protected_method_defined(ThreadContext context, IRubyObject symbol) {
DynamicMethod method = searchMethod(symbol.asJavaString());
return context.getRuntime().newBoolean(!method.isUndefined() && method.getVisibility() == PROTECTED);
}
@JRubyMethod(name = "private_method_defined?", required = 1)
public IRubyObject private_method_defined(ThreadContext context, IRubyObject symbol) {
DynamicMethod method = searchMethod(symbol.asJavaString());
return context.getRuntime().newBoolean(!method.isUndefined() && method.getVisibility() == PRIVATE);
}
@JRubyMethod(name = "public_class_method", rest = true)
public RubyModule public_class_method(IRubyObject[] args) {
getMetaClass().setMethodVisibility(args, PUBLIC);
return this;
}
@JRubyMethod(name = "private_class_method", rest = true)
public RubyModule private_class_method(IRubyObject[] args) {
getMetaClass().setMethodVisibility(args, PRIVATE);
return this;
}
@JRubyMethod(name = "alias_method", required = 2, visibility = PRIVATE)
public RubyModule alias_method(ThreadContext context, IRubyObject newId, IRubyObject oldId) {
String newName = newId.asJavaString();
defineAlias(newName, oldId.asJavaString());
RubySymbol newSym = newId instanceof RubySymbol ? (RubySymbol)newId :
context.getRuntime().newSymbol(newName);
if (isSingleton()) {
((MetaClass)this).getAttached().callMethod(context, "singleton_method_added", newSym);
} else {
callMethod(context, "method_added", newSym);
}
return this;
}
@JRubyMethod(name = "undef_method", required = 1, rest = true, visibility = PRIVATE)
public RubyModule undef_method(ThreadContext context, IRubyObject[] args) {
for (int i=0; i<args.length; i++) {
undef(context, args[i].asJavaString());
}
return this;
}
@JRubyMethod(name = {"module_eval", "class_eval"}, frame = true)
public IRubyObject module_eval(ThreadContext context, Block block) {
return specificEval(context, this, block);
}
@JRubyMethod(name = {"module_eval", "class_eval"}, frame = true)
public IRubyObject module_eval(ThreadContext context, IRubyObject arg0, Block block) {
return specificEval(context, this, arg0, block);
}
@JRubyMethod(name = {"module_eval", "class_eval"}, frame = true)
public IRubyObject module_eval(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
return specificEval(context, this, arg0, arg1, block);
}
@JRubyMethod(name = {"module_eval", "class_eval"}, frame = true)
public IRubyObject module_eval(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
return specificEval(context, this, arg0, arg1, arg2, block);
}
@Deprecated
public IRubyObject module_eval(ThreadContext context, IRubyObject[] args, Block block) {
return specificEval(context, this, args, block);
}
@JRubyMethod(name = "remove_method", required = 1, rest = true, visibility = PRIVATE)
public RubyModule remove_method(ThreadContext context, IRubyObject[] args) {
for(int i=0;i<args.length;i++) {
removeMethod(context, args[i].asJavaString());
}
return this;
}
public static void marshalTo(RubyModule module, MarshalStream output) throws java.io.IOException {
output.registerLinkTarget(module);
output.writeString(MarshalStream.getPathFromClass(module));
}
public static RubyModule unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
String name = RubyString.byteListToString(input.unmarshalString());
RubyModule result = UnmarshalStream.getModuleFromPath(input.getRuntime(), name);
input.registerLinkTarget(result);
return result;
}
/* Module class methods */
/**
* Return an array of nested modules or classes.
*/
@JRubyMethod(name = "nesting", frame = true, meta = true)
public static RubyArray nesting(ThreadContext context, IRubyObject recv, Block block) {
Ruby runtime = context.getRuntime();
RubyModule object = runtime.getObject();
StaticScope scope = context.getCurrentScope().getStaticScope();
RubyArray result = runtime.newArray();
for (StaticScope current = scope; current.getModule() != object; current = current.getPreviousCRefScope()) {
result.append(current.getModule());
}
return result;
}
private void doIncludeModule(RubyModule includedModule) {
boolean skip = false;
RubyModule currentModule = this;
while (includedModule != null) {
if (getNonIncludedClass() == includedModule.getNonIncludedClass()) {
throw getRuntime().newArgumentError("cyclic include detected");
}
boolean superclassSeen = false;
// scan class hierarchy for module
for (RubyModule superClass = this.getSuperClass(); superClass != null; superClass = superClass.getSuperClass()) {
if (superClass instanceof IncludedModuleWrapper) {
if (superClass.getNonIncludedClass() == includedModule.getNonIncludedClass()) {
if (!superclassSeen) {
currentModule = superClass;
}
skip = true;
break;
}
} else {
superclassSeen = true;
}
}
if (!skip) {
// blow away caches for any methods that are redefined by module
getRuntime().getCacheMap().moduleIncluded(currentModule, includedModule);
// In the current logic, if we get here we know that module is not an
// IncludedModuleWrapper, so there's no need to fish out the delegate. But just
// in case the logic should change later, let's do it anyway:
currentModule.setSuperClass(new IncludedModuleWrapper(getRuntime(), currentModule.getSuperClass(),
includedModule.getNonIncludedClass()));
currentModule = currentModule.getSuperClass();
}
includedModule = includedModule.getSuperClass();
skip = false;
}
}
//
////////////////// CLASS VARIABLE RUBY METHODS ////////////////
//
@JRubyMethod(name = "class_variable_defined?", required = 1)
public IRubyObject class_variable_defined_p(ThreadContext context, IRubyObject var) {
String internedName = validateClassVariable(var.asJavaString().intern());
RubyModule module = this;
do {
if (module.fastHasClassVariable(internedName)) {
return context.getRuntime().getTrue();
}
} while ((module = module.getSuperClass()) != null);
return context.getRuntime().getFalse();
}
/** rb_mod_cvar_get
*
*/
@JRubyMethod(name = "class_variable_get", required = 1, visibility = PRIVATE)
public IRubyObject class_variable_get(IRubyObject var) {
return fastGetClassVar(validateClassVariable(var.asJavaString()).intern());
}
/** rb_mod_cvar_set
*
*/
@JRubyMethod(name = "class_variable_set", required = 2, visibility = PRIVATE)
public IRubyObject class_variable_set(IRubyObject var, IRubyObject value) {
return fastSetClassVar(validateClassVariable(var.asJavaString()).intern(), value);
}
/** rb_mod_remove_cvar
*
*/
@JRubyMethod(name = "remove_class_variable", required = 1, visibility = PRIVATE)
public IRubyObject remove_class_variable(ThreadContext context, IRubyObject name) {
String javaName = validateClassVariable(name.asJavaString());
IRubyObject value;
if ((value = deleteClassVariable(javaName)) != null) {
return value;
}
if (fastIsClassVarDefined(javaName)) {
throw cannotRemoveError(javaName);
}
throw context.getRuntime().newNameError("class variable " + javaName + " not defined for " + getName(), javaName);
}
/** rb_mod_class_variables
*
*/
@JRubyMethod(name = "class_variables")
public RubyArray class_variables(ThreadContext context) {
Set<String> names = new HashSet<String>();
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
for (String name : p.getClassVariableNameList()) {
names.add(name);
}
}
Ruby runtime = context.getRuntime();
RubyArray ary = runtime.newArray();
for (String name : names) {
ary.append(runtime.newString(name));
}
return ary;
}
//
////////////////// CONSTANT RUBY METHODS ////////////////
//
/** rb_mod_const_defined
*
*/
@JRubyMethod(name = "const_defined?", required = 1)
public RubyBoolean const_defined_p(ThreadContext context, IRubyObject symbol) {
// Note: includes part of fix for JRUBY-1339
return context.getRuntime().newBoolean(fastIsConstantDefined(validateConstant(symbol.asJavaString()).intern()));
}
/** rb_mod_const_get
*
*/
@JRubyMethod(name = "const_get", required = 1)
public IRubyObject const_get(IRubyObject symbol) {
return fastGetConstant(validateConstant(symbol.asJavaString()).intern());
}
/** rb_mod_const_set
*
*/
@JRubyMethod(name = "const_set", required = 2)
public IRubyObject const_set(IRubyObject symbol, IRubyObject value) {
return fastSetConstant(validateConstant(symbol.asJavaString()).intern(), value);
}
@JRubyMethod(name = "remove_const", required = 1, visibility = PRIVATE)
public IRubyObject remove_const(ThreadContext context, IRubyObject name) {
String id = validateConstant(name.asJavaString());
IRubyObject value;
if ((value = deleteConstant(id)) != null) {
if (value != UNDEF) {
return value;
}
context.getRuntime().getLoadService().removeAutoLoadFor(getName() + "::" + id);
// FIXME: I'm not sure this is right, but the old code returned
// the undef, which definitely isn't right...
return context.getRuntime().getNil();
}
if (hasConstantInHierarchy(id)) {
throw cannotRemoveError(id);
}
throw context.getRuntime().newNameError("constant " + id + " not defined for " + getName(), id);
}
private boolean hasConstantInHierarchy(final String name) {
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (p.hasConstant(name)) {
return true;
}
}
return false;
}
/**
* Base implementation of Module#const_missing, throws NameError for specific missing constant.
*
* @param name The constant name which was found to be missing
* @return Nothing! Absolutely nothing! (though subclasses might choose to return something)
*/
@JRubyMethod(name = "const_missing", required = 1, frame = true)
public IRubyObject const_missing(ThreadContext context, IRubyObject name, Block block) {
/* Uninitialized constant */
if (this != context.getRuntime().getObject()) {
throw context.getRuntime().newNameError("uninitialized constant " + getName() + "::" + name.asJavaString(), "" + getName() + "::" + name.asJavaString());
}
throw context.getRuntime().newNameError("uninitialized constant " + name.asJavaString(), name.asJavaString());
}
/** rb_mod_constants
*
*/
@JRubyMethod(name = "constants")
public RubyArray constants(ThreadContext context) {
Ruby runtime = context.getRuntime();
RubyArray array = runtime.newArray();
RubyModule objectClass = runtime.getObject();
if (getRuntime().getModule() == this) {
for (String name : objectClass.getStoredConstantNameList()) {
array.append(runtime.newString(name));
}
} else if (objectClass == this) {
for (String name : getStoredConstantNameList()) {
array.append(runtime.newString(name));
}
} else {
Set<String> names = new HashSet<String>();
for (RubyModule p = this; p != null; p = p.getSuperClass()) {
if (objectClass != p) {
for (String name : p.getStoredConstantNameList()) {
names.add(name);
}
}
}
for (String name : names) {
array.append(runtime.newString(name));
}
}
return array;
}
//
////////////////// CLASS VARIABLE API METHODS ////////////////
//
/**
* Set the named class variable to the given value, provided taint and freeze allow setting it.
*
* Ruby C equivalent = "rb_cvar_set"
*
* @param name The variable name to set
* @param value The value to set it to
*/
public IRubyObject setClassVar(String name, IRubyObject value) {
RubyModule module = this;
do {
if (module.hasClassVariable(name)) {
return module.storeClassVariable(name, value);
}
} while ((module = module.getSuperClass()) != null);
return storeClassVariable(name, value);
}
public IRubyObject fastSetClassVar(final String internedName, final IRubyObject value) {
assert internedName == internedName.intern() : internedName + " is not interned";
RubyModule module = this;
do {
if (module.fastHasClassVariable(internedName)) {
return module.fastStoreClassVariable(internedName, value);
}
} while ((module = module.getSuperClass()) != null);
return fastStoreClassVariable(internedName, value);
}
/**
* Retrieve the specified class variable, searching through this module, included modules, and supermodules.
*
* Ruby C equivalent = "rb_cvar_get"
*
* @param name The name of the variable to retrieve
* @return The variable's value, or throws NameError if not found
*/
public IRubyObject getClassVar(String name) {
assert IdUtil.isClassVariable(name);
IRubyObject value;
RubyModule module = this;
do {
if ((value = module.variableTableFetch(name)) != null) return value;
} while ((module = module.getSuperClass()) != null);
throw getRuntime().newNameError("uninitialized class variable " + name + " in " + getName(), name);
}
public IRubyObject fastGetClassVar(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
assert IdUtil.isClassVariable(internedName);
IRubyObject value;
RubyModule module = this;
do {
if ((value = module.variableTableFastFetch(internedName)) != null) return value;
} while ((module = module.getSuperClass()) != null);
throw getRuntime().newNameError("uninitialized class variable " + internedName + " in " + getName(), internedName);
}
/**
* Is class var defined?
*
* Ruby C equivalent = "rb_cvar_defined"
*
* @param name The class var to determine "is defined?"
* @return true if true, false if false
*/
public boolean isClassVarDefined(String name) {
RubyModule module = this;
do {
if (module.hasClassVariable(name)) return true;
} while ((module = module.getSuperClass()) != null);
return false;
}
public boolean fastIsClassVarDefined(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
RubyModule module = this;
do {
if (module.fastHasClassVariable(internedName)) return true;
} while ((module = module.getSuperClass()) != null);
return false;
}
/** rb_mod_remove_cvar
*
* FIXME: any good reason to have two identical methods? (same as remove_class_variable)
*/
public IRubyObject removeCvar(IRubyObject name) { // Wrong Parameter ?
String internedName = validateClassVariable(name.asJavaString());
IRubyObject value;
if ((value = deleteClassVariable(internedName)) != null) {
return value;
}
if (fastIsClassVarDefined(internedName)) {
throw cannotRemoveError(internedName);
}
throw getRuntime().newNameError("class variable " + internedName + " not defined for " + getName(), internedName);
}
//
////////////////// CONSTANT API METHODS ////////////////
//
public IRubyObject getConstantAt(String name) {
IRubyObject value;
if ((value = fetchConstant(name)) != UNDEF) {
return value;
}
deleteConstant(name);
return getRuntime().getLoadService().autoload(getName() + "::" + name);
}
public IRubyObject fastGetConstantAt(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
IRubyObject value;
if ((value = fastFetchConstant(internedName)) != UNDEF) {
return value;
}
deleteConstant(internedName);
return getRuntime().getLoadService().autoload(getName() + "::" + internedName);
}
/**
* Retrieve the named constant, invoking 'const_missing' should that be appropriate.
*
* @param name The constant to retrieve
* @return The value for the constant, or null if not found
*/
public IRubyObject getConstant(String name) {
assert IdUtil.isConstant(name);
boolean retryForModule = false;
IRubyObject value;
RubyModule p = this;
retry: while (true) {
while (p != null) {
if ((value = p.constantTableFetch(name)) != null) {
if (value != UNDEF) {
return value;
}
p.deleteConstant(name);
if (getRuntime().getLoadService().autoload(
p.getName() + "::" + name) == null) {
break;
}
continue;
}
p = p.getSuperClass();
}
if (!retryForModule && !isClass()) {
retryForModule = true;
p = getRuntime().getObject();
continue retry;
}
break;
}
return callMethod(getRuntime().getCurrentContext(),
"const_missing", getRuntime().newSymbol(name));
}
public IRubyObject fastGetConstant(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
assert IdUtil.isConstant(internedName);
boolean retryForModule = false;
IRubyObject value;
RubyModule p = this;
retry: while (true) {
while (p != null) {
if ((value = p.constantTableFastFetch(internedName)) != null) {
if (value != UNDEF) {
return value;
}
p.deleteConstant(internedName);
if (getRuntime().getLoadService().autoload(
p.getName() + "::" + internedName) == null) {
break;
}
continue;
}
p = p.getSuperClass();
}
if (!retryForModule && !isClass()) {
retryForModule = true;
p = getRuntime().getObject();
continue retry;
}
break;
}
return callMethod(getRuntime().getCurrentContext(),
"const_missing", getRuntime().fastNewSymbol(internedName));
}
// not actually called anywhere (all known uses call the fast version)
public IRubyObject getConstantFrom(String name) {
return fastGetConstantFrom(name.intern());
}
public IRubyObject fastGetConstantFrom(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
assert IdUtil.isConstant(internedName);
RubyClass objectClass = getRuntime().getObject();
IRubyObject value;
RubyModule p = this;
while (p != null) {
if ((value = p.constantTableFastFetch(internedName)) != null) {
if (value != UNDEF) {
if (p == objectClass && this != objectClass) {
String badCName = getName() + "::" + internedName;
getRuntime().getWarnings().warn(ID.CONSTANT_BAD_REFERENCE, "toplevel constant " +
internedName + " referenced by " + badCName, badCName);
}
return value;
}
p.deleteConstant(internedName);
if (getRuntime().getLoadService().autoload(
p.getName() + "::" + internedName) == null) {
break;
}
continue;
}
p = p.getSuperClass();
}
return callMethod(getRuntime().getCurrentContext(),
"const_missing", getRuntime().fastNewSymbol(internedName));
}
/**
* Set the named constant on this module. Also, if the value provided is another Module and
* that module has not yet been named, assign it the specified name.
*
* @param name The name to assign
* @param value The value to assign to it; if an unnamed Module, also set its basename to name
* @return The result of setting the variable.
*/
public IRubyObject setConstant(String name, IRubyObject value) {
IRubyObject oldValue;
if ((oldValue = fetchConstant(name)) != null) {
if (oldValue == UNDEF) {
getRuntime().getLoadService().removeAutoLoadFor(getName() + "::" + name);
} else {
getRuntime().getWarnings().warn(ID.CONSTANT_ALREADY_INITIALIZED, "already initialized constant " + name, name);
}
}
storeConstant(name, value);
// if adding a module under a constant name, set that module's basename to the constant name
if (value instanceof RubyModule) {
RubyModule module = (RubyModule)value;
if (module.getBaseName() == null) {
module.setBaseName(name);
module.setParent(this);
}
/*
module.setParent(this);
*/
}
return value;
}
public IRubyObject fastSetConstant(String internedName, IRubyObject value) {
assert internedName == internedName.intern() : internedName + " is not interned";
IRubyObject oldValue;
if ((oldValue = fastFetchConstant(internedName)) != null) {
if (oldValue == UNDEF) {
getRuntime().getLoadService().removeAutoLoadFor(getName() + "::" + internedName);
} else {
getRuntime().getWarnings().warn(ID.CONSTANT_ALREADY_INITIALIZED, "already initialized constant " + internedName, internedName);
}
}
fastStoreConstant(internedName, value);
// if adding a module under a constant name, set that module's basename to the constant name
if (value instanceof RubyModule) {
RubyModule module = (RubyModule)value;
if (module.getBaseName() == null) {
module.setBaseName(internedName);
module.setParent(this);
}
/*
module.setParent(this);
*/
}
return value;
}
/** rb_define_const
*
*/
public void defineConstant(String name, IRubyObject value) {
assert value != null;
if (this == getRuntime().getClassClass()) {
getRuntime().secure(4);
}
if (!IdUtil.isValidConstantName(name)) {
throw getRuntime().newNameError("bad constant name " + name, name);
}
setConstant(name, value);
}
// Fix for JRUBY-1339 - search hierarchy for constant
/** rb_const_defined_at
*
*/
public boolean isConstantDefined(String name) {
assert IdUtil.isConstant(name);
boolean isObject = this == getRuntime().getObject();
RubyModule module = this;
do {
Object value;
if ((value = module.constantTableFetch(name)) != null) {
if (value != UNDEF) return true;
return getRuntime().getLoadService().autoloadFor(
module.getName() + "::" + name) != null;
}
} while (isObject && (module = module.getSuperClass()) != null );
return false;
}
public boolean fastIsConstantDefined(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
assert IdUtil.isConstant(internedName);
boolean isObject = this == getRuntime().getObject();
RubyModule module = this;
do {
Object value;
if ((value = module.constantTableFastFetch(internedName)) != null) {
if (value != UNDEF) return true;
return getRuntime().getLoadService().autoloadFor(
module.getName() + "::" + internedName) != null;
}
} while (isObject && (module = module.getSuperClass()) != null );
return false;
}
//
////////////////// COMMON CONSTANT / CVAR METHODS ////////////////
//
private RaiseException cannotRemoveError(String id) {
return getRuntime().newNameError("cannot remove " + id + " for " + getName(), id);
}
//
////////////////// INTERNAL MODULE VARIABLE API METHODS ////////////////
//
/**
* Behaves similarly to {@link #getClassVar(String)}. Searches this
* class/module <em>and its ancestors</em> for the specified internal
* variable.
*
* @param name the internal variable name
* @return the value of the specified internal variable if found, else null
* @see #setInternalModuleVariable(String, IRubyObject)
*/
public boolean hasInternalModuleVariable(final String name) {
RubyModule module = this;
do {
if (module.hasInternalVariable(name)) {
return true;
}
} while ((module = module.getSuperClass()) != null);
return false;
}
/**
* Behaves similarly to {@link #getClassVar(String)}. Searches this
* class/module <em>and its ancestors</em> for the specified internal
* variable.
*
* @param name the internal variable name
* @return the value of the specified internal variable if found, else null
* @see #setInternalModuleVariable(String, IRubyObject)
*/
public IRubyObject searchInternalModuleVariable(final String name) {
RubyModule module = this;
IRubyObject value;
do {
if ((value = module.getInternalVariable(name)) != null) {
return value;
}
} while ((module = module.getSuperClass()) != null);
return null;
}
/**
* Behaves similarly to {@link #setClassVar(String, IRubyObject)}. If the
* specified internal variable is found in this class/module <em>or an ancestor</em>,
* it is set where found. Otherwise it is set in this module.
*
* @param name the internal variable name
* @param value the internal variable value
* @see #searchInternalModuleVariable(String)
*/
public void setInternalModuleVariable(final String name, final IRubyObject value) {
RubyModule module = this;
do {
if (module.hasInternalVariable(name)) {
module.setInternalVariable(name, value);
return;
}
} while ((module = module.getSuperClass()) != null);
setInternalVariable(name, value);
}
//
////////////////// LOW-LEVEL CLASS VARIABLE INTERFACE ////////////////
//
// fetch/store/list class variables for this module
//
public boolean hasClassVariable(String name) {
assert IdUtil.isClassVariable(name);
return variableTableContains(name);
}
public boolean fastHasClassVariable(String internedName) {
assert IdUtil.isClassVariable(internedName);
return variableTableFastContains(internedName);
}
public IRubyObject fetchClassVariable(String name) {
assert IdUtil.isClassVariable(name);
return variableTableFetch(name);
}
public IRubyObject fastFetchClassVariable(String internedName) {
assert IdUtil.isClassVariable(internedName);
return variableTableFastFetch(internedName);
}
public IRubyObject storeClassVariable(String name, IRubyObject value) {
assert IdUtil.isClassVariable(name) && value != null;
ensureClassVariablesSettable();
return variableTableStore(name, value);
}
public IRubyObject fastStoreClassVariable(String internedName, IRubyObject value) {
assert IdUtil.isClassVariable(internedName) && value != null;
ensureClassVariablesSettable();
return variableTableFastStore(internedName, value);
}
public IRubyObject deleteClassVariable(String name) {
assert IdUtil.isClassVariable(name);
ensureClassVariablesSettable();
return variableTableRemove(name);
}
public List<Variable<IRubyObject>> getClassVariableList() {
ArrayList<Variable<IRubyObject>> list = new ArrayList<Variable<IRubyObject>>();
VariableTableEntry[] table = variableTableGetTable();
IRubyObject readValue;
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if (IdUtil.isClassVariable(e.name)) {
if ((readValue = e.value) == null) readValue = variableTableReadLocked(e);
list.add(new VariableEntry<IRubyObject>(e.name, readValue));
}
}
}
return list;
}
public List<String> getClassVariableNameList() {
ArrayList<String> list = new ArrayList<String>();
VariableTableEntry[] table = variableTableGetTable();
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if (IdUtil.isClassVariable(e.name)) {
list.add(e.name);
}
}
}
return list;
}
protected static final String ERR_INSECURE_SET_CLASS_VAR = "Insecure: can't modify class variable";
protected static final String ERR_FROZEN_CVAR_TYPE = "class/module ";
protected final String validateClassVariable(String name) {
if (IdUtil.isValidClassVariableName(name)) {
return name;
}
throw getRuntime().newNameError("`" + name + "' is not allowed as a class variable name", name);
}
protected final void ensureClassVariablesSettable() {
Ruby runtime = getRuntime();
if (!isFrozen() && (runtime.getSafeLevel() < 4 || isTaint())) {
return;
}
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw runtime.newSecurityError(ERR_INSECURE_SET_CONSTANT);
}
if (isFrozen()) {
if (this instanceof RubyModule) {
throw runtime.newFrozenError(ERR_FROZEN_CONST_TYPE);
} else {
throw runtime.newFrozenError("");
}
}
}
//
////////////////// LOW-LEVEL CONSTANT INTERFACE ////////////////
//
// fetch/store/list constants for this module
//
public boolean hasConstant(String name) {
assert IdUtil.isConstant(name);
return constantTableContains(name);
}
public boolean fastHasConstant(String internedName) {
assert IdUtil.isConstant(internedName);
return constantTableFastContains(internedName);
}
// returns the stored value without processing undefs (autoloads)
public IRubyObject fetchConstant(String name) {
assert IdUtil.isConstant(name);
return constantTableFetch(name);
}
// returns the stored value without processing undefs (autoloads)
public IRubyObject fastFetchConstant(String internedName) {
assert IdUtil.isConstant(internedName);
return constantTableFastFetch(internedName);
}
public IRubyObject storeConstant(String name, IRubyObject value) {
assert IdUtil.isConstant(name) && value != null;
ensureConstantsSettable();
return constantTableStore(name, value);
}
public IRubyObject fastStoreConstant(String internedName, IRubyObject value) {
assert IdUtil.isConstant(internedName) && value != null;
ensureConstantsSettable();
return constantTableFastStore(internedName, value);
}
// removes and returns the stored value without processing undefs (autoloads)
public IRubyObject deleteConstant(String name) {
assert IdUtil.isConstant(name);
ensureConstantsSettable();
return constantTableRemove(name);
}
public List<Variable<IRubyObject>> getStoredConstantList() {
ArrayList<Variable<IRubyObject>> list = new ArrayList<Variable<IRubyObject>>();
ConstantTableEntry[] table = constantTableGetTable();
for (int i = table.length; --i >= 0; ) {
for (ConstantTableEntry e = table[i]; e != null; e = e.next) {
list.add(e);
}
}
return list;
}
public List<String> getStoredConstantNameList() {
ArrayList<String> list = new ArrayList<String>();
ConstantTableEntry[] table = constantTableGetTable();
for (int i = table.length; --i >= 0; ) {
for (ConstantTableEntry e = table[i]; e != null; e = e.next) {
list.add(e.name);
}
}
return list;
}
protected static final String ERR_INSECURE_SET_CONSTANT = "Insecure: can't modify constant";
protected static final String ERR_FROZEN_CONST_TYPE = "class/module ";
protected final String validateConstant(String name) {
if (IdUtil.isValidConstantName(name)) {
return name;
}
throw getRuntime().newNameError("wrong constant name " + name, name);
}
protected final void ensureConstantsSettable() {
Ruby runtime = getRuntime();
if (!isFrozen() && (runtime.getSafeLevel() < 4 || isTaint())) {
return;
}
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw runtime.newSecurityError(ERR_INSECURE_SET_CONSTANT);
}
if (isFrozen()) {
if (this instanceof RubyModule) {
throw runtime.newFrozenError(ERR_FROZEN_CONST_TYPE);
} else {
throw runtime.newFrozenError("");
}
}
}
//
////////////////// VARIABLE TABLE METHODS ////////////////
//
// Overridden to use variableWriteLock in place of synchronization
//
@Override
protected IRubyObject variableTableStore(String name, IRubyObject value) {
int hash = name.hashCode();
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
VariableTableEntry[] table;
VariableTableEntry e;
if ((table = variableTable) == null) {
table = new VariableTableEntry[VARIABLE_TABLE_DEFAULT_CAPACITY];
e = new VariableTableEntry(hash, name.intern(), value, null);
table[hash & (VARIABLE_TABLE_DEFAULT_CAPACITY - 1)] = e;
variableTableThreshold = (int)(VARIABLE_TABLE_DEFAULT_CAPACITY * VARIABLE_TABLE_LOAD_FACTOR);
variableTableSize = 1;
variableTable = table;
return value;
}
int potentialNewSize;
if ((potentialNewSize = variableTableSize + 1) > variableTableThreshold) {
table = variableTableRehash();
}
int index;
for (e = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
e.value = value;
return value;
}
}
// external volatile value initialization intended to obviate the need for
// readValueUnderLock technique used in ConcurrentHashMap. may be a little
// slower, but better to pay a price on first write rather than all reads.
e = new VariableTableEntry(hash, name.intern(), value, table[index]);
table[index] = e;
variableTableSize = potentialNewSize;
variableTable = table; // write-volatile
} finally {
lock.unlock();
}
return value;
}
@Override
protected IRubyObject variableTableFastStore(String internedName, IRubyObject value) {
assert internedName == internedName.intern() : internedName + " not interned";
int hash = internedName.hashCode();
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
VariableTableEntry[] table;
VariableTableEntry e;
if ((table = variableTable) == null) {
table = new VariableTableEntry[VARIABLE_TABLE_DEFAULT_CAPACITY];
e = new VariableTableEntry(hash, internedName, value, null);
table[hash & (VARIABLE_TABLE_DEFAULT_CAPACITY - 1)] = e;
variableTableThreshold = (int)(VARIABLE_TABLE_DEFAULT_CAPACITY * VARIABLE_TABLE_LOAD_FACTOR);
variableTableSize = 1;
variableTable = table;
return value;
}
int potentialNewSize;
if ((potentialNewSize = variableTableSize + 1) > variableTableThreshold) {
table = variableTableRehash();
}
int index;
for (e = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
e.value = value;
return value;
}
}
// external volatile value initialization intended to obviate the need for
// readValueUnderLock technique used in ConcurrentHashMap. may be a little
// slower, but better to pay a price on first write rather than all reads.
e = new VariableTableEntry(hash, internedName, value, table[index]);
table[index] = e;
variableTableSize = potentialNewSize;
variableTable = table; // write-volatile
} finally {
lock.unlock();
}
return value;
}
@Override
protected IRubyObject variableTableRemove(String name) {
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
VariableTableEntry[] table;
if ((table = variableTable) != null) {
int hash = name.hashCode();
int index = hash & (table.length - 1);
VariableTableEntry first = table[index];
VariableTableEntry e;
for (e = first; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
IRubyObject oldValue = e.value;
// All entries following removed node can stay
// in list, but all preceding ones need to be
// cloned.
VariableTableEntry newFirst = e.next;
for (VariableTableEntry p = first; p != e; p = p.next) {
newFirst = new VariableTableEntry(p.hash, p.name, p.value, newFirst);
}
table[index] = newFirst;
variableTableSize--;
variableTable = table; // write-volatile
return oldValue;
}
}
}
} finally {
lock.unlock();
}
return null;
}
@Override
protected IRubyObject variableTableReadLocked(VariableTableEntry entry) {
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
return entry.value;
} finally {
lock.unlock();
}
}
@Override
protected void variableTableSync(List<Variable<IRubyObject>> vars) {
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
variableTableSize = 0;
variableTableThreshold = (int)(VARIABLE_TABLE_DEFAULT_CAPACITY * VARIABLE_TABLE_LOAD_FACTOR);
variableTable = new VariableTableEntry[VARIABLE_TABLE_DEFAULT_CAPACITY];
for (Variable<IRubyObject> var : vars) {
assert !var.isConstant() && var.getValue() != null;
variableTableStore(var.getName(), var.getValue());
}
} finally {
lock.unlock();
}
}
@Override
public void syncVariables(List<Variable<IRubyObject>> variables) {
ArrayList<Variable<IRubyObject>> constants = new ArrayList<Variable<IRubyObject>>(variables.size());
Variable<IRubyObject> var;
for (Iterator<Variable<IRubyObject>> iter = variables.iterator(); iter.hasNext(); ) {
if ((var = iter.next()).isConstant()) {
constants.add(var);
iter.remove();
}
}
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
variableTableSync(variables);
constantTableSync(constants);
} finally {
lock.unlock();
}
}
@Override
@SuppressWarnings("unchecked")
@Deprecated // born deprecated
public Map getVariableMap() {
Map map = variableTableGetMap();
constantTableGetMap(map);
return map;
}
@Override
public boolean hasVariables() {
return variableTableGetSize() > 0 || constantTableGetSize() > 0;
}
@Override
public int getVariableCount() {
return variableTableGetSize() + constantTableGetSize();
}
@Override
public List<Variable<IRubyObject>> getVariableList() {
VariableTableEntry[] vtable = variableTableGetTable();
ConstantTableEntry[] ctable = constantTableGetTable();
ArrayList<Variable<IRubyObject>> list = new ArrayList<Variable<IRubyObject>>();
IRubyObject readValue;
for (int i = vtable.length; --i >= 0; ) {
for (VariableTableEntry e = vtable[i]; e != null; e = e.next) {
if ((readValue = e.value) == null) readValue = variableTableReadLocked(e);
list.add(new VariableEntry<IRubyObject>(e.name, readValue));
}
}
for (int i = ctable.length; --i >= 0; ) {
for (ConstantTableEntry e = ctable[i]; e != null; e = e.next) {
list.add(e);
}
}
return list;
}
@Override
public List<String> getVariableNameList() {
VariableTableEntry[] vtable = variableTableGetTable();
ConstantTableEntry[] ctable = constantTableGetTable();
ArrayList<String> list = new ArrayList<String>();
for (int i = vtable.length; --i >= 0; ) {
for (VariableTableEntry e = vtable[i]; e != null; e = e.next) {
list.add(e.name);
}
}
for (int i = ctable.length; --i >= 0; ) {
for (ConstantTableEntry e = ctable[i]; e != null; e = e.next) {
list.add(e.name);
}
}
return list;
}
//
////////////////// CONSTANT TABLE METHODS, ETC. ////////////////
//
protected static final int CONSTANT_TABLE_DEFAULT_CAPACITY = 8; // MUST be power of 2!
protected static final int CONSTANT_TABLE_MAXIMUM_CAPACITY = 1 << 30;
protected static final float CONSTANT_TABLE_LOAD_FACTOR = 0.75f;
protected static final class ConstantTableEntry implements Variable<IRubyObject> {
final int hash;
final String name;
final IRubyObject value;
final ConstantTableEntry next;
// constant table entry values are final; if a constant is redefined, the
// entry will be removed and replaced with a new entry.
ConstantTableEntry(
int hash,
String name,
IRubyObject value,
ConstantTableEntry next) {
this.hash = hash;
this.name = name;
this.value = value;
this.next = next;
}
public String getName() {
return name;
}
public IRubyObject getValue() {
return value;
}
public final boolean isClassVariable() {
return false;
}
public final boolean isConstant() {
return true;
}
public final boolean isInstanceVariable() {
return false;
}
public final boolean isRubyVariable() {
return true;
}
}
protected boolean constantTableContains(String name) {
int hash = name.hashCode();
ConstantTableEntry[] table;
for (ConstantTableEntry e = (table = constantTable)[hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
return true;
}
}
return false;
}
protected boolean constantTableFastContains(String internedName) {
ConstantTableEntry[] table;
for (ConstantTableEntry e = (table = constantTable)[internedName.hashCode() & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
return true;
}
}
return false;
}
protected IRubyObject constantTableFetch(String name) {
int hash = name.hashCode();
ConstantTableEntry[] table;
for (ConstantTableEntry e = (table = constantTable)[hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
return e.value;
}
}
return null;
}
protected IRubyObject constantTableFastFetch(String internedName) {
ConstantTableEntry[] table;
for (ConstantTableEntry e = (table = constantTable)[internedName.hashCode() & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
return e.value;
}
}
return null;
}
protected IRubyObject constantTableStore(String name, IRubyObject value) {
int hash = name.hashCode();
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
ConstantTableEntry[] table;
ConstantTableEntry e;
ConstantTableEntry first;
int potentialNewSize;
if ((potentialNewSize = constantTableSize + 1) > constantTableThreshold) {
table = constantTableRehash();
} else {
table = constantTable;
}
int index;
for (e = first = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
// if value is unchanged, do nothing
if (value == e.value) {
return value;
}
// create new entry, prepend to any trailing entries
ConstantTableEntry newFirst = new ConstantTableEntry(e.hash, e.name, value, e.next);
// all entries before this one must be cloned
for (ConstantTableEntry n = first; n != e; n = n.next) {
newFirst = new ConstantTableEntry(n.hash, n.name, n.value, newFirst);
}
table[index] = newFirst;
constantTable = table; // write-volatile
return value;
}
}
table[index] = new ConstantTableEntry(hash, name.intern(), value, table[index]);
constantTableSize = potentialNewSize;
constantTable = table; // write-volatile
} finally {
lock.unlock();
}
return value;
}
protected IRubyObject constantTableFastStore(String internedName, IRubyObject value) {
assert internedName == internedName.intern() : internedName + " not interned";
int hash = internedName.hashCode();
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
ConstantTableEntry[] table;
ConstantTableEntry e;
ConstantTableEntry first;
int potentialNewSize;
if ((potentialNewSize = constantTableSize + 1) > constantTableThreshold) {
table = constantTableRehash();
} else {
table = constantTable;
}
int index;
for (e = first = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
// if value is unchanged, do nothing
if (value == e.value) {
return value;
}
// create new entry, prepend to any trailing entries
ConstantTableEntry newFirst = new ConstantTableEntry(e.hash, e.name, value, e.next);
// all entries before this one must be cloned
for (ConstantTableEntry n = first; n != e; n = n.next) {
newFirst = new ConstantTableEntry(n.hash, n.name, n.value, newFirst);
}
table[index] = newFirst;
constantTable = table; // write-volatile
return value;
}
}
table[index] = new ConstantTableEntry(hash, internedName, value, table[index]);
constantTableSize = potentialNewSize;
constantTable = table; // write-volatile
} finally {
lock.unlock();
}
return value;
}
protected IRubyObject constantTableRemove(String name) {
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
ConstantTableEntry[] table;
if ((table = constantTable) != null) {
int hash = name.hashCode();
int index = hash & (table.length - 1);
ConstantTableEntry first = table[index];
ConstantTableEntry e;
for (e = first; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
IRubyObject oldValue = e.value;
// All entries following removed node can stay
// in list, but all preceding ones need to be
// cloned.
ConstantTableEntry newFirst = e.next;
for (ConstantTableEntry p = first; p != e; p = p.next) {
newFirst = new ConstantTableEntry(p.hash, p.name, p.value, newFirst);
}
table[index] = newFirst;
constantTableSize--;
constantTable = table; // write-volatile
return oldValue;
}
}
}
} finally {
lock.unlock();
}
return null;
}
protected ConstantTableEntry[] constantTableGetTable() {
return constantTable;
}
protected int constantTableGetSize() {
if (constantTable != null) {
return constantTableSize;
}
return 0;
}
protected void constantTableSync(List<Variable<IRubyObject>> vars) {
ReentrantLock lock;
(lock = variableWriteLock).lock();
try {
constantTableSize = 0;
constantTableThreshold = (int)(CONSTANT_TABLE_DEFAULT_CAPACITY * CONSTANT_TABLE_LOAD_FACTOR);
constantTable = new ConstantTableEntry[CONSTANT_TABLE_DEFAULT_CAPACITY];
for (Variable<IRubyObject> var : vars) {
assert var.isConstant() && var.getValue() != null;
constantTableStore(var.getName(), var.getValue());
}
} finally {
lock.unlock();
}
}
// MUST be called from synchronized/locked block!
// should only be called by constantTableStore/constantTableFastStore
private final ConstantTableEntry[] constantTableRehash() {
ConstantTableEntry[] oldTable = constantTable;
int oldCapacity;
if ((oldCapacity = oldTable.length) >= CONSTANT_TABLE_MAXIMUM_CAPACITY) {
return oldTable;
}
int newCapacity = oldCapacity << 1;
ConstantTableEntry[] newTable = new ConstantTableEntry[newCapacity];
constantTableThreshold = (int)(newCapacity * CONSTANT_TABLE_LOAD_FACTOR);
int sizeMask = newCapacity - 1;
ConstantTableEntry e;
for (int i = oldCapacity; --i >= 0; ) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
e = oldTable[i];
if (e != null) {
ConstantTableEntry next = e.next;
int idx = e.hash & sizeMask;
// Single node on list
if (next == null)
newTable[idx] = e;
else {
// Reuse trailing consecutive sequence at same slot
ConstantTableEntry lastRun = e;
int lastIdx = idx;
for (ConstantTableEntry last = next;
last != null;
last = last.next) {
int k = last.hash & sizeMask;
if (k != lastIdx) {
lastIdx = k;
lastRun = last;
}
}
newTable[lastIdx] = lastRun;
// Clone all remaining nodes
for (ConstantTableEntry p = e; p != lastRun; p = p.next) {
int k = p.hash & sizeMask;
ConstantTableEntry m = new ConstantTableEntry(p.hash, p.name, p.value, newTable[k]);
newTable[k] = m;
}
}
}
}
constantTable = newTable;
return newTable;
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
protected Map constantTableGetMap() {
HashMap map = new HashMap();
ConstantTableEntry[] table;
if ((table = constantTable) != null) {
for (int i = table.length; --i >= 0; ) {
for (ConstantTableEntry e = table[i]; e != null; e = e.next) {
map.put(e.name, e.value);
}
}
}
return map;
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
protected Map constantTableGetMap(Map map) {
ConstantTableEntry[] table;
if ((table = constantTable) != null) {
for (int i = table.length; --i >= 0; ) {
for (ConstantTableEntry e = table[i]; e != null; e = e.next) {
map.put(e.name, e.value);
}
}
}
return map;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Anders Bengtsson <ndrsbngtssn@yahoo.se>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.runtime.Visibility.PROTECTED;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.exceptions.JumpException;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.Sprintf;
/**
* @author Anders Bengtsson
*/
@JRubyClass(name="NameError", parent="StandardError")
public class RubyNameError extends RubyException {
private IRubyObject name;
/**
* Nested class whose instances act as thunks reacting to to_str method
* called from (Exception#to_str, Exception#message)
* MRI equivalent: rb_cNameErrorMesg, class name: "message", construction method: "!",
* to_str implementation: "name_err_mesg_to_str"
*
* TODO: this class should not be lookupable
*/
@JRubyClass(name = "NameError::Message", parent = "Object")
public static final class RubyNameErrorMessage extends RubyObject {
static ObjectAllocator NAMEERRORMESSAGE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
IRubyObject dummy = new RubyObject(runtime, runtime.getObject());
return new RubyNameErrorMessage(runtime, dummy, dummy, Visibility.PRIVATE, CallType.VARIABLE);
}
};
private final IRubyObject object;
private final IRubyObject method;
private final Visibility visibility;
private final CallType callType;
RubyNameErrorMessage(Ruby runtime, IRubyObject object, IRubyObject method, Visibility visibility, CallType callType) {
super(runtime, runtime.getNameErrorMessage(), false);
this.object = object;
this.method = method;
this.visibility = visibility;
this.callType = callType;
}
@JRubyMethod(name = "_load", meta = true)
public static IRubyObject load(IRubyObject recv, IRubyObject arg) {
return arg;
}
@JRubyMethod(name = "_dump")
public IRubyObject dump(ThreadContext context, IRubyObject arg) {
return to_str(context);
}
@JRubyMethod(name = "to_str")
public IRubyObject to_str(ThreadContext context) {
String format = null;
if (visibility == PRIVATE) {
format = "private method `%s' called for %s";
} else if (visibility == PROTECTED) {
format = "protected method `%s' called for %s";
} else if (callType == CallType.VARIABLE) {
format = "undefined local variable or method `%s' for %s";
} else if (callType == CallType.SUPER) {
format = "super: no superclass method `%s'";
}
if (format == null) format = "undefined method `%s' for %s";
String description = null;
if (object.isNil()) {
description = "nil";
} else if (object instanceof RubyBoolean && object.isTrue()) {
description = "true";
} else if (object instanceof RubyBoolean && !object.isTrue()) {
description = "false";
} else {
try {
description = RubyObject.inspect(context, object).toString();
} catch(JumpException e) {}
if (description == null || description.length() > 65) description = object.anyToString().toString();
}
if (description.length() == 0 || (description.length() > 0 && description.charAt(0) != '#')) {
description = description + ":" + object.getMetaClass().getRealClass().getName();
}
Ruby runtime = getRuntime();
RubyArray arr = runtime.newArray(method, runtime.newString(description));
RubyString msg = runtime.newString(Sprintf.sprintf(runtime.newString(format), arr).toString());
if (object.isTaint()) msg.setTaint(true);
return msg;
}
}
private static ObjectAllocator NAMEERROR_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyNameError(runtime, klass);
}
};
public static RubyClass createNameErrorClass(Ruby runtime, RubyClass standardErrorClass) {
RubyClass nameErrorClass = runtime.defineClass("NameError", standardErrorClass, NAMEERROR_ALLOCATOR);
nameErrorClass.defineAnnotatedMethods(RubyNameError.class);
return nameErrorClass;
}
public static RubyClass createNameErrorMessageClass(Ruby runtime, RubyClass nameErrorClass) {
RubyClass messageClass = nameErrorClass.defineClassUnder("Message", runtime.getObject(), RubyNameErrorMessage.NAMEERRORMESSAGE_ALLOCATOR);
messageClass.defineAnnotatedMethods(RubyNameErrorMessage.class);
return messageClass;
}
protected RubyNameError(Ruby runtime, RubyClass exceptionClass) {
this(runtime, exceptionClass, exceptionClass.getName());
}
public RubyNameError(Ruby runtime, RubyClass exceptionClass, String message) {
this(runtime, exceptionClass, message, null);
}
public RubyNameError(Ruby runtime, RubyClass exceptionClass, String message, String name) {
super(runtime, exceptionClass, message);
this.name = name == null ? runtime.getNil() : runtime.newString(name);
}
@JRubyMethod(name = "exception", rest = true, meta = true)
public static RubyException newRubyNameError(IRubyObject recv, IRubyObject[] args) {
RubyClass klass = (RubyClass)recv;
RubyException newError = (RubyException) klass.allocate();
newError.callInit(args, Block.NULL_BLOCK);
return newError;
}
@JRubyMethod(name = "initialize", optional = 2, frame = true)
@Override
public IRubyObject initialize(IRubyObject[] args, Block block) {
if (args.length > 1) {
name = args[args.length - 1];
int newLength = args.length > 2 ? args.length - 2 : args.length - 1;
IRubyObject []tmpArgs = new IRubyObject[newLength];
System.arraycopy(args, 0, tmpArgs, 0, newLength);
args = tmpArgs;
} else {
name = getRuntime().getNil();
}
super.initialize(args, block);
return this;
}
@JRubyMethod(name = "to_s")
@Override
public IRubyObject to_s() {
if (message.isNil()) return getRuntime().newString(message.getMetaClass().getName());
RubyString str = message.convertToString();
if (str != message) message = str;
if (isTaint()) message.setTaint(true);
return message;
}
@JRubyMethod(name = "name")
public IRubyObject name() {
return name;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* @author jpetersen
*/
@JRubyClass(name="NilClass")
public class RubyNil extends RubyObject {
public RubyNil(Ruby runtime) {
super(runtime, runtime.getNilClass(), false);
flags |= NIL_F | FALSE_F;
}
public static final ObjectAllocator NIL_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return runtime.getNil();
}
};
public static RubyClass createNilClass(Ruby runtime) {
RubyClass nilClass = runtime.defineClass("NilClass", runtime.getObject(), NIL_ALLOCATOR);
runtime.setNilClass(nilClass);
nilClass.index = ClassIndex.NIL;
nilClass.defineAnnotatedMethods(RubyNil.class);
nilClass.getMetaClass().undefineMethod("new");
// FIXME: This is causing a verification error for some reason
//nilClass.dispatcher = callbackFactory.createDispatcher(nilClass);
return nilClass;
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.NIL;
}
@Override
public boolean isImmediate() {
return true;
}
@Override
public RubyClass getSingletonClass() {
return metaClass;
}
@Override
public Class<?> getJavaClass() {
return void.class;
}
// Methods of the Nil Class (nil_*):
/** nil_to_i
*
*/
@JRubyMethod(name = "to_i")
public static RubyFixnum to_i(IRubyObject recv) {
return RubyFixnum.zero(recv.getRuntime());
}
/**
* nil_to_f
*
*/
@JRubyMethod(name = "to_f")
public static RubyFloat to_f(IRubyObject recv) {
return RubyFloat.newFloat(recv.getRuntime(), 0.0D);
}
/** nil_to_s
*
*/
@JRubyMethod(name = "to_s")
public static RubyString to_s(IRubyObject recv) {
return RubyString.newEmptyString(recv.getRuntime());
}
/** nil_to_a
*
*/
@JRubyMethod(name = "to_a")
public static RubyArray to_a(IRubyObject recv) {
return recv.getRuntime().newEmptyArray();
}
/** nil_inspect
*
*/
@JRubyMethod(name = "inspect")
public static RubyString inspect(IRubyObject recv) {
return recv.getRuntime().newString("nil");
}
/** nil_type
*
*/
@JRubyMethod(name = "type")
public static RubyClass type(IRubyObject recv) {
return recv.getRuntime().getNilClass();
}
/** nil_and
*
*/
@JRubyMethod(name = "&", required = 1)
public static RubyBoolean op_and(IRubyObject recv, IRubyObject obj) {
return recv.getRuntime().getFalse();
}
/** nil_or
*
*/
@JRubyMethod(name = "|", required = 1)
public static RubyBoolean op_or(IRubyObject recv, IRubyObject obj) {
return recv.getRuntime().newBoolean(obj.isTrue());
}
/** nil_xor
*
*/
@JRubyMethod(name = "^", required = 1)
public static RubyBoolean op_xor(IRubyObject recv, IRubyObject obj) {
return recv.getRuntime().newBoolean(obj.isTrue());
}
@JRubyMethod(name = "nil?")
public IRubyObject nil_p() {
return getRuntime().getTrue();
}
@Override
public RubyFixnum id() {
return getRuntime().newFixnum(4);
}
@Override
public IRubyObject taint(ThreadContext context) {
return this;
}
@Override
public IRubyObject freeze(ThreadContext context) {
return this;
}
/** nilclass_to_c
*
*/
@JRubyMethod(name = "to_c", compat = CompatVersion.RUBY1_9)
public static IRubyObject to_c(ThreadContext context, IRubyObject recv) {
return RubyComplex.newComplexCanonicalize(context, RubyFixnum.zero(context.getRuntime()));
}
/** nilclass_to_r
*
*/
@JRubyMethod(name = "to_r", compat = CompatVersion.RUBY1_9)
public static IRubyObject to_r(ThreadContext context, IRubyObject recv) {
return RubyRational.newRationalCanonicalize(context, RubyFixnum.zero(context.getRuntime()));
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Koichiro Ohba <koichiro@meadowy.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.UnsupportedCharsetException;
import java.util.HashMap;
import java.util.Map;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.KCode;
@JRubyModule(name="NKF")
public class RubyNKF {
public static final NKFCharset AUTO = new NKFCharset(0, "x-JISAutoDetect");
public static final NKFCharset JIS = new NKFCharset(1, "iso-2022-jp");
public static final NKFCharset EUC = new NKFCharset(2, "EUC-JP");
public static final NKFCharset SJIS = new NKFCharset(3, "Windows-31J");
public static final NKFCharset BINARY = new NKFCharset(4, null);
public static final NKFCharset NOCONV = new NKFCharset(4, null);
public static final NKFCharset UNKNOWN = new NKFCharset(0, null);
public static final NKFCharset ASCII = new NKFCharset(5, "iso-8859-1");
public static final NKFCharset UTF8 = new NKFCharset(6, "UTF-8");
public static final NKFCharset UTF16 = new NKFCharset(8, "UTF-16");
public static final NKFCharset UTF32 = new NKFCharset(12, "UTF-32");
public static final NKFCharset OTHER = new NKFCharset(16, null);
public static class NKFCharset {
private final int value;
private final String charset;
public NKFCharset(int v, String c) {
value = v;
charset = c;
}
public int getValue() {
return value;
}
public String getCharset() {
return charset;
}
}
public static void createNKF(Ruby runtime) {
RubyModule nkfModule = runtime.defineModule("NKF");
nkfModule.defineConstant("AUTO", RubyFixnum.newFixnum(runtime, AUTO.getValue()));
nkfModule.defineConstant("JIS", RubyFixnum.newFixnum(runtime, JIS.getValue()));
nkfModule.defineConstant("EUC", RubyFixnum.newFixnum(runtime, EUC.getValue()));
nkfModule.defineConstant("SJIS", RubyFixnum.newFixnum(runtime, SJIS.getValue()));
nkfModule.defineConstant("BINARY", RubyFixnum.newFixnum(runtime, BINARY.getValue()));
nkfModule.defineConstant("NOCONV", RubyFixnum.newFixnum(runtime, NOCONV.getValue()));
nkfModule.defineConstant("UNKNOWN", RubyFixnum.newFixnum(runtime, UNKNOWN.getValue()));
nkfModule.defineConstant("ASCII", RubyFixnum.newFixnum(runtime, ASCII.getValue()));
nkfModule.defineConstant("UTF8", RubyFixnum.newFixnum(runtime, UTF8.getValue()));
nkfModule.defineConstant("UTF16", RubyFixnum.newFixnum(runtime, UTF16.getValue()));
nkfModule.defineConstant("UTF32", RubyFixnum.newFixnum(runtime, UTF32.getValue()));
nkfModule.defineConstant("OTHER", RubyFixnum.newFixnum(runtime, OTHER.getValue()));
RubyString version = runtime.newString("2.0.7 (JRuby 2007-05-11)");
RubyString nkfVersion = runtime.newString("2.0.7");
RubyString nkfDate = runtime.newString("2007-05-11");
ThreadContext context = runtime.getCurrentContext();
version.freeze(context);
nkfVersion.freeze(context);
nkfDate.freeze(context);
nkfModule.defineAnnotatedMethods(RubyNKF.class);
}
@JRubyMethod(name = "guess", required = 1, module = true)
public static IRubyObject guess(ThreadContext context, IRubyObject recv, IRubyObject s) {
Ruby runtime = context.getRuntime();
if (!s.respondsTo("to_str")) {
throw runtime.newTypeError("can't convert " + s.getMetaClass() + " into String");
}
ByteList bytes = s.convertToString().getByteList();
ByteBuffer buf = ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin(), bytes.length());
CharsetDecoder decoder = Charset.forName("x-JISAutoDetect").newDecoder();
try {
decoder.decode(buf);
} catch (CharacterCodingException e) {
return runtime.newFixnum(UNKNOWN.getValue());
}
if (!decoder.isCharsetDetected()) {
return runtime.newFixnum(UNKNOWN.getValue());
}
Charset charset = decoder.detectedCharset();
String name = charset.name();
// System.out.println("detect: " + name + "\n");
if ("Shift_JIS".equals(name))
return runtime.newFixnum(SJIS.getValue());
if ("windows-31j".equals(name))
return runtime.newFixnum(SJIS.getValue());
else if ("EUC-JP".equals(name))
return runtime.newFixnum(EUC.getValue());
else if ("ISO-2022-JP".equals(name))
return runtime.newFixnum(JIS.getValue());
else
return runtime.newFixnum(UNKNOWN.getValue());
}
@JRubyMethod(name = "guess1", required = 1, module = true)
public static IRubyObject guess1(ThreadContext context, IRubyObject recv, IRubyObject str) {
return guess(context, recv, str);
}
@JRubyMethod(name = "guess2", required = 1, module = true)
public static IRubyObject guess2(ThreadContext context, IRubyObject recv, IRubyObject str) {
return guess(context, recv, str);
}
@JRubyMethod(name = "nkf", required = 2, module = true)
public static IRubyObject nkf(ThreadContext context, IRubyObject recv, IRubyObject opt, IRubyObject str) {
Ruby runtime = context.getRuntime();
if (!opt.respondsTo("to_str")) {
throw runtime.newTypeError("can't convert " + opt.getMetaClass() + " into String");
}
if (!str.respondsTo("to_str")) {
throw runtime.newTypeError("can't convert " + str.getMetaClass() + " into String");
}
Map<String, NKFCharset> options = parseOpt(opt.convertToString().toString());
NKFCharset nc = options.get("input");
if (nc.getValue() == AUTO.getValue()) {
KCode kcode = runtime.getKCode();
if (kcode == KCode.SJIS) {
nc = SJIS;
} else if (kcode == KCode.EUC) {
nc = EUC;
} else if (kcode == KCode.UTF8) {
nc = UTF8;
}
}
String decodeCharset = nc.getCharset();
String encodeCharset = options.get("output").getCharset();
return convert(context, decodeCharset, encodeCharset, str);
}
private static IRubyObject convert(ThreadContext context, String decodeCharset,
String encodeCharset, IRubyObject str) {
Ruby runtime = context.getRuntime();
CharsetDecoder decoder;
CharsetEncoder encoder;
try {
decoder = Charset.forName(decodeCharset).newDecoder();
encoder = Charset.forName(encodeCharset).newEncoder();
} catch (UnsupportedCharsetException e) {
throw runtime.newArgumentError("invalid encoding");
}
ByteList bytes = str.convertToString().getByteList();
ByteBuffer buf = ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin(), bytes.length());
try {
CharBuffer cbuf = decoder.decode(buf);
buf = encoder.encode(cbuf);
} catch (CharacterCodingException e) {
throw runtime.newArgumentError("invalid encoding");
}
byte[] arr = buf.array();
return runtime.newString(new ByteList(arr, 0, buf.limit()));
}
private static int optionUTF(String s, int i) {
int n = 8;
if (i+1 < s.length() && Character.isDigit(s.charAt(i+1))) {
n = Character.digit(s.charAt(i+1), 10);
if (i+2 < s.length() && Character.isDigit(s.charAt(i+2))) {
n *= 10;
n += Character.digit(s.charAt(i+2), 10);
}
}
return n;
}
private static Map<String, NKFCharset> parseOpt(String s) {
Map<String, NKFCharset> options = new HashMap<String, NKFCharset>();
// default options
options.put("input", AUTO);
options.put("output", JIS);
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'b':
break;
case 'u':
break;
case 'j': // iso-2022-jp
options.put("output", JIS);
break;
case 's': // Shift_JIS
options.put("output", SJIS);
break;
case 'e': // EUC-JP
options.put("output", EUC);
break;
case 'w': // UTF-8
{
int n = optionUTF(s, i);
if (n == 32)
options.put("output", UTF32);
else if (n == 16)
options.put("output", UTF16);
else
options.put("output", UTF8);
}
break;
case 'J': // iso-2022-jp
options.put("input", JIS);
break;
case 'S': // Shift_JIS
options.put("input", SJIS);
break;
case 'E': // EUC-JP
options.put("input", EUC);
break;
case 'W': // UTF-8
{
int n = optionUTF(s, i);
if (n == 32)
options.put("input", UTF32);
else if (n == 16)
options.put("input", UTF16);
else
options.put("input", UTF8);
}
break;
case 't':
break;
case 'r':
break;
case 'h':
break;
case 'm':
break;
case 'M':
break;
case 'l':
break;
case 'f':
break;
case 'F':
break;
case 'Z':
break;
case 'X':
break;
case 'x':
break;
case 'B':
break;
case 'T':
break;
case 'd':
break;
case 'c':
break;
case 'I':
break;
case 'L':
break;
case '-':
if (s.charAt(i+1) == '-') {
// long name option
}
default:
}
}
return options;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyClass(name="NoMethodError", parent="NameError")
public class RubyNoMethodError extends RubyNameError {
private IRubyObject args;
private static final ObjectAllocator NOMETHODERROR_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyNoMethodError(runtime, klass);
}
};
public static RubyClass createNoMethodErrorClass(Ruby runtime, RubyClass nameErrorClass) {
RubyClass noMethodErrorClass = runtime.defineClass("NoMethodError", nameErrorClass, NOMETHODERROR_ALLOCATOR);
noMethodErrorClass.defineAnnotatedMethods(RubyNoMethodError.class);
return noMethodErrorClass;
}
protected RubyNoMethodError(Ruby runtime, RubyClass exceptionClass) {
super(runtime, exceptionClass, exceptionClass.getName());
this.args = runtime.getNil();
}
public RubyNoMethodError(Ruby runtime, RubyClass exceptionClass, String message, String name, IRubyObject args) {
super(runtime, exceptionClass, message, name);
this.args = args;
}
@JRubyMethod(name = "initialize", optional = 3, frame = true)
public IRubyObject initialize(IRubyObject[] args, Block block) {
if (args.length > 2) {
this.args = args[args.length - 1];
IRubyObject []tmpArgs = new IRubyObject[args.length - 1];
System.arraycopy(args, 0, tmpArgs, 0, tmpArgs.length);
args = tmpArgs;
} else {
this.args = getRuntime().getNil();
}
super.initialize(args, block);
return this;
}
@JRubyMethod(name = "args")
public IRubyObject args() {
return args;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2006 Antti Karanta <Antti.Karanta@napa.fi>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.util.Numeric.f_abs;
import static org.jruby.util.Numeric.f_arg;
import static org.jruby.util.Numeric.f_negative_p;
import java.math.BigInteger;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Block;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.Convert;
/**
* Base class for all numerical types in ruby.
*/
// TODO: Numeric.new works in Ruby and it does here too. However trying to use
// that instance in a numeric operation should generate an ArgumentError. Doing
// this seems so pathological I do not see the need to fix this now.
@JRubyClass(name="Numeric", include="Comparable")
public class RubyNumeric extends RubyObject {
public static RubyClass createNumericClass(Ruby runtime) {
RubyClass numeric = runtime.defineClass("Numeric", runtime.getObject(), NUMERIC_ALLOCATOR);
runtime.setNumeric(numeric);
numeric.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyNumeric;
}
};
numeric.includeModule(runtime.getComparable());
numeric.defineAnnotatedMethods(RubyNumeric.class);
return numeric;
}
protected static final ObjectAllocator NUMERIC_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyNumeric(runtime, klass);
}
};
public static double DBL_EPSILON=2.2204460492503131e-16;
private static IRubyObject convertToNum(double val, Ruby runtime) {
if (val >= (double) RubyFixnum.MAX || val < (double) RubyFixnum.MIN) {
return RubyBignum.newBignum(runtime, val);
}
return RubyFixnum.newFixnum(runtime, (long) val);
}
public RubyNumeric(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
public RubyNumeric(Ruby runtime, RubyClass metaClass, boolean useObjectSpace) {
super(runtime, metaClass, useObjectSpace);
}
// The implementations of these are all bonus (see TODO above) I was going
// to throw an error from these, but it appears to be the wrong place to
// do it.
public double getDoubleValue() {
return 0;
}
public long getLongValue() {
return 0;
}
public static RubyNumeric newNumeric(Ruby runtime) {
return new RubyNumeric(runtime, runtime.getNumeric());
}
/* ================
* Utility Methods
* ================
*/
/** rb_num2int, NUM2INT
*
*/
public static int num2int(IRubyObject arg) {
long num = num2long(arg);
checkInt(arg, num);
return (int)num;
}
/** check_int
*
*/
public static void checkInt(IRubyObject arg, long num){
String s;
if (num < Integer.MIN_VALUE) {
s = "small";
} else if (num > Integer.MAX_VALUE) {
s = "big";
} else {
return;
}
throw arg.getRuntime().newRangeError("integer " + num + " too " + s + " to convert to `int'");
}
/**
* NUM2CHR
*/
public static byte num2chr(IRubyObject arg) {
if (arg instanceof RubyString) {
String value = ((RubyString) arg).toString();
if (value != null && value.length() > 0) return (byte) value.charAt(0);
}
return (byte) num2int(arg);
}
/** rb_num2long and FIX2LONG (numeric.c)
*
*/
public static long num2long(IRubyObject arg) {
if (arg instanceof RubyFixnum) {
return ((RubyFixnum) arg).getLongValue();
}
if (arg.isNil()) {
throw arg.getRuntime().newTypeError("no implicit conversion from nil to integer");
}
if (arg instanceof RubyFloat) {
double aFloat = ((RubyFloat) arg).getDoubleValue();
if (aFloat <= (double) Long.MAX_VALUE && aFloat >= (double) Long.MIN_VALUE) {
return (long) aFloat;
} else {
// TODO: number formatting here, MRI uses "%-.10g", 1.4 API is a must?
throw arg.getRuntime().newRangeError("float " + aFloat + " out of range of integer");
}
} else if (arg instanceof RubyBignum) {
return RubyBignum.big2long((RubyBignum) arg);
}
return arg.convertToInteger().getLongValue();
}
/** rb_dbl2big + LONG2FIX at once (numeric.c)
*
*/
public static IRubyObject dbl2num(Ruby runtime, double val) {
if (Double.isInfinite(val)) {
throw runtime.newFloatDomainError(val < 0 ? "-Infinity" : "Infinity");
}
if (Double.isNaN(val)) {
throw runtime.newFloatDomainError("NaN");
}
return convertToNum(val,runtime);
}
/** rb_num2dbl and NUM2DBL
*
*/
public static double num2dbl(IRubyObject arg) {
if (arg instanceof RubyFloat) {
return ((RubyFloat) arg).getDoubleValue();
} else if (arg instanceof RubyString) {
throw arg.getRuntime().newTypeError("no implicit conversion to float from string");
} else if (arg == arg.getRuntime().getNil()) {
throw arg.getRuntime().newTypeError("no implicit conversion to float from nil");
}
return arg.convertToFloat().getDoubleValue();
}
/** rb_dbl_cmp (numeric.c)
*
*/
public static IRubyObject dbl_cmp(Ruby runtime, double a, double b) {
if (Double.isNaN(a) || Double.isNaN(b)) {
return runtime.getNil();
}
if (a > b) {
return RubyFixnum.one(runtime);
}
if (a < b) {
return RubyFixnum.minus_one(runtime);
}
return RubyFixnum.zero(runtime);
}
public static long fix2long(IRubyObject arg) {
return ((RubyFixnum) arg).getLongValue();
}
public static int fix2int(IRubyObject arg) {
long num = arg instanceof RubyFixnum ? fix2long(arg) : num2long(arg);
checkInt(arg, num);
return (int) num;
}
public static RubyInteger str2inum(Ruby runtime, RubyString str, int base) {
return str2inum(runtime,str,base,false);
}
public static RubyNumeric int2fix(Ruby runtime, long val) {
return RubyFixnum.newFixnum(runtime,val);
}
/** rb_num2fix
*
*/
public static IRubyObject num2fix(IRubyObject val) {
if (val instanceof RubyFixnum) {
return val;
}
if (val instanceof RubyBignum) {
// any BigInteger is bigger than Fixnum and we don't have FIXABLE
throw val.getRuntime().newRangeError("integer " + val + " out of range of fixnum");
}
return RubyFixnum.newFixnum(val.getRuntime(), num2long(val));
}
/**
* Converts a string representation of an integer to the integer value.
* Parsing starts at the beginning of the string (after leading and
* trailing whitespace have been removed), and stops at the end or at the
* first character that can't be part of an integer. Leading signs are
* allowed. If <code>base</code> is zero, strings that begin with '0[xX]',
* '0[bB]', or '0' (optionally preceded by a sign) will be treated as hex,
* binary, or octal numbers, respectively. If a non-zero base is given,
* only the prefix (if any) that is appropriate to that base will be
* parsed correctly. For example, if the base is zero or 16, the string
* "0xff" will be converted to 256, but if the base is 10, it will come out
* as zero, since 'x' is not a valid decimal digit. If the string fails
* to parse as a number, zero is returned.
*
* @param runtime the ruby runtime
* @param str the string to be converted
* @param base the expected base of the number (for example, 2, 8, 10, 16),
* or 0 if the method should determine the base automatically
* (defaults to 10). Values 0 and 2-36 are permitted. Any other
* value will result in an ArgumentError.
* @param strict if true, enforce the strict criteria for String encoding of
* numeric values, as required by Integer('n'), and raise an
* exception when those criteria are not met. Otherwise, allow
* lax expression of values, as permitted by String#to_i, and
* return a value in almost all cases (excepting illegal radix).
* TODO: describe the rules/criteria
* @return a RubyFixnum or (if necessary) a RubyBignum representing
* the result of the conversion, which will be zero if the
* conversion failed.
*/
public static RubyInteger str2inum(Ruby runtime, RubyString str, int base, boolean strict) {
if (base != 0 && (base < 2 || base > 36)) {
throw runtime.newArgumentError("illegal radix " + base);
}
ByteList bytes = str.getByteList();
try {
return runtime.newFixnum(Convert.byteListToLong(bytes, base, strict));
} catch (InvalidIntegerException e) {
return str2inumIIE(strict, runtime, str);
} catch (NumberTooLargeException e) {
return str2inumNTLE(strict, runtime, str, bytes, base);
}
}
private static RubyInteger str2inumIIE(boolean strict, Ruby runtime, RubyString str) throws RaiseException {
if (strict) {
throw runtime.newArgumentError("invalid value for Integer: " + str.callMethod(runtime.getCurrentContext(), "inspect").toString());
}
return RubyFixnum.zero(runtime);
}
private static RubyInteger str2inumNTLE(boolean strict, Ruby runtime, RubyString str, ByteList bytes, int base) {
try {
BigInteger bi = Convert.byteListToBigInteger(bytes, base, strict);
return new RubyBignum(runtime, bi);
} catch (InvalidIntegerException e2) {
return str2inumIIE(strict, runtime, str);
}
}
public static RubyFloat str2fnum(Ruby runtime, RubyString arg) {
return str2fnum(runtime,arg,false);
}
/**
* Converts a string representation of a floating-point number to the
* numeric value. Parsing starts at the beginning of the string (after
* leading and trailing whitespace have been removed), and stops at the
* end or at the first character that can't be part of a number. If
* the string fails to parse as a number, 0.0 is returned.
*
* @param runtime the ruby runtime
* @param arg the string to be converted
* @param strict if true, enforce the strict criteria for String encoding of
* numeric values, as required by Float('n'), and raise an
* exception when those criteria are not met. Otherwise, allow
* lax expression of values, as permitted by String#to_f, and
* return a value in all cases.
* TODO: describe the rules/criteria
* @return a RubyFloat representing the result of the conversion, which
* will be 0.0 if the conversion failed.
*/
public static RubyFloat str2fnum(Ruby runtime, RubyString arg, boolean strict) {
final double ZERO = 0.0;
try {
return new RubyFloat(runtime,Convert.byteListToDouble(arg.getByteList(),strict));
} catch (NumberFormatException e) {
if (strict) {
throw runtime.newArgumentError("invalid value for Float(): "
+ arg.callMethod(runtime.getCurrentContext(), "inspect").toString());
}
return new RubyFloat(runtime,ZERO);
}
}
/** Numeric methods. (num_*)
*
*/
protected IRubyObject[] getCoerced(ThreadContext context, IRubyObject other, boolean error) {
IRubyObject result;
try {
result = other.callMethod(context, "coerce", this);
} catch (RaiseException e) {
if (error) {
throw getRuntime().newTypeError(
other.getMetaClass().getName() + " can't be coerced into " + getMetaClass().getName());
}
return null;
}
if (!(result instanceof RubyArray) || ((RubyArray)result).getLength() != 2) {
throw getRuntime().newTypeError("coerce must return [x, y]");
}
return ((RubyArray)result).toJavaArray();
}
protected IRubyObject callCoerced(ThreadContext context, String method, IRubyObject other, boolean err) {
IRubyObject[] args = getCoerced(context, other, err);
if(args == null) {
return getRuntime().getNil();
}
return args[0].callMethod(context, method, args[1]);
}
protected IRubyObject callCoerced(ThreadContext context, String method, IRubyObject other) {
IRubyObject[] args = getCoerced(context, other, false);
if(args == null) {
return getRuntime().getNil();
}
return args[0].callMethod(context, method, args[1]);
}
// beneath are rewritten coercions that reflect MRI logic, the aboves are used only by RubyBigDecimal
/** coerce_body
*
*/
protected final IRubyObject coerceBody(ThreadContext context, IRubyObject other) {
return other.callMethod(context, "coerce", this);
}
/** do_coerce
*
*/
protected final RubyArray doCoerce(ThreadContext context, IRubyObject other, boolean err) {
IRubyObject result;
try {
result = coerceBody(context, other);
} catch (RaiseException e) {
if (err) {
throw getRuntime().newTypeError(
other.getMetaClass().getName() + " can't be coerced into " + getMetaClass().getName());
}
return null;
}
if (!(result instanceof RubyArray) || ((RubyArray) result).getLength() != 2) {
throw getRuntime().newTypeError("coerce must return [x, y]");
}
return (RubyArray) result;
}
/** rb_num_coerce_bin
* coercion taking two arguments
*/
protected final IRubyObject coerceBin(ThreadContext context, String method, IRubyObject other) {
RubyArray ary = doCoerce(context, other, true);
return (ary.eltInternal(0)).callMethod(context, method, ary.eltInternal(1));
}
/** rb_num_coerce_cmp
* coercion used for comparisons
*/
protected final IRubyObject coerceCmp(ThreadContext context, String method, IRubyObject other) {
RubyArray ary = doCoerce(context, other, false);
if (ary == null) {
return getRuntime().getNil(); // MRI does it!
}
return (ary.eltInternal(0)).callMethod(context, method, ary.eltInternal(1));
}
/** rb_num_coerce_relop
* coercion used for relative operators
*/
protected final IRubyObject coerceRelOp(ThreadContext context, String method, IRubyObject other) {
RubyArray ary = doCoerce(context, other, false);
if (ary == null) {
return RubyComparable.cmperr(this, other);
}
return unwrapCoerced(context, method, other, ary);
}
private final IRubyObject unwrapCoerced(ThreadContext context, String method, IRubyObject other, RubyArray ary) {
IRubyObject result = (ary.eltInternal(0)).callMethod(context, method, ary.eltInternal(1));
if (result.isNil()) {
return RubyComparable.cmperr(this, other);
}
return result;
}
public RubyNumeric asNumeric() {
return this;
}
/* ================
* Instance Methods
* ================
*/
/** num_sadded
*
*/
@JRubyMethod(name = "singleton_method_added")
public IRubyObject sadded(IRubyObject name) {
throw getRuntime().newTypeError("can't define singleton method " + name + " for " + getType().getName());
}
/** num_init_copy
*
*/
@Override
@JRubyMethod(name = "initialize_copy", visibility = Visibility.PRIVATE)
public IRubyObject initialize_copy(IRubyObject arg) {
throw getRuntime().newTypeError("can't copy " + getType().getName());
}
/** num_coerce
*
*/
@JRubyMethod(name = "coerce")
public IRubyObject coerce(IRubyObject other) {
if (getClass() == other.getClass()) return getRuntime().newArray(other, this);
IRubyObject cdr = RubyKernel.new_float(this, this);
IRubyObject car = RubyKernel.new_float(this, other);
return getRuntime().newArray(car, cdr);
}
/** num_uplus
*
*/
@JRubyMethod(name = "+@")
public IRubyObject op_uplus() {
return this;
}
/** num_uminus
*
*/
@JRubyMethod(name = "-@")
public IRubyObject op_uminus(ThreadContext context) {
RubyFixnum zero = RubyFixnum.zero(getRuntime());
RubyArray ary = zero.doCoerce(context, this, true);
return ary.eltInternal(0).callMethod(context, MethodIndex.OP_MINUS, "-", ary.eltInternal(1));
}
/** num_cmp
*
*/
@JRubyMethod(name = "<=>")
public IRubyObject op_cmp(IRubyObject other) {
if (this == other) { // won't hurt fixnums
return RubyFixnum.zero(getRuntime());
}
return getRuntime().getNil();
}
/** num_eql
*
*/
@JRubyMethod(name = "eql?")
public IRubyObject eql_p(ThreadContext context, IRubyObject other) {
if (getClass() != other.getClass()) return getRuntime().getFalse();
return equalInternal(context, this, other) ? getRuntime().getTrue() : getRuntime().getFalse();
}
/** num_quo
*
*/
@JRubyMethod(name = "quo")
public IRubyObject quo(ThreadContext context, IRubyObject other) {
return callMethod(context, "/", other);
}
/** num_quo
*
*/
@JRubyMethod(name = "quo", compat = CompatVersion.RUBY1_9)
public IRubyObject quo_19(ThreadContext context, IRubyObject other) {
return RubyRational.newRationalRaw(context.getRuntime(), this).callMethod(context, "/", other);
}
/** num_div
*
*/
@JRubyMethod(name = "div")
public IRubyObject div(ThreadContext context, IRubyObject other) {
return callMethod(context, "/", other).convertToFloat().floor();
}
/** num_divmod
*
*/
@JRubyMethod(name = "divmod")
public IRubyObject divmod(ThreadContext context, IRubyObject other) {
return RubyArray.newArray(getRuntime(), div(context, other), modulo(context, other));
}
/** num_fdiv (1.9) */
@JRubyMethod(name = "fdiv", compat = CompatVersion.RUBY1_9)
public IRubyObject fdiv(ThreadContext context, IRubyObject other) {
return RuntimeHelpers.invoke(context, this.convertToFloat(), "/", other);
}
/** num_modulo
*
*/
@JRubyMethod(name = "modulo")
public IRubyObject modulo(ThreadContext context, IRubyObject other) {
return callMethod(context, "%", other);
}
/** num_remainder
*
*/
@JRubyMethod(name = "remainder")
public IRubyObject remainder(ThreadContext context, IRubyObject dividend) {
IRubyObject z = callMethod(context, "%", dividend);
IRubyObject x = this;
RubyFixnum zero = RubyFixnum.zero(getRuntime());
if (!equalInternal(context, z, zero) &&
((x.callMethod(context, MethodIndex.OP_LT, "<", zero).isTrue() &&
dividend.callMethod(context, MethodIndex.OP_GT, ">", zero).isTrue()) ||
(x.callMethod(context, MethodIndex.OP_GT, ">", zero).isTrue() &&
dividend.callMethod(context, MethodIndex.OP_LT, "<", zero).isTrue()))) {
return z.callMethod(context, MethodIndex.OP_MINUS, "-", dividend);
} else {
return z;
}
}
/** num_abs
*
*/
@JRubyMethod(name = "abs")
public IRubyObject abs(ThreadContext context) {
if (callMethod(context, MethodIndex.OP_LT, "<", RubyFixnum.zero(getRuntime())).isTrue()) {
return callMethod(context, "-@");
}
return this;
}
/** num_to_int
*
*/
@JRubyMethod(name = "to_int")
public IRubyObject to_int(ThreadContext context) {
return RuntimeHelpers.invoke(context, this, "to_i");
}
/** num_scalar_p
*
*/
@JRubyMethod(name = "scalar?", compat = CompatVersion.RUBY1_9)
public IRubyObject scalar_p() {
return getRuntime().getTrue();
}
/** num_int_p
*
*/
@JRubyMethod(name = "integer?")
public IRubyObject integer_p() {
return getRuntime().getFalse();
}
/** num_zero_p
*
*/
@JRubyMethod(name = "zero?")
public IRubyObject zero_p(ThreadContext context) {
return equalInternal(context, this, RubyFixnum.zero(getRuntime())) ? getRuntime().getTrue() : getRuntime().getFalse();
}
/** num_nonzero_p
*
*/
@JRubyMethod(name = "nonzero?")
public IRubyObject nonzero_p(ThreadContext context) {
if (callMethod(context, "zero?").isTrue()) {
return getRuntime().getNil();
}
return this;
}
/** num_floor
*
*/
@JRubyMethod(name = "floor")
public IRubyObject floor() {
return convertToFloat().floor();
}
/** num_ceil
*
*/
@JRubyMethod(name = "ceil")
public IRubyObject ceil() {
return convertToFloat().ceil();
}
/** num_round
*
*/
@JRubyMethod(name = "round")
public IRubyObject round() {
return convertToFloat().round();
}
/** num_truncate
*
*/
@JRubyMethod(name = "truncate")
public IRubyObject truncate() {
return convertToFloat().truncate();
}
@JRubyMethod(name = "step", required = 1, optional = 1, frame = true)
public IRubyObject step(ThreadContext context, IRubyObject[] args, Block block) {
switch (args.length) {
case 0: throw context.getRuntime().newArgumentError(0, 1);
case 1: return step(context, args[0], block);
case 2: return step(context, args[0], args[1], block);
default: throw context.getRuntime().newArgumentError(args.length, 2);
}
}
@JRubyMethod(name = "step", frame = true)
public IRubyObject step(ThreadContext context, IRubyObject arg0, Block block) {
return step(context, arg0, RubyFixnum.one(context.getRuntime()), block);
}
@JRubyMethod(name = "step", frame = true)
public IRubyObject step(ThreadContext context, IRubyObject to, IRubyObject step, Block block) {
if (this instanceof RubyFixnum && to instanceof RubyFixnum && step instanceof RubyFixnum) {
long value = getLongValue();
long end = ((RubyFixnum) to).getLongValue();
long diff = ((RubyFixnum) step).getLongValue();
if (diff == 0) {
throw getRuntime().newArgumentError("step cannot be 0");
}
if (diff > 0) {
for (long i = value; i <= end; i += diff) {
block.yield(context, RubyFixnum.newFixnum(getRuntime(), i));
}
} else {
for (long i = value; i >= end; i += diff) {
block.yield(context, RubyFixnum.newFixnum(getRuntime(), i));
}
}
} else if (this instanceof RubyFloat || to instanceof RubyFloat || step instanceof RubyFloat) {
double beg = num2dbl(this);
double end = num2dbl(to);
double unit = num2dbl(step);
if (unit == 0) {
throw getRuntime().newArgumentError("step cannot be 0");
}
double n = (end - beg)/unit;
double err = (Math.abs(beg) + Math.abs(end) + Math.abs(end - beg)) / Math.abs(unit) * DBL_EPSILON;
if (err>0.5) {
err=0.5;
}
n = Math.floor(n + err) + 1;
for(double i = 0; i < n; i++){
block.yield(context, RubyFloat.newFloat(getRuntime(), i * unit + beg));
}
} else {
RubyNumeric i = this;
int cmp;
String cmpString;
if (((RubyBoolean) step.callMethod(context, MethodIndex.OP_GT, ">", RubyFixnum.zero(getRuntime()))).isTrue()) {
cmp = MethodIndex.OP_GT;
} else {
cmp = MethodIndex.OP_LT;
}
cmpString = MethodIndex.NAMES.get(cmp);
while (true) {
if (i.callMethod(context, cmp, cmpString, to).isTrue()) {
break;
}
block.yield(context, i);
i = (RubyNumeric) i.callMethod(context, MethodIndex.OP_PLUS, "+", step);
}
}
return this;
}
/** num_equal, doesn't override RubyObject.op_equal
*
*/
protected final IRubyObject op_num_equal(ThreadContext context, IRubyObject other) {
// it won't hurt fixnums
if (this == other) return getRuntime().getTrue();
return other.callMethod(context, MethodIndex.EQUALEQUAL, "==", this);
}
/** num_numerator
*
*/
@JRubyMethod(name = "numerator", compat = CompatVersion.RUBY1_9)
public IRubyObject numerator(ThreadContext context) {
return RubyRational.newRationalConvert(context, this).callMethod(context, "numerator");
}
/** num_denominator
*
*/
@JRubyMethod(name = "denominator", compat = CompatVersion.RUBY1_9)
public IRubyObject denominator(ThreadContext context) {
return RubyRational.newRationalConvert(context, this).callMethod(context, "denominator");
}
/** numeric_to_c
*
*/
@JRubyMethod(name = "to_c", compat = CompatVersion.RUBY1_9)
public IRubyObject to_c(ThreadContext context) {
return RubyComplex.newComplexCanonicalize(context, this);
}
/** numeric_re
*
*/
@JRubyMethod(name = "re", compat = CompatVersion.RUBY1_9)
public IRubyObject re(ThreadContext context) {
return RubyComplex.newComplexConvert(context, this);
}
/** numeric_im
*
*/
@JRubyMethod(name = "im", compat = CompatVersion.RUBY1_9)
public IRubyObject im(ThreadContext context) {
return RubyComplex.newComplexConvert(context, RubyFixnum.zero(context.getRuntime()), this);
}
/** numeric_real
*
*/
@JRubyMethod(name = "real", compat = CompatVersion.RUBY1_9)
public IRubyObject real(ThreadContext context) {
return this;
}
/** numeric_image
*
*/
@JRubyMethod(name = {"image", "imag"}, compat = CompatVersion.RUBY1_9)
public IRubyObject image(ThreadContext context) {
return RubyFixnum.zero(context.getRuntime());
}
/** numeric_arg
*
*/
@JRubyMethod(name = "arg", compat = CompatVersion.RUBY1_9)
public IRubyObject arg(ThreadContext context) {
if (!f_negative_p(context, this)) return RubyFixnum.zero(context.getRuntime());
return context.getRuntime().getMath().fastFetchConstant("PI");
}
/** numeric_polar
*
*/
@JRubyMethod(name = "polar", compat = CompatVersion.RUBY1_9)
public IRubyObject polar(ThreadContext context) {
return context.getRuntime().newArray(f_abs(context, this), f_arg(context, this));
}
/** numeric_real
*
*/
@JRubyMethod(name = "conjugate", compat = CompatVersion.RUBY1_9)
public IRubyObject conjugate(ThreadContext context) {
return this;
}
public static class InvalidIntegerException extends NumberFormatException {
private static final long serialVersionUID = 55019452543252148L;
public InvalidIntegerException() {
super();
}
public InvalidIntegerException(String message) {
super(message);
}
public Throwable fillInStackTrace() {
return this;
}
}
public static class NumberTooLargeException extends NumberFormatException {
private static final long serialVersionUID = -1835120694982699449L;
public NumberTooLargeException() {
super();
}
public NumberTooLargeException(String message) {
super(message);
}
public Throwable fillInStackTrace() {
return this;
}
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Ola Bini <ola.bini@ki.se>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 MenTaLguY <mental@rydia.net>
* Copyright (C) 2007 William N Dortch <bill.dortch@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.evaluator.ASTInterpreter;
import org.jruby.exceptions.JumpException;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.util.IdUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.javasupport.JavaObject;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.builtin.InstanceVariables;
import org.jruby.runtime.builtin.InternalVariables;
import org.jruby.runtime.marshal.CoreObjectType;
import org.jruby.util.TypeConverter;
/**
* RubyObject is the only implementation of the
* {@link org.jruby.runtime.builtin.IRubyObject}. Every Ruby object in JRuby
* is represented by something that is an instance of RubyObject. In
* some of the core class implementations, this means doing a subclass
* that extends RubyObject, in other cases it means using a simple
* RubyObject instance and the data field to store specific
* information about the Ruby object.
*
* Some care has been taken to make the implementation be as
* monomorphic as possible, so that the Java Hotspot engine can
* improve performance of it. That is the reason for several patterns
* that might seem odd in this class.
*
* The IRubyObject interface used to have lots of methods for
* different things, but these have now mostly been refactored into
* several interfaces that gives access to that specific part of the
* object. This gives us the possibility to switch out that subsystem
* without changing interfaces again. For example, instance variable
* and internal variables are handled this way, but the implementation
* in RubyObject only returns "this" in {@link #getInstanceVariables()} and
* {@link #getInternalVariables()}.
*
* @author jpetersen
*/
@JRubyClass(name="Object", include="Kernel")
public class RubyObject implements Cloneable, IRubyObject, Serializable, CoreObjectType, InstanceVariables, InternalVariables {
/**
* It's not valid to create a totally empty RubyObject. Since the
* RubyObject is always defined in relation to a runtime, that
* means that creating RubyObjects from outside the class might
* cause problems.
*/
private RubyObject(){};
/**
* A value that is used as a null sentinel in among other places
* the RubyArray implementation. It will cause large problems to
* call any methods on this object.
*/
public static final IRubyObject NEVER = new RubyObject();
/**
* A value that specifies an undefined value. This value is used
* as a sentinel for undefined constant values, and other places
* where neither null nor NEVER makes sense.
*/
public static final IRubyObject UNDEF = new RubyObject();
// The class of this object
protected transient RubyClass metaClass;
/**
* The variableTable contains variables for an object, defined as:
* <ul>
* <li> instance variables
* <li> class variables (for classes/modules)
* <li> internal variables (such as those used when marshaling RubyRange and RubyException)
* </ul>
*
* Constants are stored separately, see {@link RubyModule}.
*
*/
protected transient volatile VariableTableEntry[] variableTable;
protected transient int variableTableSize;
protected transient int variableTableThreshold;
// The dataStruct is a place where custom information can be
// contained for core implementations that doesn't necessarily
// want to go to the trouble of creating a subclass of
// RubyObject. The OpenSSL implementation uses this heavily to
// save holder objects containing Java cryptography objects.
// Java integration uses this to store the Java object ref.
protected transient Object dataStruct;
protected int flags; // zeroed by jvm
public static final int ALL_F = -1;
public static final int FALSE_F = 1 << 0;
/**
* This flag is a bit funny. It's used to denote that this value
* is nil. It's a bit counterintuitive for a Java programmer to
* not use subclassing to handle this case, since we have a
* RubyNil subclass anyway. Well, the reason for it being a flag
* is that the {@link #isNil()} method is called extremely often. So often
* that it gives a good speed boost to make it monomorphic and
* final. It turns out using a flag for this actually gives us
* better performance than having a polymorphic {@link #isNil()} method.
*/
public static final int NIL_F = 1 << 1;
public static final int FROZEN_F = 1 << 2;
public static final int TAINTED_F = 1 << 3;
public static final int FL_USHIFT = 4;
public static final int USER0_F = (1<<(FL_USHIFT+0));
public static final int USER1_F = (1<<(FL_USHIFT+1));
public static final int USER2_F = (1<<(FL_USHIFT+2));
public static final int USER3_F = (1<<(FL_USHIFT+3));
public static final int USER4_F = (1<<(FL_USHIFT+4));
public static final int USER5_F = (1<<(FL_USHIFT+5));
public static final int USER6_F = (1<<(FL_USHIFT+6));
public static final int USER7_F = (1<<(FL_USHIFT+7));
/**
* Sets or unsets a flag on this object. The only flags that are
* guaranteed to be valid to use as the first argument is:
*
* <ul>
* <li>{@link #FALSE_F}</li>
* <li>{@link NIL_F}</li>
* <li>{@link FROZEN_F}</li>
* <li>{@link TAINTED_F}</li>
* <li>{@link USER0_F}</li>
* <li>{@link USER1_F}</li>
* <li>{@link USER2_F}</li>
* <li>{@link USER3_F}</li>
* <li>{@link USER4_F}</li>
* <li>{@link USER5_F}</li>
* <li>{@link USER6_F}</li>
* <li>{@link USER7_F}</li>
* </ul>
*
* @param flag the actual flag to set or unset.
* @param set if true, the flag will be set, if false, the flag will be unset.
*/
public final void setFlag(int flag, boolean set) {
if (set) {
flags |= flag;
} else {
flags &= ~flag;
}
}
/**
* Get the value of a custom flag on this object. The only
* guaranteed flags that can be sent in to this method is:
*
* <ul>
* <li>{@link #FALSE_F}</li>
* <li>{@link NIL_F}</li>
* <li>{@link FROZEN_F}</li>
* <li>{@link TAINTED_F}</li>
* <li>{@link USER0_F}</li>
* <li>{@link USER1_F}</li>
* <li>{@link USER2_F}</li>
* <li>{@link USER3_F}</li>
* <li>{@link USER4_F}</li>
* <li>{@link USER5_F}</li>
* <li>{@link USER6_F}</li>
* <li>{@link USER7_F}</li>
* </ul>
*
* @param flag the flag to get
* @return true if the flag is set, false otherwise
*/
public final boolean getFlag(int flag) {
return (flags & flag) != 0;
}
private transient Finalizer finalizer;
/**
* Class that keeps track of the finalizers for the object under
* operation.
*/
public class Finalizer implements Finalizable {
private long id;
private List<IRubyObject> finalizers;
private AtomicBoolean finalized;
public Finalizer(long id) {
this.id = id;
this.finalized = new AtomicBoolean(false);
}
public void addFinalizer(IRubyObject finalizer) {
if (finalizers == null) {
finalizers = new ArrayList<IRubyObject>();
}
finalizers.add(finalizer);
}
public void removeFinalizers() {
finalizers = null;
}
@Override
public void finalize() {
if (finalized.compareAndSet(false, true)) {
if (finalizers != null) {
for (int i = 0; i < finalizers.size(); i++) {
IRubyObject finalizer = finalizers.get(i);
RuntimeHelpers.invoke(
finalizer.getRuntime().getCurrentContext(),
finalizer, "call", RubyObject.this.id());
}
}
}
}
}
/**
* Standard path for object creation. Objects are entered into ObjectSpace
* only if ObjectSpace is enabled.
*/
public RubyObject(Ruby runtime, RubyClass metaClass) {
this.metaClass = metaClass;
if (runtime.isObjectSpaceEnabled()) addToObjectSpace(runtime);
if (runtime.getSafeLevel() >= 3) taint(runtime);
}
/**
* Path for objects who want to decide whether they don't want to be in
* ObjectSpace even when it is on. (notably used by objects being
* considered immediate, they'll always pass false here)
*/
protected RubyObject(Ruby runtime, RubyClass metaClass, boolean useObjectSpace) {
this.metaClass = metaClass;
if (useObjectSpace) addToObjectSpace(runtime);
if (runtime.getSafeLevel() >= 3) taint(runtime);
}
private void addToObjectSpace(Ruby runtime) {
assert runtime.isObjectSpaceEnabled();
runtime.getObjectSpace().add(this);
}
/**
* Will create the Ruby class Object in the runtime
* specified. This method needs to take the actual class as an
* argument because of the Object class' central part in runtime
* initialization.
*/
public static RubyClass createObjectClass(Ruby runtime, RubyClass objectClass) {
objectClass.index = ClassIndex.OBJECT;
objectClass.defineAnnotatedMethods(ObjectMethods.class);
return objectClass;
}
/**
* Interestingly, the Object class doesn't really have that many
* methods for itself. Instead almost all of the Object methods
* are really defined on the Kernel module. This class is a holder
* for all Object methods.
*
* @see RubyKernel
*/
public static class ObjectMethods {
@JRubyMethod(name = "initialize", visibility = Visibility.PRIVATE)
public static IRubyObject intialize(IRubyObject self) {
return self.getRuntime().getNil();
}
}
/**
* Default allocator instance for all Ruby objects. The only
* reason to not use this allocator is if you actually need to
* have all instances of something be a subclass of RubyObject.
*
* @see org.jruby.runtime.ObjectAllocator
*/
public static final ObjectAllocator OBJECT_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyObject(runtime, klass);
}
};
/**
* Will make sure that this object is added to the current object
* space.
*
* @see org.jruby.runtime.ObjectSpace
*/
public void attachToObjectSpace() {
getRuntime().getObjectSpace().add(this);
}
/**
* This is overridden in the other concrete Java builtins to provide a fast way
* to determine what type they are.
*
* Will generally return a value from org.jruby.runtime.ClassIndex
*
* @see org.jruby.runtime.ClassInde
*/
public int getNativeTypeIndex() {
return ClassIndex.OBJECT;
}
/**
* Specifically polymorphic method that are meant to be overridden
* by modules to specify that they are modules in an easy way.
*/
public boolean isModule() {
return false;
}
/**
* Specifically polymorphic method that are meant to be overridden
* by classes to specify that they are classes in an easy way.
*/
public boolean isClass() {
return false;
}
/**
* Is object immediate (def: Fixnum, Symbol, true, false, nil?).
*/
public boolean isImmediate() {
return false;
}
/** rb_make_metaclass
*
* Will create a new meta class, insert this in the chain of
* classes for this specific object, and return the generated meta
* class.
*/
public RubyClass makeMetaClass(RubyClass superClass) {
MetaClass klass = new MetaClass(getRuntime(), superClass); // rb_class_boot
setMetaClass(klass);
klass.setAttached(this);
klass.setMetaClass(superClass.getRealClass().getMetaClass());
return klass;
}
/**
* Will return the Java interface that most closely can represent
* this object, when working through JAva integration
* translations.
*/
public Class getJavaClass() {
if (dataGetStruct() instanceof JavaObject) {
return ((JavaObject)dataGetStruct()).getValue().getClass();
}
return getClass();
}
/**
* Simple helper to print any objects.
*/
public static void puts(Object obj) {
System.out.println(obj.toString());
}
/**
* This method is just a wrapper around the Ruby "==" method,
* provided so that RubyObjects can be used as keys in the Java
* HashMap object underlying RubyHash.
*/
@Override
public boolean equals(Object other) {
return other == this ||
other instanceof IRubyObject &&
callMethod(getRuntime().getCurrentContext(), MethodIndex.EQUALEQUAL, "==", (IRubyObject) other).isTrue();
}
/**
* The default toString method is just a wrapper that calls the
* Ruby "to_s" method.
*/
@Override
public String toString() {
return RuntimeHelpers.invoke(getRuntime().getCurrentContext(), this, "to_s").toString();
}
/**
* Will return the runtime that this object is associated with.
*
* @return current runtime
*/
public final Ruby getRuntime() {
return getMetaClass().getClassRuntime();
}
/**
* if exist return the meta-class else return the type of the object.
*
*/
public final RubyClass getMetaClass() {
return metaClass;
}
/**
* Makes it possible to change the metaclass of an object. In
* practice, this is a simple version of Smalltalks Become, except
* that it doesn't work when we're dealing with subclasses. In
* practice it's used to change the singleton/meta class used,
* without changing the "real" inheritance chain.
*/
public void setMetaClass(RubyClass metaClass) {
this.metaClass = metaClass;
}
/**
* Is this value frozen or not? Shortcut for doing
* getFlag(FROZEN_F).
*
* @return true if this object is frozen, false otherwise
*/
public boolean isFrozen() {
return (flags & FROZEN_F) != 0;
}
/**
* Sets whether this object is frozen or not. Shortcut for doing
* setFlag(FROZEN_F, frozen).
*
* @param frozen should this object be frozen?
*/
public void setFrozen(boolean frozen) {
if (frozen) {
flags |= FROZEN_F;
} else {
flags &= ~FROZEN_F;
}
}
/** rb_frozen_class_p
*
* Helper to test whether this object is frozen, and if it is will
* throw an exception based on the message.
*/
protected final void testFrozen(String message) {
if (isFrozen()) {
throw getRuntime().newFrozenError(message + " " + getMetaClass().getName());
}
}
/**
* The actual method that checks frozen with the default frozen message from MRI.
* If possible, call this instead of {@link #testFrozen}.
*/
protected void checkFrozen() {
testFrozen("can't modify frozen ");
}
/**
* Gets the taint. Shortcut for getFlag(TAINTED_F).
*
* @return true if this object is tainted
*/
public boolean isTaint() {
return (flags & TAINTED_F) != 0;
}
/**
* Sets the taint flag. Shortcut for setFlag(TAINTED_F, taint)
*
* @param taint should this object be tainted or not?
*/
public void setTaint(boolean taint) {
if (taint) {
flags |= TAINTED_F;
} else {
flags &= ~TAINTED_F;
}
}
/**
* Does this object represent nil? See the docs for the {@link
* #NIL_F} flag for more information.
*/
public final boolean isNil() {
return (flags & NIL_F) != 0;
}
/**
* Is this value a true value or not? Based on the {@link #FALSE_F} flag.
*/
public final boolean isTrue() {
return (flags & FALSE_F) == 0;
}
/**
* Is this value a false value or not? Based on the {@link #FALSE_F} flag.
*/
public final boolean isFalse() {
return (flags & FALSE_F) != 0;
}
/**
* Does this object respond to the specified message? Uses a
* shortcut if it can be proved that respond_to? haven't been
* overridden.
*/
public final boolean respondsTo(String name) {
if(getMetaClass().searchMethod("respond_to?") == getRuntime().getRespondToMethod()) {
return getMetaClass().isMethodBound(name, false);
} else {
return callMethod(getRuntime().getCurrentContext(),"respond_to?",getRuntime().newSymbol(name)).isTrue();
}
}
/** rb_singleton_class
*
* Note: this method is specialized for RubyFixnum, RubySymbol,
* RubyNil and RubyBoolean
*
* Will either return the existing singleton class for this
* object, or create a new one and return that.
*/
public RubyClass getSingletonClass() {
RubyClass klass;
if (getMetaClass().isSingleton() && ((MetaClass)getMetaClass()).getAttached() == this) {
klass = getMetaClass();
} else {
klass = makeMetaClass(getMetaClass());
}
klass.setTaint(isTaint());
if (isFrozen()) klass.setFrozen(true);
return klass;
}
/** rb_singleton_class_clone
*
* Will make sure that if the current objects class is a
* singleton, it will get cloned.
*
* @return either a real class, or a clone of the current singleton class
*/
protected RubyClass getSingletonClassClone() {
RubyClass klass = getMetaClass();
if (!klass.isSingleton()) return klass;
MetaClass clone = new MetaClass(getRuntime());
clone.flags = flags;
if (this instanceof RubyClass) {
clone.setMetaClass(clone);
} else {
clone.setMetaClass(klass.getSingletonClassClone());
}
clone.setSuperClass(klass.getSuperClass());
if (klass.hasVariables()) {
clone.syncVariables(klass.getVariableList());
}
klass.cloneMethods(clone);
((MetaClass)clone.getMetaClass()).setAttached(clone);
((MetaClass)clone).setAttached(((MetaClass)klass).getAttached());
return clone;
}
/** init_copy
*
* Initializes a copy with variable and special instance variable
* information, and then call the initialize_copy Ruby method.
*/
private static void initCopy(IRubyObject clone, RubyObject original) {
assert !clone.isFrozen() : "frozen object (" + clone.getMetaClass().getName() + ") allocated";
original.copySpecialInstanceVariables(clone);
if (original.hasVariables()) {
clone.syncVariables(original.getVariableList());
}
/* FIXME: finalizer should be dupped here */
clone.callMethod(clone.getRuntime().getCurrentContext(), "initialize_copy", original);
}
/** OBJ_INFECT
*
* Infects this object with traits from the argument obj. In real
* terms this currently means that if obj is tainted, this object
* will get tainted too. It's possible to hijack this method to do
* other infections if that would be interesting.
*/
public IRubyObject infectBy(IRubyObject obj) {
if (obj.isTaint()) setTaint(true);
return this;
}
/**
* The protocol for super method invocation is a bit complicated
* in Ruby. In real terms it involves first finding the real
* implementation class (the super class), getting the name of the
* method to call from the frame, and then invoke that on the
* super class with the current self as the actual object
* invoking.
*/
public IRubyObject callSuper(ThreadContext context, IRubyObject[] args, Block block) {
RubyModule klazz = context.getFrameKlazz();
RubyClass superClass = RuntimeHelpers.findImplementerIfNecessary(getMetaClass(), klazz).getSuperClass();
if (superClass == null) {
String name = context.getFrameName();
return RuntimeHelpers.callMethodMissing(context, this, klazz.searchMethod(name), name, args, this, CallType.SUPER, block);
}
return RuntimeHelpers.invokeAs(context, superClass, this, context.getFrameName(), args, CallType.SUPER, block);
}
/**
* Will invoke a named method with no arguments and no block.
*/
public final IRubyObject callMethod(ThreadContext context, String name) {
return RuntimeHelpers.invoke(context, this, name);
}
/**
* Will invoke a named method with one argument and no block with
* functional invocation.
*/
public final IRubyObject callMethod(ThreadContext context, String name, IRubyObject arg) {
return RuntimeHelpers.invoke(context, this, name, arg);
}
/**
* Will invoke a named method with the supplied arguments and no
* block with functional invocation.
*/
public final IRubyObject callMethod(ThreadContext context, String name, IRubyObject[] args) {
return RuntimeHelpers.invoke(context, this, name, args);
}
/**
* Will invoke a named method with the supplied arguments and
* supplied block with functional invocation.
*/
public final IRubyObject callMethod(ThreadContext context, String name, IRubyObject[] args, Block block) {
return RuntimeHelpers.invoke(context, this, name, args, block);
}
/**
* Will invoke an indexed method with the no arguments and no
* block.
*/
public final IRubyObject callMethod(ThreadContext context, int methodIndex, String name) {
return RuntimeHelpers.invoke(context, this, name);
}
/**
* Will invoke an indexed method with the one argument and no
* block with a functional invocation.
*/
public final IRubyObject callMethod(ThreadContext context, int methodIndex, String name, IRubyObject arg) {
return RuntimeHelpers.invoke(context, this, name, arg, Block.NULL_BLOCK);
}
/**
* Call the Ruby initialize method with the supplied arguments and block.
*/
public final void callInit(IRubyObject[] args, Block block) {
callMethod(getRuntime().getCurrentContext(), "initialize", args, block);
}
/** rb_to_id
*
* Will try to convert this object to a String using the Ruby
* "to_str" if the object isn't already a String. If this still
* doesn't work, will throw a Ruby TypeError.
*
*/
public String asJavaString() {
IRubyObject asString = checkStringType();
if(!asString.isNil()) return ((RubyString)asString).asJavaString();
throw getRuntime().newTypeError(inspect().toString() + " is not a symbol");
}
/**
* Tries to convert this object to a Ruby Array using the "to_ary"
* method.
*/
public RubyArray convertToArray() {
return (RubyArray) TypeConverter.convertToType(this, getRuntime().getArray(), MethodIndex.TO_ARY, "to_ary");
}
/**
* Tries to convert this object to a Ruby Hash using the "to_hash"
* method.
*/
public RubyHash convertToHash() {
return (RubyHash)TypeConverter.convertToType(this, getRuntime().getHash(), MethodIndex.TO_HASH, "to_hash");
}
/**
* Tries to convert this object to a Ruby Float using the "to_f"
* method.
*/
public RubyFloat convertToFloat() {
return (RubyFloat) TypeConverter.convertToType(this, getRuntime().getFloat(), MethodIndex.TO_F, "to_f");
}
/**
* Tries to convert this object to a Ruby Integer using the "to_int"
* method.
*/
public RubyInteger convertToInteger() {
return convertToInteger(MethodIndex.TO_INT, "to_int");
}
/**
* Tries to convert this object to a Ruby Integer using the
* supplied conversion method.
*/
public RubyInteger convertToInteger(int convertMethodIndex, String convertMethod) {
IRubyObject val = TypeConverter.convertToType(this, getRuntime().getInteger(), convertMethodIndex, convertMethod, true);
if (!(val instanceof RubyInteger)) throw getRuntime().newTypeError(getMetaClass().getName() + "#" + convertMethod + " should return Integer");
return (RubyInteger)val;
}
/**
* Tries to convert this object to a Ruby String using the
* "to_str" method.
*/
public RubyString convertToString() {
return (RubyString) TypeConverter.convertToType(this, getRuntime().getString(), MethodIndex.TO_STR, "to_str");
}
/**
* Tries to convert this object to the specified Ruby type, using
* a specific conversion method.
*/
public final IRubyObject convertToType(RubyClass target, int convertMethodIndex) {
return TypeConverter.convertToType(this, target, convertMethodIndex, (String)MethodIndex.NAMES.get(convertMethodIndex));
}
/** rb_obj_as_string
*
* First converts this object into a String using the "to_s"
* method, infects it with the current taint and returns it. If
* to_s doesn't return a Ruby String, {@link #anyToString} is used
* instead.
*/
public RubyString asString() {
IRubyObject str = RuntimeHelpers.invoke(getRuntime().getCurrentContext(), this, "to_s");
if (!(str instanceof RubyString)) return (RubyString)anyToString();
if (isTaint()) str.setTaint(true);
return (RubyString) str;
}
/** rb_check_string_type
*
* Tries to return a coerced string representation of this object,
* using "to_str". If that returns something other than a String
* or nil, an empty String will be returned.
*
*/
public IRubyObject checkStringType() {
IRubyObject str = TypeConverter.convertToTypeWithCheck(this, getRuntime().getString(), MethodIndex.TO_STR, "to_str");
if(!str.isNil() && !(str instanceof RubyString)) {
str = RubyString.newEmptyString(getRuntime());
}
return str;
}
/** rb_check_array_type
*
* Returns the result of trying to convert this object to an Array
* with "to_ary".
*/
public IRubyObject checkArrayType() {
return TypeConverter.convertToTypeWithCheck(this, getRuntime().getArray(), MethodIndex.TO_ARY, "to_ary");
}
/** specific_eval
*
* Evaluates the block or string inside of the context of this
* object, using the supplied arguments. If a block is given, this
* will be yielded in the specific context of this object. If no
* block is given then a String-like object needs to be the first
* argument, and this string will be evaluated. Second and third
* arguments in the args-array is optional, but can contain the
* filename and line of the string under evaluation.
*/
@Deprecated
public IRubyObject specificEval(ThreadContext context, RubyModule mod, IRubyObject[] args, Block block) {
if (block.isGiven()) {
if (args.length > 0) throw getRuntime().newArgumentError(args.length, 0);
return yieldUnder(context, mod, block);
}
if (args.length == 0) {
throw getRuntime().newArgumentError("block not supplied");
} else if (args.length > 3) {
String lastFuncName = context.getFrameName();
throw getRuntime().newArgumentError(
"wrong # of arguments: " + lastFuncName + "(src) or " + lastFuncName + "{..}");
}
// We just want the TypeError if the argument doesn't convert to a String (JRUBY-386)
RubyString evalStr;
if (args[0] instanceof RubyString) {
evalStr = (RubyString)args[0];
} else {
evalStr = args[0].convertToString();
}
String file;
int line;
if (args.length > 1) {
file = args[1].convertToString().asJavaString();
if (args.length > 2) {
line = (int)(args[2].convertToInteger().getLongValue() - 1);
} else {
line = 0;
}
} else {
file = "(eval)";
line = 0;
}
return evalUnder(context, mod, evalStr, file, line);
}
/** specific_eval
*
* Evaluates the block or string inside of the context of this
* object, using the supplied arguments. If a block is given, this
* will be yielded in the specific context of this object. If no
* block is given then a String-like object needs to be the first
* argument, and this string will be evaluated. Second and third
* arguments in the args-array is optional, but can contain the
* filename and line of the string under evaluation.
*/
public IRubyObject specificEval(ThreadContext context, RubyModule mod, Block block) {
if (block.isGiven()) {
return yieldUnder(context, mod, block);
} else {
throw context.getRuntime().newArgumentError("block not supplied");
}
}
/** specific_eval
*
* Evaluates the block or string inside of the context of this
* object, using the supplied arguments. If a block is given, this
* will be yielded in the specific context of this object. If no
* block is given then a String-like object needs to be the first
* argument, and this string will be evaluated. Second and third
* arguments in the args-array is optional, but can contain the
* filename and line of the string under evaluation.
*/
public IRubyObject specificEval(ThreadContext context, RubyModule mod, IRubyObject arg, Block block) {
if (block.isGiven()) throw context.getRuntime().newArgumentError(1, 0);
// We just want the TypeError if the argument doesn't convert to a String (JRUBY-386)
RubyString evalStr;
if (arg instanceof RubyString) {
evalStr = (RubyString)arg;
} else {
evalStr = arg.convertToString();
}
String file = "(eval)";
int line = 0;
return evalUnder(context, mod, evalStr, file, line);
}
/** specific_eval
*
* Evaluates the block or string inside of the context of this
* object, using the supplied arguments. If a block is given, this
* will be yielded in the specific context of this object. If no
* block is given then a String-like object needs to be the first
* argument, and this string will be evaluated. Second and third
* arguments in the args-array is optional, but can contain the
* filename and line of the string under evaluation.
*/
public IRubyObject specificEval(ThreadContext context, RubyModule mod, IRubyObject arg0, IRubyObject arg1, Block block) {
if (block.isGiven()) throw context.getRuntime().newArgumentError(2, 0);
// We just want the TypeError if the argument doesn't convert to a String (JRUBY-386)
RubyString evalStr;
if (arg0 instanceof RubyString) {
evalStr = (RubyString)arg0;
} else {
evalStr = arg0.convertToString();
}
String file = arg1.convertToString().asJavaString();
int line = 0;
return evalUnder(context, mod, evalStr, file, line);
}
/** specific_eval
*
* Evaluates the block or string inside of the context of this
* object, using the supplied arguments. If a block is given, this
* will be yielded in the specific context of this object. If no
* block is given then a String-like object needs to be the first
* argument, and this string will be evaluated. Second and third
* arguments in the args-array is optional, but can contain the
* filename and line of the string under evaluation.
*/
public IRubyObject specificEval(ThreadContext context, RubyModule mod, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
if (block.isGiven()) throw context.getRuntime().newArgumentError(2, 0);
// We just want the TypeError if the argument doesn't convert to a String (JRUBY-386)
RubyString evalStr;
if (arg0 instanceof RubyString) {
evalStr = (RubyString)arg0;
} else {
evalStr = arg0.convertToString();
}
String file = arg1.convertToString().asJavaString();
int line = (int)(arg2.convertToInteger().getLongValue() - 1);
return evalUnder(context, mod, evalStr, file, line);
}
/**
* Evaluates the string src with self set to the current object,
* using the module under as the context.
* @deprecated Call with an int line number and String file
*/
public IRubyObject evalUnder(final ThreadContext context, RubyModule under, IRubyObject src, IRubyObject file, IRubyObject line) {
return evalUnder(context, under, src.convertToString(), file.convertToString().toString(), (int) (line.convertToInteger().getLongValue() - 1));
}
/**
* Evaluates the string src with self set to the current object,
* using the module under as the context.
*/
public IRubyObject evalUnder(final ThreadContext context, RubyModule under, RubyString src, String file, int line) {
Visibility savedVisibility = context.getCurrentVisibility();
context.setCurrentVisibility(Visibility.PUBLIC);
context.preExecuteUnder(under, Block.NULL_BLOCK);
try {
return ASTInterpreter.evalSimple(context, this, src,
file, line);
} finally {
context.postExecuteUnder();
context.setCurrentVisibility(savedVisibility);
}
}
/**
* Will yield to the specific block changing the self to be the
* current object instead of the self that is part of the frame
* saved in the block frame. This method is the basis for the Ruby
* instance_eval and module_eval methods. The arguments sent in to
* it in the args array will be yielded to the block. This makes
* it possible to emulate both instance_eval and instance_exec
* with this implementation.
*/
private IRubyObject yieldUnder(final ThreadContext context, RubyModule under, IRubyObject[] args, Block block) {
context.preExecuteUnder(under, block);
Visibility savedVisibility = block.getBinding().getVisibility();
block.getBinding().setVisibility(Visibility.PUBLIC);
try {
IRubyObject valueInYield;
boolean aValue;
if (args.length == 1) {
valueInYield = args[0];
aValue = false;
} else {
valueInYield = RubyArray.newArrayNoCopy(context.getRuntime(), args);
aValue = true;
}
// FIXME: This is an ugly hack to resolve JRUBY-1381; I'm not proud of it
block = block.cloneBlock();
block.getBinding().setSelf(RubyObject.this);
block.getBinding().getFrame().setSelf(RubyObject.this);
// end hack
return block.yield(context, valueInYield, RubyObject.this, context.getRubyClass(), aValue);
//TODO: Should next and return also catch here?
} catch (JumpException.BreakJump bj) {
return (IRubyObject) bj.getValue();
} finally {
block.getBinding().setVisibility(savedVisibility);
context.postExecuteUnder();
}
}
/**
* Will yield to the specific block changing the self to be the
* current object instead of the self that is part of the frame
* saved in the block frame. This method is the basis for the Ruby
* instance_eval and module_eval methods. The arguments sent in to
* it in the args array will be yielded to the block. This makes
* it possible to emulate both instance_eval and instance_exec
* with this implementation.
*/
private IRubyObject yieldUnder(final ThreadContext context, RubyModule under, Block block) {
context.preExecuteUnder(under, block);
Visibility savedVisibility = block.getBinding().getVisibility();
block.getBinding().setVisibility(Visibility.PUBLIC);
try {
// FIXME: This is an ugly hack to resolve JRUBY-1381; I'm not proud of it
block = block.cloneBlock();
block.getBinding().setSelf(RubyObject.this);
block.getBinding().getFrame().setSelf(RubyObject.this);
// end hack
return block.yield(context, this, this, context.getRubyClass(), false);
//TODO: Should next and return also catch here?
} catch (JumpException.BreakJump bj) {
return (IRubyObject) bj.getValue();
} finally {
block.getBinding().setVisibility(savedVisibility);
context.postExecuteUnder();
}
}
// Methods of the Object class (rb_obj_*):
/** rb_obj_equal
*
* Will by default use identity equality to compare objects. This
* follows the Ruby semantics.
*/
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(ThreadContext context, IRubyObject obj) {
return this == obj ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
/** rb_obj_equal
*
* Will use Java identity equality.
*/
@JRubyMethod(name = "equal?", required = 1)
public IRubyObject equal_p(ThreadContext context, IRubyObject obj) {
return this == obj ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
/** method used for Hash key comparison (specialized for String, Symbol and Fixnum)
*
* Will by default just call the Ruby method "eql?"
*/
public boolean eql(IRubyObject other) {
return callMethod(getRuntime().getCurrentContext(), MethodIndex.EQL_P, "eql?", other).isTrue();
}
/** rb_obj_equal
*
* Just like "==" and "equal?", "eql?" will use identity equality for Object.
*/
@JRubyMethod(name = "eql?", required = 1)
public IRubyObject eql_p(IRubyObject obj) {
return this == obj ? getRuntime().getTrue() : getRuntime().getFalse();
}
/** rb_equal
*
* The Ruby "===" method is used by default in case/when
* statements. The Object implementation first checks Java identity
* equality and then calls the "==" method too.
*/
@JRubyMethod(name = "===", required = 1)
public IRubyObject op_eqq(ThreadContext context, IRubyObject other) {
return context.getRuntime().newBoolean(equalInternal(context, this, other));
}
/**
* Helper method for checking equality, first using Java identity
* equality, and then calling the "==" method.
*/
protected static boolean equalInternal(final ThreadContext context, final IRubyObject that, final IRubyObject other){
return that == other || that.callMethod(context, MethodIndex.EQUALEQUAL, "==", other).isTrue();
}
/**
* Helper method for checking equality, first using Java identity
* equality, and then calling the "eql?" method.
*/
protected static boolean eqlInternal(final ThreadContext context, final IRubyObject that, final IRubyObject other){
return that == other || that.callMethod(context, MethodIndex.EQL_P, "eql?", other).isTrue();
}
/** rb_obj_init_copy
*
* Initializes this object as a copy of the original, that is the
* parameter to this object. Will make sure that the argument
* actually has the same real class as this object. It shouldn't
* be possible to initialize an object with something totally
* different.
*/
@JRubyMethod(name = "initialize_copy", required = 1, visibility = Visibility.PRIVATE)
public IRubyObject initialize_copy(IRubyObject original) {
if (this == original) return this;
checkFrozen();
if (getMetaClass().getRealClass() != original.getMetaClass().getRealClass()) {
throw getRuntime().newTypeError("initialize_copy should take same class object");
}
return this;
}
/** obj_respond_to
*
* respond_to?( aSymbol, includePriv=false ) -> true or false
*
* Returns true if this object responds to the given method. Private
* methods are included in the search only if the optional second
* parameter evaluates to true.
*
* @return true if this responds to the given method
*
* !!! For some reason MRI shows the arity of respond_to? as -1, when it should be -2; that's why this is rest instead of required, optional = 1
*
* Going back to splitting according to method arity. MRI is wrong
* about most of these anyway, and since we have arity splitting
* in both the compiler and the interpreter, the performance
* benefit is important for this method.
*/
@JRubyMethod(name = "respond_to?")
public RubyBoolean respond_to_p(IRubyObject mname) {
String name = mname.asJavaString();
return getRuntime().newBoolean(getMetaClass().isMethodBound(name, true));
}
/** obj_respond_to
*
* respond_to?( aSymbol, includePriv=false ) -> true or false
*
* Returns true if this object responds to the given method. Private
* methods are included in the search only if the optional second
* parameter evaluates to true.
*
* @return true if this responds to the given method
*
* !!! For some reason MRI shows the arity of respond_to? as -1, when it should be -2; that's why this is rest instead of required, optional = 1
*
* Going back to splitting according to method arity. MRI is wrong
* about most of these anyway, and since we have arity splitting
* in both the compiler and the interpreter, the performance
* benefit is important for this method.
*/
@JRubyMethod(name = "respond_to?")
public RubyBoolean respond_to_p(IRubyObject mname, IRubyObject includePrivate) {
String name = mname.asJavaString();
return getRuntime().newBoolean(getMetaClass().isMethodBound(name, !includePrivate.isTrue()));
}
/** rb_obj_id
*
* Return the internal id of an object.
*
* FIXME: Should this be renamed to match its ruby name?
*/
@JRubyMethod(name = {"object_id", "__id__"})
public synchronized IRubyObject id() {
return getRuntime().newFixnum(getRuntime().getObjectSpace().idOf(this));
}
/** rb_obj_id_obsolete
*
* Old id version. This one is bound to the "id" name and will emit a deprecation warning.
*/
@JRubyMethod(name = "id")
public synchronized IRubyObject id_deprecated() {
getRuntime().getWarnings().warn(ID.DEPRECATED_METHOD, "Object#id will be deprecated; use Object#object_id", "Object#id", "Object#object_id");
return id();
}
/** rb_obj_id
*
* Will return the hash code of this object. In comparison to MRI,
* this method will use the Java identity hash code instead of
* using rb_obj_id, since the usage of id in JRuby will incur the
* cost of some. ObjectSpace maintenance.
*/
@JRubyMethod(name = "hash")
public RubyFixnum hash() {
return getRuntime().newFixnum(super.hashCode());
}
/**
* Override the Object#hashCode method to make sure that the Ruby
* hash is actually used as the hashcode for Ruby objects. If the
* Ruby "hash" method doesn't return a number, the Object#hashCode
* implementation will be used instead.
*/
@Override
public int hashCode() {
IRubyObject hashValue = callMethod(getRuntime().getCurrentContext(), MethodIndex.HASH, "hash");
if (hashValue instanceof RubyFixnum) return (int) RubyNumeric.fix2long(hashValue);
return super.hashCode();
}
/** rb_obj_class
*
* Returns the real class of this object, excluding any
* singleton/meta class in the inheritance chain.
*/
@JRubyMethod(name = "class")
public RubyClass type() {
return getMetaClass().getRealClass();
}
/** rb_obj_type
*
* The deprecated version of type, that emits a deprecation
* warning.
*/
@JRubyMethod(name = "type")
public RubyClass type_deprecated() {
getRuntime().getWarnings().warn(ID.DEPRECATED_METHOD, "Object#type is deprecated; use Object#class", "Object#type", "Object#class");
return type();
}
/** rb_obj_clone
*
* This method should be overridden only by: Proc, Method,
* UnboundedMethod, Binding. It will use the defined allocated of
* the object, then clone the singleton class, taint the object,
* call initCopy and then copy frozen state.
*/
@JRubyMethod(name = "clone", frame = true)
public IRubyObject rbClone() {
if (isImmediate()) throw getRuntime().newTypeError("can't clone " + getMetaClass().getName());
// We're cloning ourselves, so we know the result should be a RubyObject
RubyObject clone = (RubyObject)getMetaClass().getRealClass().allocate();
clone.setMetaClass(getSingletonClassClone());
if (isTaint()) clone.setTaint(true);
initCopy(clone, this);
if (isFrozen()) clone.setFrozen(true);
return clone;
}
/** rb_obj_dup
*
* This method should be overridden only by: Proc
*
* Will allocate a new instance of the real class of this object,
* and then initialize that copy. It's different from {@link
* #rbClone} in that it doesn't copy the singleton class.
*/
@JRubyMethod(name = "dup")
public IRubyObject dup() {
if (isImmediate()) throw getRuntime().newTypeError("can't dup " + getMetaClass().getName());
IRubyObject dup = getMetaClass().getRealClass().allocate();
if (isTaint()) dup.setTaint(true);
initCopy(dup, this);
return dup;
}
/**
* Lots of MRI objects keep their state in non-lookupable ivars
* (e:g. Range, Struct, etc). This method is responsible for
* dupping our java field equivalents
*/
protected void copySpecialInstanceVariables(IRubyObject clone) {
}
/** rb_obj_display
*
* call-seq:
* obj.display(port=$>) => nil
*
* Prints <i>obj</i> on the given port (default <code>$></code>).
* Equivalent to:
*
* def display(port=$>)
* port.write self
* end
*
* For example:
*
* 1.display
* "cat".display
* [ 4, 5, 6 ].display
* puts
*
* <em>produces:</em>
*
* 1cat456
*
*/
@JRubyMethod(name = "display", optional = 1)
public IRubyObject display(ThreadContext context, IRubyObject[] args) {
IRubyObject port = args.length == 0 ? context.getRuntime().getGlobalVariables().get("$>") : args[0];
port.callMethod(context, "write", this);
return context.getRuntime().getNil();
}
/** rb_obj_tainted
*
* call-seq:
* obj.tainted? => true or false
*
* Returns <code>true</code> if the object is tainted.
*
*/
@JRubyMethod(name = "tainted?")
public RubyBoolean tainted_p(ThreadContext context) {
return context.getRuntime().newBoolean(isTaint());
}
/** rb_obj_taint
*
* call-seq:
* obj.taint -> obj
*
* Marks <i>obj</i> as tainted---if the <code>$SAFE</code> level is
* set appropriately, many method calls which might alter the running
* programs environment will refuse to accept tainted strings.
*/
@JRubyMethod(name = "taint")
public IRubyObject taint(ThreadContext context) {
taint(context.getRuntime());
return this;
}
private void taint(Ruby runtime) {
runtime.secure(4);
if (!isTaint()) {
testFrozen("object");
setTaint(true);
}
}
/** rb_obj_untaint
*
* call-seq:
* obj.untaint => obj
*
* Removes the taint from <i>obj</i>.
*
* Only callable in if more secure than 3.
*/
@JRubyMethod(name = "untaint")
public IRubyObject untaint(ThreadContext context) {
context.getRuntime().secure(3);
if (isTaint()) {
testFrozen("object");
setTaint(false);
}
return this;
}
/** rb_obj_freeze
*
* call-seq:
* obj.freeze => obj
*
* Prevents further modifications to <i>obj</i>. A
* <code>TypeError</code> will be raised if modification is attempted.
* There is no way to unfreeze a frozen object. See also
* <code>Object#frozen?</code>.
*
* a = [ "a", "b", "c" ]
* a.freeze
* a << "z"
*
* <em>produces:</em>
*
* prog.rb:3:in `<<': can't modify frozen array (TypeError)
* from prog.rb:3
*/
@JRubyMethod(name = "freeze")
public IRubyObject freeze(ThreadContext context) {
if ((flags & FROZEN_F) == 0) {
if (context.getRuntime().getSafeLevel() >= 4 && isTaint()) {
throw context.getRuntime().newSecurityError("Insecure: can't freeze object");
}
flags |= FROZEN_F;
}
return this;
}
/** rb_obj_frozen_p
*
* call-seq:
* obj.frozen? => true or false
*
* Returns the freeze status of <i>obj</i>.
*
* a = [ "a", "b", "c" ]
* a.freeze #=> ["a", "b", "c"]
* a.frozen? #=> true
*/
@JRubyMethod(name = "frozen?")
public RubyBoolean frozen_p(ThreadContext context) {
return context.getRuntime().newBoolean(isFrozen());
}
/** inspect_obj
*
* The internal helper method that takes care of the part of the
* inspection that inspects instance variables.
*/
private StringBuilder inspectObj(StringBuilder part) {
ThreadContext context = getRuntime().getCurrentContext();
String sep = "";
for (Variable<IRubyObject> ivar : getInstanceVariableList()) {
part.append(sep).append(" ").append(ivar.getName()).append("=");
part.append(ivar.getValue().callMethod(context, "inspect"));
sep = ",";
}
part.append(">");
return part;
}
/** rb_inspect
*
* The internal helper that ensures a RubyString instance is returned
* so dangerous casting can be omitted
* Prefered over callMethod(context, "inspect")
*/
static RubyString inspect(ThreadContext context, IRubyObject object) {
return RubyString.objAsString(context, object.callMethod(context, "inspect"));
}
/** rb_obj_inspect
*
* call-seq:
* obj.inspect => string
*
* Returns a string containing a human-readable representation of
* <i>obj</i>. If not overridden, uses the <code>to_s</code> method to
* generate the string.
*
* [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
* Time.new.inspect #=> "Wed Apr 09 08:54:39 CDT 2003"
*/
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
Ruby runtime = getRuntime();
if ((!isImmediate()) &&
// TYPE(obj) == T_OBJECT
!(this instanceof RubyClass) &&
this != runtime.getObject() &&
this != runtime.getModule() &&
!(this instanceof RubyModule) &&
// TODO: should have #hasInstanceVariables method, though
// this will work here:
hasVariables()) {
StringBuilder part = new StringBuilder();
String cname = getMetaClass().getRealClass().getName();
part.append("#<").append(cname).append(":0x");
part.append(Integer.toHexString(System.identityHashCode(this)));
if (runtime.isInspecting(this)) {
/* 6:tags 16:addr 1:eos */
part.append(" ...>");
return runtime.newString(part.toString());
}
try {
runtime.registerInspecting(this);
return runtime.newString(inspectObj(part).toString());
} finally {
runtime.unregisterInspecting(this);
}
}
if (isNil()) return RubyNil.inspect(this);
return RuntimeHelpers.invoke(runtime.getCurrentContext(), this, "to_s");
}
/** rb_obj_is_instance_of
*
* call-seq:
* obj.instance_of?(class) => true or false
*
* Returns <code>true</code> if <i>obj</i> is an instance of the given
* class. See also <code>Object#kind_of?</code>.
*/
@JRubyMethod(name = "instance_of?", required = 1)
public RubyBoolean instance_of_p(ThreadContext context, IRubyObject type) {
if (type() == type) {
return context.getRuntime().getTrue();
} else if (!(type instanceof RubyModule)) {
throw context.getRuntime().newTypeError("class or module required");
} else {
return context.getRuntime().getFalse();
}
}
/** rb_obj_is_kind_of
*
* call-seq:
* obj.is_a?(class) => true or false
* obj.kind_of?(class) => true or false
*
* Returns <code>true</code> if <i>class</i> is the class of
* <i>obj</i>, or if <i>class</i> is one of the superclasses of
* <i>obj</i> or modules included in <i>obj</i>.
*
* module M; end
* class A
* include M
* end
* class B < A; end
* class C < B; end
* b = B.new
* b.instance_of? A #=> false
* b.instance_of? B #=> true
* b.instance_of? C #=> false
* b.instance_of? M #=> false
* b.kind_of? A #=> true
* b.kind_of? B #=> true
* b.kind_of? C #=> false
* b.kind_of? M #=> true
*/
@JRubyMethod(name = {"kind_of?", "is_a?"}, required = 1)
public RubyBoolean kind_of_p(ThreadContext context, IRubyObject type) {
// TODO: Generalize this type-checking code into IRubyObject helper.
if (!(type instanceof RubyModule)) {
// TODO: newTypeError does not offer enough for ruby error string...
throw context.getRuntime().newTypeError("class or module required");
}
return context.getRuntime().newBoolean(((RubyModule)type).isInstance(this));
}
/** rb_obj_methods
*
* call-seq:
* obj.methods => array
*
* Returns a list of the names of methods publicly accessible in
* <i>obj</i>. This will include all the methods accessible in
* <i>obj</i>'s ancestors.
*
* class Klass
* def kMethod()
* end
* end
* k = Klass.new
* k.methods[0..9] #=> ["kMethod", "freeze", "nil?", "is_a?",
* "class", "instance_variable_set",
* "methods", "extend", "__send__", "instance_eval"]
* k.methods.length #=> 42
*/
@JRubyMethod(name = "methods", optional = 1)
public IRubyObject methods(ThreadContext context, IRubyObject[] args) {
boolean all = true;
if (args.length == 1) {
all = args[0].isTrue();
}
RubyArray singletonMethods = null;
if (getMetaClass().isSingleton()) {
singletonMethods =
getMetaClass().instance_methods(new IRubyObject[] {context.getRuntime().getFalse()});
if (all) {
singletonMethods.concat(getMetaClass().getSuperClass().instance_methods(new IRubyObject[] {context.getRuntime().getTrue()}));
}
} else {
if (all) {
singletonMethods = getMetaClass().instance_methods(new IRubyObject[] {context.getRuntime().getTrue()});
} else {
singletonMethods = context.getRuntime().newEmptyArray();
}
}
return singletonMethods;
}
/** rb_obj_public_methods
*
* call-seq:
* obj.public_methods(all=true) => array
*
* Returns the list of public methods accessible to <i>obj</i>. If
* the <i>all</i> parameter is set to <code>false</code>, only those methods
* in the receiver will be listed.
*/
@JRubyMethod(name = "public_methods", optional = 1)
public IRubyObject public_methods(ThreadContext context, IRubyObject[] args) {
if (args.length == 0) {
args = new IRubyObject[] { context.getRuntime().getTrue() };
}
return getMetaClass().public_instance_methods(args);
}
/** rb_obj_protected_methods
*
* call-seq:
* obj.protected_methods(all=true) => array
*
* Returns the list of protected methods accessible to <i>obj</i>. If
* the <i>all</i> parameter is set to <code>false</code>, only those methods
* in the receiver will be listed.
*
* Internally this implementation uses the
* {@link RubyModule#protected_instance_methods} method.
*/
@JRubyMethod(name = "protected_methods", optional = 1)
public IRubyObject protected_methods(ThreadContext context, IRubyObject[] args) {
if (args.length == 0) {
args = new IRubyObject[] { context.getRuntime().getTrue() };
}
return getMetaClass().protected_instance_methods(args);
}
/** rb_obj_private_methods
*
* call-seq:
* obj.private_methods(all=true) => array
*
* Returns the list of private methods accessible to <i>obj</i>. If
* the <i>all</i> parameter is set to <code>false</code>, only those methods
* in the receiver will be listed.
*
* Internally this implementation uses the
* {@link RubyModule#private_instance_methods} method.
*/
@JRubyMethod(name = "private_methods", optional = 1)
public IRubyObject private_methods(ThreadContext context, IRubyObject[] args) {
if (args.length == 0) {
args = new IRubyObject[] { context.getRuntime().getTrue() };
}
return getMetaClass().private_instance_methods(args);
}
/** rb_obj_singleton_methods
*
* call-seq:
* obj.singleton_methods(all=true) => array
*
* Returns an array of the names of singleton methods for <i>obj</i>.
* If the optional <i>all</i> parameter is true, the list will include
* methods in modules included in <i>obj</i>.
*
* module Other
* def three() end
* end
*
* class Single
* def Single.four() end
* end
*
* a = Single.new
*
* def a.one()
* end
*
* class << a
* include Other
* def two()
* end
* end
*
* Single.singleton_methods #=> ["four"]
* a.singleton_methods(false) #=> ["two", "one"]
* a.singleton_methods #=> ["two", "one", "three"]
*/
// TODO: This is almost RubyModule#instance_methods on the metaClass. Perhaps refactor.
@JRubyMethod(name = "singleton_methods", optional = 1)
public RubyArray singleton_methods(ThreadContext context, IRubyObject[] args) {
boolean all = true;
if(args.length == 1) {
all = args[0].isTrue();
}
RubyArray singletonMethods;
if (getMetaClass().isSingleton()) {
singletonMethods = getMetaClass().instance_methods(new IRubyObject[] {context.getRuntime().getFalse()});
if (all) {
RubyClass superClass = getMetaClass().getSuperClass();
while (superClass.isIncluded()) {
singletonMethods.concat(superClass.instance_methods(new IRubyObject[] {context.getRuntime().getFalse()}));
superClass = superClass.getSuperClass();
}
}
} else {
singletonMethods = context.getRuntime().newEmptyArray();
}
return singletonMethods;
}
/** rb_obj_method
*
* call-seq:
* obj.method(sym) => method
*
* Looks up the named method as a receiver in <i>obj</i>, returning a
* <code>Method</code> object (or raising <code>NameError</code>). The
* <code>Method</code> object acts as a closure in <i>obj</i>'s object
* instance, so instance variables and the value of <code>self</code>
* remain available.
*
* class Demo
* def initialize(n)
* @iv = n
* end
* def hello()
* "Hello, @iv = #{@iv}"
* end
* end
*
* k = Demo.new(99)
* m = k.method(:hello)
* m.call #=> "Hello, @iv = 99"
*
* l = Demo.new('Fred')
* m = l.method("hello")
* m.call #=> "Hello, @iv = Fred"
*/
@JRubyMethod(name = "method", required = 1)
public IRubyObject method(IRubyObject symbol) {
return getMetaClass().newMethod(this, symbol.asJavaString(), true);
}
/**
* Internal method that helps to convert any object into the
* format of a class name and a hex string inside of #<>.
*/
public IRubyObject anyToString() {
String cname = getMetaClass().getRealClass().getName();
/* 6:tags 16:addr 1:eos */
RubyString str = getRuntime().newString("#<" + cname + ":0x" + Integer.toHexString(System.identityHashCode(this)) + ">");
str.setTaint(isTaint());
return str;
}
/** rb_any_to_s
*
* call-seq:
* obj.to_s => string
*
* Returns a string representing <i>obj</i>. The default
* <code>to_s</code> prints the object's class and an encoding of the
* object id. As a special case, the top-level object that is the
* initial execution context of Ruby programs returns ``main.''
*/
@JRubyMethod(name = "to_s")
public IRubyObject to_s() {
return anyToString();
}
/** rb_any_to_a
*
* call-seq:
* obj.to_a -> anArray
*
* Returns an array representation of <i>obj</i>. For objects of class
* <code>Object</code> and others that don't explicitly override the
* method, the return value is an array containing <code>self</code>.
* However, this latter behavior will soon be obsolete.
*
* self.to_a #=> -:1: warning: default `to_a' will be obsolete
* "hello".to_a #=> ["hello"]
* Time.new.to_a #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, "CDT"]
*
* The default to_a method is deprecated.
*/
@JRubyMethod(name = "to_a", visibility = Visibility.PUBLIC)
public RubyArray to_a() {
getRuntime().getWarnings().warn(ID.DEPRECATED_METHOD, "default 'to_a' will be obsolete", "to_a");
return getRuntime().newArray(this);
}
/** rb_obj_instance_eval
*
* call-seq:
* obj.instance_eval(string [, filename [, lineno]] ) => obj
* obj.instance_eval {| | block } => obj
*
* Evaluates a string containing Ruby source code, or the given block,
* within the context of the receiver (_obj_). In order to set the
* context, the variable +self+ is set to _obj_ while
* the code is executing, giving the code access to _obj_'s
* instance variables. In the version of <code>instance_eval</code>
* that takes a +String+, the optional second and third
* parameters supply a filename and starting line number that are used
* when reporting compilation errors.
*
* class Klass
* def initialize
* @secret = 99
* end
* end
* k = Klass.new
* k.instance_eval { @secret } #=> 99
*/
@JRubyMethod(name = "instance_eval", frame = true)
public IRubyObject instance_eval(ThreadContext context, Block block) {
return specificEval(context, getInstanceEvalClass(), block);
}
@JRubyMethod(name = "instance_eval", frame = true)
public IRubyObject instance_eval(ThreadContext context, IRubyObject arg0, Block block) {
return specificEval(context, getInstanceEvalClass(), arg0, block);
}
@JRubyMethod(name = "instance_eval", frame = true)
public IRubyObject instance_eval(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
return specificEval(context, getInstanceEvalClass(), arg0, arg1, block);
}
@JRubyMethod(name = "instance_eval", frame = true)
public IRubyObject instance_eval(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
return specificEval(context, getInstanceEvalClass(), arg0, arg1, arg2, block);
}
@Deprecated
public IRubyObject instance_eval(ThreadContext context, IRubyObject[] args, Block block) {
RubyModule klazz;
if (isImmediate()) {
// Ruby uses Qnil here, we use "dummy" because we need a class
klazz = context.getRuntime().getDummy();
} else {
klazz = getSingletonClass();
}
return specificEval(context, klazz, args, block);
}
private RubyModule getInstanceEvalClass() {
if (isImmediate()) {
// Ruby uses Qnil here, we use "dummy" because we need a class
return getRuntime().getDummy();
} else {
return getSingletonClass();
}
}
/** rb_obj_instance_exec
*
* call-seq:
* obj.instance_exec(arg...) {|var...| block } => obj
*
* Executes the given block within the context of the receiver
* (_obj_). In order to set the context, the variable +self+ is set
* to _obj_ while the code is executing, giving the code access to
* _obj_'s instance variables. Arguments are passed as block parameters.
*
* class Klass
* def initialize
* @secret = 99
* end
* end
* k = Klass.new
* k.instance_exec(5) {|x| @secret+x } #=> 104
*/
@JRubyMethod(name = "instance_exec", optional = 3, frame = true)
public IRubyObject instance_exec(ThreadContext context, IRubyObject[] args, Block block) {
if (!block.isGiven()) throw context.getRuntime().newArgumentError("block not supplied");
RubyModule klazz;
if (isImmediate()) {
// Ruby uses Qnil here, we use "dummy" because we need a class
klazz = context.getRuntime().getDummy();
} else {
klazz = getSingletonClass();
}
return yieldUnder(context, klazz, args, block);
}
/** rb_obj_extend
*
* call-seq:
* obj.extend(module, ...) => obj
*
* Adds to _obj_ the instance methods from each module given as a
* parameter.
*
* module Mod
* def hello
* "Hello from Mod.\n"
* end
* end
*
* class Klass
* def hello
* "Hello from Klass.\n"
* end
* end
*
* k = Klass.new
* k.hello #=> "Hello from Klass.\n"
* k.extend(Mod) #=> #<Klass:0x401b3bc8>
* k.hello #=> "Hello from Mod.\n"
*/
@JRubyMethod(name = "extend", required = 1, rest = true)
public IRubyObject extend(IRubyObject[] args) {
Ruby runtime = getRuntime();
// Make sure all arguments are modules before calling the callbacks
for (int i = 0; i < args.length; i++) {
if (!args[i].isModule()) throw runtime.newTypeError(args[i], runtime.getModule());
}
ThreadContext context = runtime.getCurrentContext();
// MRI extends in order from last to first
for (int i = args.length - 1; i >= 0; i--) {
args[i].callMethod(context, "extend_object", this);
args[i].callMethod(context, "extended", this);
}
return this;
}
/** rb_obj_dummy
*
* Default initialize method. This one gets defined in some other
* place as a Ruby method.
*/
public IRubyObject initialize() {
return getRuntime().getNil();
}
/** rb_f_send
*
* send( aSymbol [, args ]* ) -> anObject
*
* Invokes the method identified by aSymbol, passing it any arguments
* specified. You can use __send__ if the name send clashes with an
* existing method in this object.
*
* <pre>
* class Klass
* def hello(*args)
* "Hello " + args.join(' ')
* end
* end
*
* k = Klass.new
* k.send :hello, "gentle", "readers"
* </pre>
*
* @return the result of invoking the method identified by aSymbol.
*/
@JRubyMethod(name = {"send", "__send__"})
public IRubyObject send(ThreadContext context, Block block) {
throw context.getRuntime().newArgumentError(0, 1);
}
@JRubyMethod(name = {"send", "__send__"})
public IRubyObject send(ThreadContext context, IRubyObject arg0, Block block) {
String name = arg0.asJavaString();
return getMetaClass().finvoke(context, this, name, block);
}
@JRubyMethod(name = {"send", "__send__"})
public IRubyObject send(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
String name = arg0.asJavaString();
return getMetaClass().finvoke(context, this, name, arg1, block);
}
@JRubyMethod(name = {"send", "__send__"})
public IRubyObject send(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
String name = arg0.asJavaString();
return getMetaClass().finvoke(context, this, name, arg1, arg2, block);
}
@JRubyMethod(name = {"send", "__send__"}, rest = true)
public IRubyObject send(ThreadContext context, IRubyObject[] args, Block block) {
String name = args[0].asJavaString();
int newArgsLength = args.length - 1;
IRubyObject[] newArgs;
if (newArgsLength == 0) {
newArgs = IRubyObject.NULL_ARRAY;
} else {
newArgs = new IRubyObject[newArgsLength];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
}
return getMetaClass().finvoke(context, this, name, newArgs, block);
}
/** rb_false
*
* call_seq:
* nil.nil? => true
* <anything_else>.nil? => false
*
* Only the object <i>nil</i> responds <code>true</code> to <code>nil?</code>.
*/
@JRubyMethod(name = "nil?")
public IRubyObject nil_p(ThreadContext context) {
return context.getRuntime().getFalse();
}
/** rb_obj_pattern_match
*
* call-seq:
* obj =~ other => false
*
* Pattern Match---Overridden by descendents (notably
* <code>Regexp</code> and <code>String</code>) to provide meaningful
* pattern-match semantics.
*/
@JRubyMethod(name = "=~", required = 1)
public IRubyObject op_match(ThreadContext context, IRubyObject arg) {
return context.getRuntime().getFalse();
}
public IRubyObject to_java() {
throw getRuntime().newTypeError(getMetaClass().getBaseName() + " cannot coerce to a Java type.");
}
public IRubyObject as(Class javaClass) {
throw getRuntime().newTypeError(getMetaClass().getBaseName() + " cannot coerce to a Java type.");
}
/**
* @see org.jruby.runtime.builtin.IRubyObject#getType()
*/
public RubyClass getType() {
return type();
}
/**
* @see org.jruby.runtime.builtin.IRubyObject#dataWrapStruct()
*/
public synchronized void dataWrapStruct(Object obj) {
this.dataStruct = obj;
}
/**
* @see org.jruby.runtime.builtin.IRubyObject#dataGetStruct()
*/
public synchronized Object dataGetStruct() {
return dataStruct;
}
/**
* Adds the specified object as a finalizer for this object.
*/
public void addFinalizer(IRubyObject finalizer) {
if (this.finalizer == null) {
this.finalizer = new Finalizer(getRuntime().getObjectSpace().idOf(this));
getRuntime().addFinalizer(this.finalizer);
}
this.finalizer.addFinalizer(finalizer);
}
/**
* Remove all the finalizers for this object.
*/
public void removeFinalizers() {
if (finalizer != null) {
finalizer.removeFinalizers();
finalizer = null;
getRuntime().removeFinalizer(this.finalizer);
}
}
//
// INSTANCE VARIABLE RUBY METHODS
//
/** rb_obj_ivar_defined
*
* call-seq:
* obj.instance_variable_defined?(symbol) => true or false
*
* Returns <code>true</code> if the given instance variable is
* defined in <i>obj</i>.
*
* class Fred
* def initialize(p1, p2)
* @a, @b = p1, p2
* end
* end
* fred = Fred.new('cat', 99)
* fred.instance_variable_defined?(:@a) #=> true
* fred.instance_variable_defined?("@b") #=> true
* fred.instance_variable_defined?("@c") #=> false
*/
@JRubyMethod(name = "instance_variable_defined?", required = 1)
public IRubyObject instance_variable_defined_p(ThreadContext context, IRubyObject name) {
if (variableTableContains(validateInstanceVariable(name.asJavaString()))) {
return context.getRuntime().getTrue();
}
return context.getRuntime().getFalse();
}
/** rb_obj_ivar_get
*
* call-seq:
* obj.instance_variable_get(symbol) => obj
*
* Returns the value of the given instance variable, or nil if the
* instance variable is not set. The <code>@</code> part of the
* variable name should be included for regular instance
* variables. Throws a <code>NameError</code> exception if the
* supplied symbol is not valid as an instance variable name.
*
* class Fred
* def initialize(p1, p2)
* @a, @b = p1, p2
* end
* end
* fred = Fred.new('cat', 99)
* fred.instance_variable_get(:@a) #=> "cat"
* fred.instance_variable_get("@b") #=> 99
*/
@JRubyMethod(name = "instance_variable_get", required = 1)
public IRubyObject instance_variable_get(ThreadContext context, IRubyObject name) {
IRubyObject value;
if ((value = variableTableFetch(validateInstanceVariable(name.asJavaString()))) != null) {
return value;
}
return context.getRuntime().getNil();
}
/** rb_obj_ivar_set
*
* call-seq:
* obj.instance_variable_set(symbol, obj) => obj
*
* Sets the instance variable names by <i>symbol</i> to
* <i>object</i>, thereby frustrating the efforts of the class's
* author to attempt to provide proper encapsulation. The variable
* did not have to exist prior to this call.
*
* class Fred
* def initialize(p1, p2)
* @a, @b = p1, p2
* end
* end
* fred = Fred.new('cat', 99)
* fred.instance_variable_set(:@a, 'dog') #=> "dog"
* fred.instance_variable_set(:@c, 'cat') #=> "cat"
* fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
*/
@JRubyMethod(name = "instance_variable_set", required = 2)
public IRubyObject instance_variable_set(IRubyObject name, IRubyObject value) {
ensureInstanceVariablesSettable();
return variableTableStore(validateInstanceVariable(name.asJavaString()), value);
}
/** rb_obj_remove_instance_variable
*
* call-seq:
* obj.remove_instance_variable(symbol) => obj
*
* Removes the named instance variable from <i>obj</i>, returning that
* variable's value.
*
* class Dummy
* attr_reader :var
* def initialize
* @var = 99
* end
* def remove
* remove_instance_variable(:@var)
* end
* end
* d = Dummy.new
* d.var #=> 99
* d.remove #=> 99
* d.var #=> nil
*/
@JRubyMethod(name = "remove_instance_variable", required = 1, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject remove_instance_variable(ThreadContext context, IRubyObject name, Block block) {
ensureInstanceVariablesSettable();
IRubyObject value;
if ((value = variableTableRemove(validateInstanceVariable(name.asJavaString()))) != null) {
return value;
}
throw context.getRuntime().newNameError("instance variable " + name.asJavaString() + " not defined", name.asJavaString());
}
/** rb_obj_instance_variables
*
* call-seq:
* obj.instance_variables => array
*
* Returns an array of instance variable names for the receiver. Note
* that simply defining an accessor does not create the corresponding
* instance variable.
*
* class Fred
* attr_accessor :a1
* def initialize
* @iv = 3
* end
* end
* Fred.new.instance_variables #=> ["@iv"]
*/
@JRubyMethod(name = "instance_variables")
public RubyArray instance_variables(ThreadContext context) {
Ruby runtime = context.getRuntime();
List<String> nameList = getInstanceVariableNameList();
RubyArray array = runtime.newArray(nameList.size());
for (String name : nameList) {
array.append(runtime.newString(name));
}
return array;
}
//
// INSTANCE VARIABLE API METHODS
//
/**
* Dummy method to avoid a cast, and to avoid polluting the
* IRubyObject interface with all the instance variable management
* methods.
*/
public InstanceVariables getInstanceVariables() {
return this;
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#hasInstanceVariable
*/
public boolean hasInstanceVariable(String name) {
assert IdUtil.isInstanceVariable(name);
return variableTableContains(name);
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#fastHasInstanceVariable
*/
public boolean fastHasInstanceVariable(String internedName) {
assert IdUtil.isInstanceVariable(internedName);
return variableTableFastContains(internedName);
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#getInstanceVariable
*/
public IRubyObject getInstanceVariable(String name) {
assert IdUtil.isInstanceVariable(name);
return variableTableFetch(name);
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#fastGetInstanceVariable
*/
public IRubyObject fastGetInstanceVariable(String internedName) {
assert IdUtil.isInstanceVariable(internedName);
return variableTableFastFetch(internedName);
}
/** rb_iv_set / rb_ivar_set
*
* @see org.jruby.runtime.builtin.InstanceVariables#setInstanceVariable
*/
public IRubyObject setInstanceVariable(String name, IRubyObject value) {
assert IdUtil.isInstanceVariable(name) && value != null;
ensureInstanceVariablesSettable();
return variableTableStore(name, value);
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#fastSetInstanceVariable
*/
public IRubyObject fastSetInstanceVariable(String internedName, IRubyObject value) {
assert IdUtil.isInstanceVariable(internedName) && value != null;
ensureInstanceVariablesSettable();
return variableTableFastStore(internedName, value);
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#removeInstanceVariable
*/
public IRubyObject removeInstanceVariable(String name) {
assert IdUtil.isInstanceVariable(name);
ensureInstanceVariablesSettable();
return variableTableRemove(name);
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#getInstanceVariableList
*/
public List<Variable<IRubyObject>> getInstanceVariableList() {
VariableTableEntry[] table = variableTableGetTable();
ArrayList<Variable<IRubyObject>> list = new ArrayList<Variable<IRubyObject>>();
IRubyObject readValue;
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if (IdUtil.isInstanceVariable(e.name)) {
if ((readValue = e.value) == null) readValue = variableTableReadLocked(e);
list.add(new VariableEntry<IRubyObject>(e.name, readValue));
}
}
}
return list;
}
/**
* @see org.jruby.runtime.builtin.InstanceVariables#getInstanceVariableNameList
*/
public List<String> getInstanceVariableNameList() {
VariableTableEntry[] table = variableTableGetTable();
ArrayList<String> list = new ArrayList<String>();
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if (IdUtil.isInstanceVariable(e.name)) {
list.add(e.name);
}
}
}
return list;
}
/**
* The error message used when some one tries to modify an
* instance variable in a high security setting.
*/
protected static final String ERR_INSECURE_SET_INST_VAR = "Insecure: can't modify instance variable";
/**
* Checks if the name parameter represents a legal instance variable name, and otherwise throws a Ruby NameError
*/
protected String validateInstanceVariable(String name) {
if (IdUtil.isValidInstanceVariableName(name)) return name;
throw getRuntime().newNameError("`" + name + "' is not allowable as an instance variable name", name);
}
/**
* Makes sure that instance variables can be set on this object,
* including information about whether this object is frozen, or
* tainted. Will throw a suitable exception in that case.
*/
protected void ensureInstanceVariablesSettable() {
if (!isFrozen() && (getRuntime().getSafeLevel() < 4 || isTaint())) {
return;
}
if (getRuntime().getSafeLevel() >= 4 && !isTaint()) {
throw getRuntime().newSecurityError(ERR_INSECURE_SET_INST_VAR);
}
if (isFrozen()) {
if (this instanceof RubyModule) {
throw getRuntime().newFrozenError("class/module ");
} else {
throw getRuntime().newFrozenError("");
}
}
}
//
// INTERNAL VARIABLE METHODS
//
/**
* Dummy method to avoid a cast, and to avoid polluting the
* IRubyObject interface with all the instance variable management
* methods.
*/
public InternalVariables getInternalVariables() {
return this;
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#hasInternalVariable
*/
public boolean hasInternalVariable(String name) {
assert !isRubyVariable(name);
return variableTableContains(name);
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#fastHasInternalVariable
*/
public boolean fastHasInternalVariable(String internedName) {
assert !isRubyVariable(internedName);
return variableTableFastContains(internedName);
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#getInternalVariable
*/
public IRubyObject getInternalVariable(String name) {
assert !isRubyVariable(name);
return variableTableFetch(name);
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#fastGetInternalVariable
*/
public IRubyObject fastGetInternalVariable(String internedName) {
assert !isRubyVariable(internedName);
return variableTableFastFetch(internedName);
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#setInternalVariable
*/
public void setInternalVariable(String name, IRubyObject value) {
assert !isRubyVariable(name);
variableTableStore(name, value);
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#fastSetInternalVariable
*/
public void fastSetInternalVariable(String internedName, IRubyObject value) {
assert !isRubyVariable(internedName);
variableTableFastStore(internedName, value);
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#removeInternalVariable
*/
public IRubyObject removeInternalVariable(String name) {
assert !isRubyVariable(name);
return variableTableRemove(name);
}
/**
* Sync one variable table with another - this is used to make
* rbClone work correctly.
*/
public void syncVariables(List<Variable<IRubyObject>> variables) {
variableTableSync(variables);
}
/**
* @see org.jruby.runtime.builtin.InternalVariables#getInternalVariableList
*/
public List<Variable<IRubyObject>> getInternalVariableList() {
VariableTableEntry[] table = variableTableGetTable();
ArrayList<Variable<IRubyObject>> list = new ArrayList<Variable<IRubyObject>>();
IRubyObject readValue;
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if (!isRubyVariable(e.name)) {
if ((readValue = e.value) == null) readValue = variableTableReadLocked(e);
list.add(new VariableEntry<IRubyObject>(e.name, readValue));
}
}
}
return list;
}
//
// COMMON VARIABLE METHODS
//
/**
* Returns true if object has any variables, defined as:
* <ul>
* <li> instance variables
* <li> class variables
* <li> constants
* <li> internal variables, such as those used when marshaling Ranges and Exceptions
* </ul>
* @return true if object has any variables, else false
*/
public boolean hasVariables() {
return variableTableGetSize() > 0;
}
/**
* Returns the amount of instance variables, class variables,
* constants and internal variables this object has.
*/
public int getVariableCount() {
return variableTableGetSize();
}
/**
* Gets a list of all variables in this object.
*/
// TODO: must override in RubyModule to pick up constants
public List<Variable<IRubyObject>> getVariableList() {
VariableTableEntry[] table = variableTableGetTable();
ArrayList<Variable<IRubyObject>> list = new ArrayList<Variable<IRubyObject>>();
IRubyObject readValue;
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if ((readValue = e.value) == null) readValue = variableTableReadLocked(e);
list.add(new VariableEntry<IRubyObject>(e.name, readValue));
}
}
return list;
}
/**
* Gets a name list of all variables in this object.
*/
// TODO: must override in RubyModule to pick up constants
public List<String> getVariableNameList() {
VariableTableEntry[] table = variableTableGetTable();
ArrayList<String> list = new ArrayList<String>();
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
list.add(e.name);
}
}
return list;
}
/**
* Gets internal access to the getmap for variables.
*/
@SuppressWarnings("unchecked")
@Deprecated // born deprecated
public Map getVariableMap() {
return variableTableGetMap();
}
/**
* Check the syntax of a Ruby variable, including that it's longer
* than zero characters, and starts with either an @ or a capital
* letter.
*/
// FIXME: this should go somewhere more generic -- maybe IdUtil
protected static final boolean isRubyVariable(String name) {
char c;
return name.length() > 0 && ((c = name.charAt(0)) == '@' || (c <= 'Z' && c >= 'A'));
}
//
// VARIABLE TABLE METHODS, ETC.
//
protected static final int VARIABLE_TABLE_DEFAULT_CAPACITY = 8; // MUST be power of 2!
protected static final int VARIABLE_TABLE_MAXIMUM_CAPACITY = 1 << 30;
protected static final float VARIABLE_TABLE_LOAD_FACTOR = 0.75f;
protected static final VariableTableEntry[] VARIABLE_TABLE_EMPTY_TABLE = new VariableTableEntry[0];
/**
* Every entry in the variable map is represented by an instance
* of this class.
*/
protected static final class VariableTableEntry {
final int hash;
final String name;
volatile IRubyObject value;
final VariableTableEntry next;
VariableTableEntry(int hash, String name, IRubyObject value, VariableTableEntry next) {
assert name == name.intern() : name + " is not interned";
this.hash = hash;
this.name = name;
this.value = value;
this.next = next;
}
}
/**
* Reads the value of the specified entry, locked on the current
* object.
*/
protected synchronized IRubyObject variableTableReadLocked(VariableTableEntry entry) {
return entry.value;
}
/**
* Checks if the variable table contains a variable of the
* specified name.
*/
protected boolean variableTableContains(String name) {
VariableTableEntry[] table;
if ((table = variableTable) != null) {
int hash = name.hashCode();
for (VariableTableEntry e = table[hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
return true;
}
}
}
return false;
}
/**
* Checks if the variable table contains the the variable of the
* specified name, where the precondition is that the name must be
* an interned Java String.
*/
protected boolean variableTableFastContains(String internedName) {
assert internedName == internedName.intern() : internedName + " not interned";
VariableTableEntry[] table;
if ((table = variableTable) != null) {
for (VariableTableEntry e = table[internedName.hashCode() & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
return true;
}
}
}
return false;
}
/**
* Fetch an object from the variable table based on the name.
*
* @return the object or null if not found
*/
protected IRubyObject variableTableFetch(String name) {
VariableTableEntry[] table;
IRubyObject readValue;
if ((table = variableTable) != null) {
int hash = name.hashCode();
for (VariableTableEntry e = table[hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
if ((readValue = e.value) != null) return readValue;
return variableTableReadLocked(e);
}
}
}
return null;
}
/**
* Fetch an object from the variable table based on the name,
* where the name must be an interned Java String.
*
* @return the object or null if not found
*/
protected IRubyObject variableTableFastFetch(String internedName) {
assert internedName == internedName.intern() : internedName + " not interned";
VariableTableEntry[] table;
IRubyObject readValue;
if ((table = variableTable) != null) {
for (VariableTableEntry e = table[internedName.hashCode() & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
if ((readValue = e.value) != null) return readValue;
return variableTableReadLocked(e);
}
}
}
return null;
}
/**
* Store a value in the variable store under the specific name.
*/
protected IRubyObject variableTableStore(String name, IRubyObject value) {
int hash = name.hashCode();
synchronized(this) {
VariableTableEntry[] table;
VariableTableEntry e;
if ((table = variableTable) == null) {
table = new VariableTableEntry[VARIABLE_TABLE_DEFAULT_CAPACITY];
e = new VariableTableEntry(hash, name.intern(), value, null);
table[hash & (VARIABLE_TABLE_DEFAULT_CAPACITY - 1)] = e;
variableTableThreshold = (int)(VARIABLE_TABLE_DEFAULT_CAPACITY * VARIABLE_TABLE_LOAD_FACTOR);
variableTableSize = 1;
variableTable = table;
return value;
}
int potentialNewSize;
if ((potentialNewSize = variableTableSize + 1) > variableTableThreshold) {
table = variableTableRehash();
}
int index;
for (e = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
e.value = value;
return value;
}
}
e = new VariableTableEntry(hash, name.intern(), value, table[index]);
table[index] = e;
variableTableSize = potentialNewSize;
variableTable = table; // write-volatile
}
return value;
}
/**
* Will store the value under the specified name, where the name
* needs to be an interned Java String.
*/
protected IRubyObject variableTableFastStore(String internedName, IRubyObject value) {
assert internedName == internedName.intern() : internedName + " not interned";
int hash = internedName.hashCode();
synchronized(this) {
VariableTableEntry[] table;
VariableTableEntry e;
if ((table = variableTable) == null) {
table = new VariableTableEntry[VARIABLE_TABLE_DEFAULT_CAPACITY];
e = new VariableTableEntry(hash, internedName, value, null);
table[hash & (VARIABLE_TABLE_DEFAULT_CAPACITY - 1)] = e;
variableTableThreshold = (int)(VARIABLE_TABLE_DEFAULT_CAPACITY * VARIABLE_TABLE_LOAD_FACTOR);
variableTableSize = 1;
variableTable = table;
return value;
}
int potentialNewSize;
if ((potentialNewSize = variableTableSize + 1) > variableTableThreshold) {
table = variableTableRehash();
}
int index;
for (e = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
e.value = value;
return value;
}
}
e = new VariableTableEntry(hash, internedName, value, table[index]);
table[index] = e;
variableTableSize = potentialNewSize;
variableTable = table; // write-volatile
}
return value;
}
/**
* Removes the entry with the specified name from the variable
* table, and returning the removed value.
*/
protected IRubyObject variableTableRemove(String name) {
synchronized(this) {
VariableTableEntry[] table;
if ((table = variableTable) != null) {
int hash = name.hashCode();
int index = hash & (table.length - 1);
VariableTableEntry first = table[index];
VariableTableEntry e;
for (e = first; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
IRubyObject oldValue = e.value;
// All entries following removed node can stay
// in list, but all preceding ones need to be
// cloned.
VariableTableEntry newFirst = e.next;
for (VariableTableEntry p = first; p != e; p = p.next) {
newFirst = new VariableTableEntry(p.hash, p.name, p.value, newFirst);
}
table[index] = newFirst;
variableTableSize--;
variableTable = table; // write-volatile
return oldValue;
}
}
}
}
return null;
}
/**
* Get the actual table used to save variable entries.
*/
protected VariableTableEntry[] variableTableGetTable() {
VariableTableEntry[] table;
if ((table = variableTable) != null) {
return table;
}
return VARIABLE_TABLE_EMPTY_TABLE;
}
/**
* Get the size of the variable table.
*/
protected int variableTableGetSize() {
if (variableTable != null) {
return variableTableSize;
}
return 0;
}
/**
* Synchronize the variable table with the argument. In real terms
* this means copy all entries into a newly allocated table.
*/
protected void variableTableSync(List<Variable<IRubyObject>> vars) {
synchronized(this) {
variableTableSize = 0;
variableTableThreshold = (int)(VARIABLE_TABLE_DEFAULT_CAPACITY * VARIABLE_TABLE_LOAD_FACTOR);
variableTable = new VariableTableEntry[VARIABLE_TABLE_DEFAULT_CAPACITY];
for (Variable<IRubyObject> var : vars) {
variableTableStore(var.getName(), var.getValue());
}
}
}
/**
* Rehashes the variable table. Must be called from a synchronized
* block.
*/
// MUST be called from synchronized/locked block!
// should only be called by variableTableStore/variableTableFastStore
protected final VariableTableEntry[] variableTableRehash() {
VariableTableEntry[] oldTable = variableTable;
int oldCapacity;
if ((oldCapacity = oldTable.length) >= VARIABLE_TABLE_MAXIMUM_CAPACITY) {
return oldTable;
}
int newCapacity = oldCapacity << 1;
VariableTableEntry[] newTable = new VariableTableEntry[newCapacity];
variableTableThreshold = (int)(newCapacity * VARIABLE_TABLE_LOAD_FACTOR);
int sizeMask = newCapacity - 1;
VariableTableEntry e;
for (int i = oldCapacity; --i >= 0; ) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
e = oldTable[i];
if (e != null) {
VariableTableEntry next = e.next;
int idx = e.hash & sizeMask;
// Single node on list
if (next == null)
newTable[idx] = e;
else {
// Reuse trailing consecutive sequence at same slot
VariableTableEntry lastRun = e;
int lastIdx = idx;
for (VariableTableEntry last = next;
last != null;
last = last.next) {
int k = last.hash & sizeMask;
if (k != lastIdx) {
lastIdx = k;
lastRun = last;
}
}
newTable[lastIdx] = lastRun;
// Clone all remaining nodes
for (VariableTableEntry p = e; p != lastRun; p = p.next) {
int k = p.hash & sizeMask;
VariableTableEntry m = new VariableTableEntry(p.hash, p.name, p.value, newTable[k]);
newTable[k] = m;
}
}
}
}
variableTable = newTable;
return newTable;
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
protected Map variableTableGetMap() {
HashMap map = new HashMap();
VariableTableEntry[] table;
IRubyObject readValue;
if ((table = variableTable) != null) {
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if ((readValue = e.value) == null) readValue = variableTableReadLocked(e);
map.put(e.name, readValue);
}
}
}
return map;
}
/**
* Method to help ease transition to new variables implementation.
* Will likely be deprecated in the near future.
*/
@SuppressWarnings("unchecked")
protected Map variableTableGetMap(Map map) {
VariableTableEntry[] table;
IRubyObject readValue;
if ((table = variableTable) != null) {
for (int i = table.length; --i >= 0; ) {
for (VariableTableEntry e = table[i]; e != null; e = e.next) {
if ((readValue = e.value) == null) readValue = variableTableReadLocked(e);
map.put(e.name, readValue);
}
}
}
return map;
}
/**
* Tries to support Java serialization of Ruby objects. This is
* still experimental and might not work.
*/
// NOTE: Serialization is primarily supported for testing purposes, and there is no general
// guarantee that serialization will work correctly. Specifically, instance variables pointing
// at symbols, threads, modules, classes, and other unserializable types are not detected.
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
// write out ivar count followed by name/value pairs
List<String> names = getInstanceVariableNameList();
out.writeInt(names.size());
for (String name : names) {
out.writeObject(name);
out.writeObject(getInstanceVariables().getInstanceVariable(name));
}
}
/**
* Tries to support Java unserialization of Ruby objects. This is
* still experimental and might not work.
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
// rest in ivar count followed by name/value pairs
int ivarCount = in.readInt();
for (int i = 0; i < ivarCount; i++) {
setInstanceVariable((String)in.readObject(), (IRubyObject)in.readObject());
}
}
}
package org.jruby;
import org.jruby.runtime.Block;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* @author nicksieger
*/
public interface RubyObjectAdapter {
boolean isKindOf(IRubyObject value, RubyModule rubyModule);
IRubyObject setInstanceVariable(IRubyObject obj, String variableName, IRubyObject value);
IRubyObject[] convertToJavaArray(IRubyObject array);
RubyInteger convertToRubyInteger(IRubyObject obj);
IRubyObject getInstanceVariable(IRubyObject obj, String variableName);
RubyString convertToRubyString(IRubyObject obj);
// These call* assume ThreadContext = receiver.getRuntime().getCurrentContext()
IRubyObject callMethod(IRubyObject receiver, String methodName);
IRubyObject callMethod(IRubyObject receiver, String methodName, IRubyObject singleArg);
IRubyObject callMethod(IRubyObject receiver, String methodName, IRubyObject[] args);
IRubyObject callMethod(IRubyObject receiver, String methodName, IRubyObject[] args, Block block);
IRubyObject callSuper(IRubyObject receiver, IRubyObject[] args);
IRubyObject callSuper(IRubyObject receiver, IRubyObject[] args, Block block);
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.Iterator;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyModule(name="ObjectSpace")
public class RubyObjectSpace {
/** Create the ObjectSpace module and add it to the Ruby runtime.
*
*/
public static RubyModule createObjectSpaceModule(Ruby runtime) {
RubyModule objectSpaceModule = runtime.defineModule("ObjectSpace");
runtime.setObjectSpaceModule(objectSpaceModule);
objectSpaceModule.defineAnnotatedMethods(RubyObjectSpace.class);
return objectSpaceModule;
}
@JRubyMethod(name = "define_finalizer", required = 1, optional = 1, frame = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject define_finalizer(IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = recv.getRuntime();
IRubyObject finalizer = null;
if (args.length == 2) {
finalizer = args[1];
if (!finalizer.respondsTo("call")) {
throw runtime.newArgumentError("wrong type argument "
+ finalizer.getType() + " (should be callable)");
}
} else {
finalizer = runtime.newProc(Block.Type.PROC, block);
}
IRubyObject obj = args[0];
runtime.getObjectSpace().addFinalizer(obj, finalizer);
return runtime.newArray(runtime.newFixnum(runtime.getSafeLevel()), finalizer);
}
@JRubyMethod(name = "undefine_finalizer", required = 1, frame = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject undefine_finalizer(IRubyObject recv, IRubyObject arg1, Block block) {
recv.getRuntime().getObjectSpace().removeFinalizers(RubyNumeric.fix2long(arg1.id()));
return recv;
}
@JRubyMethod(name = "_id2ref", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject id2ref(IRubyObject recv, IRubyObject id) {
Ruby runtime = id.getRuntime();
if (!(id instanceof RubyFixnum)) {
throw recv.getRuntime().newTypeError(id, recv.getRuntime().getFixnum());
}
RubyFixnum idFixnum = (RubyFixnum) id;
long longId = idFixnum.getLongValue();
if (longId == 0) {
return runtime.getFalse();
} else if (longId == 2) {
return runtime.getTrue();
} else if (longId == 4) {
return runtime.getNil();
} else if (longId % 2 != 0) {
// odd
return runtime.newFixnum((longId - 1) / 2);
} else {
IRubyObject object = runtime.getObjectSpace().id2ref(longId);
if (object == null) {
return runtime.getNil();
}
return object;
}
}
@JRubyMethod(name = "each_object", optional = 1, frame = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject each_object(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyModule rubyClass;
if (args.length == 0) {
rubyClass = recv.getRuntime().getObject();
} else {
if (!(args[0] instanceof RubyModule)) throw recv.getRuntime().newTypeError("class or module required");
rubyClass = (RubyModule) args[0];
}
Ruby runtime = recv.getRuntime();
int count = 0;
if (rubyClass != runtime.getClassClass()) {
if (!runtime.isObjectSpaceEnabled()) {
throw runtime.newRuntimeError("ObjectSpace is disabled; each_object will only work with Class, pass +O to enable");
}
Iterator iter = recv.getRuntime().getObjectSpace().iterator(rubyClass);
IRubyObject obj = null;
while ((obj = (IRubyObject)iter.next()) != null) {
count++;
block.yield(context, obj);
}
} else {
Iterator iter = runtime.getObject().subclasses(true).iterator();
while (iter.hasNext()) {
count++;
block.yield(context, (IRubyObject)iter.next());
}
}
return recv.getRuntime().newFixnum(count);
}
@JRubyMethod(name = "garbage_collect", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject garbage_collect(IRubyObject recv) {
return RubyGC.start(recv);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callback.Callback;
/**
*
* @author jpetersen
*/
@JRubyModule(name="Precision")
public class RubyPrecision {
public static RubyModule createPrecisionModule(Ruby runtime) {
RubyModule precisionModule = runtime.defineModule("Precision");
runtime.setPrecision(precisionModule);
precisionModule.defineAnnotatedMethods(RubyPrecision.class);
return precisionModule;
}
public static IRubyObject induced_from(IRubyObject receiver, IRubyObject source, Block block) {
throw receiver.getRuntime().newTypeError("Undefined conversion from " + source.getMetaClass().getName() + " into " + ((RubyClass)receiver).getName());
}
@JRubyMethod(name = "append_features", required = 1, frame = true, module = true)
public static IRubyObject append_features(IRubyObject receiver, IRubyObject include, Block block) {
if (include instanceof RubyModule) {
((RubyModule) include).includeModule(receiver);
include.getSingletonClass().defineMethod("induced_from", new Callback() {
public IRubyObject execute(IRubyObject recv, IRubyObject[] args, Block block) {
Arity.checkArgumentCount(recv.getRuntime(), args, 1, 1);
return RubyPrecision.induced_from(recv, args[0], block);
}
public Arity getArity() {
return Arity.ONE_ARGUMENT;
}
});
}
return receiver;
}
@JRubyMethod(name = "prec", required = 1, frame = true)
public static IRubyObject prec(ThreadContext context, IRubyObject receiver, IRubyObject type, Block block) {
return type.callMethod(context, "induced_from", receiver);
}
@JRubyMethod(name = "prec_i", frame = true)
public static IRubyObject prec_i(ThreadContext context, IRubyObject receiver, Block block) {
return receiver.getRuntime().getInteger().callMethod(context, "induced_from", receiver);
}
@JRubyMethod(name = "prec_f", frame = true)
public static IRubyObject prec_f(ThreadContext context, IRubyObject receiver, Block block) {
return receiver.getRuntime().getFloat().callMethod(context, "induced_from", receiver);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.exceptions.JumpException;
import org.jruby.internal.runtime.JumpTarget;
import org.jruby.java.MiniJava;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
/**
* @author jpetersen
*/
@JRubyClass(name="Proc")
public class RubyProc extends RubyObject implements JumpTarget {
private Block block = Block.NULL_BLOCK;
private Block.Type type;
private String file;
private int line;
public RubyProc(Ruby runtime, RubyClass rubyClass, Block.Type type) {
super(runtime, rubyClass);
this.type = type;
}
private static ObjectAllocator PROC_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyProc instance = RubyProc.newProc(runtime, Block.Type.PROC);
instance.setMetaClass(klass);
return instance;
}
};
public static RubyClass createProcClass(Ruby runtime) {
RubyClass procClass = runtime.defineClass("Proc", runtime.getObject(), PROC_ALLOCATOR);
runtime.setProc(procClass);
procClass.defineAnnotatedMethods(RubyProc.class);
return procClass;
}
public Block getBlock() {
return block;
}
// Proc class
public static RubyProc newProc(Ruby runtime, Block.Type type) {
return new RubyProc(runtime, runtime.getProc(), type);
}
public static RubyProc newProc(Ruby runtime, Block block, Block.Type type) {
RubyProc proc = new RubyProc(runtime, runtime.getProc(), type);
proc.callInit(NULL_ARRAY, block);
return proc;
}
/**
* Create a new instance of a Proc object. We override this method (from RubyClass)
* since we need to deal with special case of Proc.new with no arguments or block arg. In
* this case, we need to check previous frame for a block to consume.
*/
@JRubyMethod(name = "new", rest = true, frame = true, meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
// No passed in block, lets check next outer frame for one ('Proc.new')
if (!block.isGiven()) {
block = context.getPreviousFrame().getBlock();
}
if (block.isGiven() && block.getProcObject() != null) {
return block.getProcObject();
}
IRubyObject obj = ((RubyClass) recv).allocate();
obj.callMethod(context, "initialize", args, block);
return obj;
}
@JRubyMethod(name = "initialize", frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, Block procBlock) {
if (!procBlock.isGiven()) {
throw getRuntime().newArgumentError("tried to create Proc object without a block");
}
if (type == Block.Type.LAMBDA && procBlock == null) {
// TODO: warn "tried to create Proc object without a block"
}
block = procBlock.cloneBlock();
block.type = type;
block.setProcObject(this);
file = context.getFile();
line = context.getLine();
return this;
}
@JRubyMethod(name = "clone")
public IRubyObject rbClone() {
RubyProc newProc = new RubyProc(getRuntime(), getRuntime().getProc(), type);
newProc.block = getBlock();
newProc.file = file;
newProc.line = line;
// TODO: CLONE_SETUP here
return newProc;
}
@JRubyMethod(name = "dup")
public IRubyObject dup() {
RubyProc newProc = new RubyProc(getRuntime(), getRuntime().getProc(), type);
newProc.block = getBlock();
newProc.file = file;
newProc.line = line;
return newProc;
}
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(IRubyObject other) {
if (!(other instanceof RubyProc)) return getRuntime().getFalse();
if (this == other || this.block == ((RubyProc)other).block) {
return getRuntime().getTrue();
}
return getRuntime().getFalse();
}
@JRubyMethod(name = "to_s")
public IRubyObject to_s() {
return RubyString.newString(getRuntime(),
"#<Proc:0x" + Integer.toString(block.hashCode(), 16) + "@" +
file + ":" + (line + 1) + ">");
}
@JRubyMethod(name = "binding")
public IRubyObject binding() {
return getRuntime().newBinding(block.getBinding());
}
@JRubyMethod(name = {"call", "[]"}, rest = true, frame = true)
public IRubyObject call(ThreadContext context, IRubyObject[] args) {
return call(context, args, null);
}
public IRubyObject call(ThreadContext context, IRubyObject[] args, IRubyObject self) {
assert args != null;
Ruby runtime = getRuntime();
Block newBlock = block.cloneBlock();
JumpTarget jumpTarget = newBlock.getBinding().getFrame().getJumpTarget();
try {
if (self != null) newBlock.getBinding().setSelf(self);
return newBlock.call(context, args);
} catch (JumpException.BreakJump bj) {
switch(block.type) {
case LAMBDA: if (bj.getTarget() == jumpTarget) {
return (IRubyObject) bj.getValue();
} else {
throw runtime.newLocalJumpError("break", (IRubyObject)bj.getValue(), "unexpected break");
}
case PROC:
if (newBlock.isEscaped()) {
throw runtime.newLocalJumpError("break", (IRubyObject)bj.getValue(), "break from proc-closure");
} else {
throw bj;
}
default: throw bj;
}
} catch (JumpException.ReturnJump rj) {
Object target = rj.getTarget();
if (target == jumpTarget && block.type == Block.Type.LAMBDA) return (IRubyObject) rj.getValue();
if (type == Block.Type.THREAD) {
throw runtime.newThreadError("return can't jump across threads");
}
throw rj;
} catch (JumpException.RetryJump rj) {
throw runtime.newLocalJumpError("retry", (IRubyObject)rj.getValue(), "retry not supported outside rescue");
}
}
@JRubyMethod(name = "arity")
public RubyFixnum arity() {
return getRuntime().newFixnum(block.arity().getValue());
}
@JRubyMethod(name = "to_proc")
public RubyProc to_proc() {
return this;
}
public IRubyObject as(Class asClass) {
final Ruby ruby = getRuntime();
if (!asClass.isInterface()) {
throw ruby.newTypeError(asClass.getCanonicalName() + " is not an interface");
}
return MiniJava.javaToRuby(ruby, Proxy.newProxyInstance(Ruby.getClassLoader(), new Class[] {asClass}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
IRubyObject[] rubyArgs = new IRubyObject[args.length + 1];
rubyArgs[0] = RubySymbol.newSymbol(ruby, method.getName());
for (int i = 1; i < rubyArgs.length; i++) {
rubyArgs[i] = MiniJava.javaToRuby(ruby, args[i - 1]);
}
return MiniJava.rubyToJava(call(ruby.getCurrentContext(), rubyArgs));
}
}));
}
}
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.ext.posix.POSIX;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.CallBlock;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
/**
*/
@JRubyModule(name="Process")
public class RubyProcess {
public static RubyModule createProcessModule(Ruby runtime) {
RubyModule process = runtime.defineModule("Process");
runtime.setProcess(process);
// TODO: NOT_ALLOCATABLE_ALLOCATOR is probably ok here. Confirm. JRUBY-415
RubyClass process_status = process.defineClassUnder("Status", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setProcStatus(process_status);
RubyModule process_uid = process.defineModuleUnder("UID");
runtime.setProcUID(process_uid);
RubyModule process_gid = process.defineModuleUnder("GID");
runtime.setProcGID(process_gid);
RubyModule process_sys = process.defineModuleUnder("Sys");
runtime.setProcSys(process_sys);
process.defineAnnotatedMethods(RubyProcess.class);
process_status.defineAnnotatedMethods(RubyStatus.class);
process_uid.defineAnnotatedMethods(UserID.class);
process_gid.defineAnnotatedMethods(GroupID.class);
process_sys.defineAnnotatedMethods(Sys.class);
process.defineConstant("PRIO_PROCESS", runtime.newFixnum(0));
process.defineConstant("PRIO_PGRP", runtime.newFixnum(1));
process.defineConstant("PRIO_USER", runtime.newFixnum(2));
process.defineConstant("WNOHANG", runtime.newFixnum(1));
return process;
}
@JRubyClass(name="Process::Status")
public static class RubyStatus extends RubyObject {
private long status = 0L;
private static final long EXIT_SUCCESS = 0L;
public RubyStatus(Ruby runtime, RubyClass metaClass, long status) {
super(runtime, metaClass);
this.status = status;
}
public static RubyStatus newProcessStatus(Ruby runtime, long status) {
return new RubyStatus(runtime, runtime.getProcStatus(), status);
}
// Bunch of methods still not implemented
@JRubyMethod(name = {"to_int", "pid", "stopped?", "stopsig", "signaled?", "termsig?", "exited?", "coredump?"})
public IRubyObject not_implemented() {
String error = "Process::Status#" + getRuntime().getCurrentContext().getFrameName() + " not implemented";
throw getRuntime().newNotImplementedError(error);
}
@JRubyMethod(name = {"&"})
public IRubyObject not_implemented1(IRubyObject arg) {
String error = "Process::Status#" + getRuntime().getCurrentContext().getFrameName() + " not implemented";
throw getRuntime().newNotImplementedError(error);
}
@JRubyMethod
public IRubyObject exitstatus() {
return getRuntime().newFixnum(status);
}
@JRubyMethod(name = ">>")
public IRubyObject op_rshift(IRubyObject other) {
long shiftValue = other.convertToInteger().getLongValue();
return getRuntime().newFixnum(status >> shiftValue);
}
@JRubyMethod(name = "==")
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
return other.callMethod(context, MethodIndex.EQUALEQUAL, "==", this.to_i());
}
@JRubyMethod
public IRubyObject to_i() {
return getRuntime().newFixnum(shiftedValue());
}
@JRubyMethod
public IRubyObject to_s() {
return getRuntime().newString(String.valueOf(shiftedValue()));
}
@JRubyMethod
public IRubyObject inspect() {
return getRuntime().newString("#<Process::Status: pid=????,exited(" + String.valueOf(status) + ")>");
}
@JRubyMethod(name = "success?")
public IRubyObject success_p() {
return getRuntime().newBoolean(status == EXIT_SUCCESS);
}
private long shiftedValue() {
return status << 8;
}
}
@JRubyModule(name="Process::UID")
public static class UserID {
@JRubyMethod(name = "change_privilege", module = true)
public static IRubyObject change_privilege(IRubyObject self, IRubyObject arg) {
throw self.getRuntime().newNotImplementedError("Process::UID::change_privilege not implemented yet");
}
@JRubyMethod(name = "eid", module = true)
public static IRubyObject eid(IRubyObject self) {
return euid(self);
}
@JRubyMethod(name = "eid=", module = true)
public static IRubyObject eid(IRubyObject self, IRubyObject arg) {
return euid_set(self, arg);
}
@JRubyMethod(name = "grant_privilege", module = true)
public static IRubyObject grant_privilege(IRubyObject self, IRubyObject arg) {
throw self.getRuntime().newNotImplementedError("Process::UID::grant_privilege not implemented yet");
}
@JRubyMethod(name = "re_exchange", module = true)
public static IRubyObject re_exchange(ThreadContext context, IRubyObject self) {
return switch_rb(context, self, Block.NULL_BLOCK);
}
@JRubyMethod(name = "re_exchangeable?", module = true)
public static IRubyObject re_exchangeable_p(IRubyObject self) {
throw self.getRuntime().newNotImplementedError("Process::UID::re_exchangeable? not implemented yet");
}
@JRubyMethod(name = "rid", module = true)
public static IRubyObject rid(IRubyObject self) {
return uid(self);
}
@JRubyMethod(name = "sid_available?", module = true)
public static IRubyObject sid_available_p(IRubyObject self) {
throw self.getRuntime().newNotImplementedError("Process::UID::sid_available not implemented yet");
}
@JRubyMethod(name = "switch", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject switch_rb(ThreadContext context, IRubyObject self, Block block) {
Ruby runtime = self.getRuntime();
int uid = runtime.getPosix().getuid();
int euid = runtime.getPosix().geteuid();
if (block.isGiven()) {
try {
runtime.getPosix().seteuid(uid);
runtime.getPosix().setuid(euid);
return block.yield(context, runtime.getNil());
} finally {
runtime.getPosix().seteuid(euid);
runtime.getPosix().setuid(uid);
}
} else {
runtime.getPosix().seteuid(uid);
runtime.getPosix().setuid(euid);
return RubyFixnum.zero(runtime);
}
}
}
@JRubyModule(name="Process::GID")
public static class GroupID {
@JRubyMethod(name = "change_privilege", module = true)
public static IRubyObject change_privilege(IRubyObject self, IRubyObject arg) {
throw self.getRuntime().newNotImplementedError("Process::GID::change_privilege not implemented yet");
}
@JRubyMethod(name = "eid", module = true)
public static IRubyObject eid(IRubyObject self) {
return egid(self);
}
@JRubyMethod(name = "eid=", module = true)
public static IRubyObject eid(IRubyObject self, IRubyObject arg) {
return RubyProcess.egid_set(self, arg);
}
@JRubyMethod(name = "grant_privilege", module = true)
public static IRubyObject grant_privilege(IRubyObject self, IRubyObject arg) {
throw self.getRuntime().newNotImplementedError("Process::GID::grant_privilege not implemented yet");
}
@JRubyMethod(name = "re_exchange", module = true)
public static IRubyObject re_exchange(ThreadContext context, IRubyObject self) {
return switch_rb(context, self, Block.NULL_BLOCK);
}
@JRubyMethod(name = "re_exchangeable?", module = true)
public static IRubyObject re_exchangeable_p(IRubyObject self) {
throw self.getRuntime().newNotImplementedError("Process::GID::re_exchangeable? not implemented yet");
}
@JRubyMethod(name = "rid", module = true)
public static IRubyObject rid(IRubyObject self) {
return gid(self);
}
@JRubyMethod(name = "sid_available?", module = true)
public static IRubyObject sid_available_p(IRubyObject self) {
throw self.getRuntime().newNotImplementedError("Process::GID::sid_available not implemented yet");
}
@JRubyMethod(name = "switch", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject switch_rb(ThreadContext context, IRubyObject self, Block block) {
Ruby runtime = self.getRuntime();
int gid = runtime.getPosix().getgid();
int egid = runtime.getPosix().getegid();
if (block.isGiven()) {
try {
runtime.getPosix().setegid(gid);
runtime.getPosix().setgid(egid);
return block.yield(context, runtime.getNil());
} finally {
runtime.getPosix().setegid(egid);
runtime.getPosix().setgid(gid);
}
} else {
runtime.getPosix().setegid(gid);
runtime.getPosix().setgid(egid);
return RubyFixnum.zero(runtime);
}
}
}
@JRubyModule(name="Process::Sys")
public static class Sys {
@JRubyMethod(name = "getegid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject getegid(IRubyObject self) {
return egid(self);
}
@JRubyMethod(name = "geteuid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject geteuid(IRubyObject self) {
return euid(self);
}
@JRubyMethod(name = "getgid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject getgid(IRubyObject self) {
return gid(self);
}
@JRubyMethod(name = "getuid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject getuid(IRubyObject self) {
return uid(self);
}
@JRubyMethod(name = "setegid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setegid(IRubyObject recv, IRubyObject arg) {
return egid_set(recv, arg);
}
@JRubyMethod(name = "seteuid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject seteuid(IRubyObject recv, IRubyObject arg) {
return euid_set(recv, arg);
}
@JRubyMethod(name = "setgid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setgid(IRubyObject recv, IRubyObject arg) {
return gid_set(recv, arg);
}
@JRubyMethod(name = "setuid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setuid(IRubyObject recv, IRubyObject arg) {
return uid_set(recv, arg);
}
}
@JRubyMethod(name = "abort", optional = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject abort(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return RubyKernel.abort(context, recv, args);
}
@JRubyMethod(name = "exit!", optional = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject exit_bang(IRubyObject recv, IRubyObject[] args) {
return RubyKernel.exit_bang(recv, args);
}
@JRubyMethod(name = "groups", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject groups(IRubyObject recv) {
throw recv.getRuntime().newNotImplementedError("Process#groups not yet implemented");
}
@JRubyMethod(name = "setrlimit", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setrlimit(IRubyObject recv, IRubyObject[] args) {
throw recv.getRuntime().newNotImplementedError("Process#setrlimit not yet implemented");
}
@JRubyMethod(name = "getpgrp", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject getpgrp(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().getpgrp());
}
@JRubyMethod(name = "groups=", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject groups_set(IRubyObject recv, IRubyObject arg) {
throw recv.getRuntime().newNotImplementedError("Process#groups not yet implemented");
}
@JRubyMethod(name = "waitpid", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject waitpid(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
int pid = -1;
int flags = 0;
if (args.length > 0) {
pid = (int)args[0].convertToInteger().getLongValue();
}
if (args.length > 1) {
flags = (int)args[1].convertToInteger().getLongValue();
}
int[] status = new int[1];
pid = runtime.getPosix().waitpid(pid, status, flags);
if (pid == -1) {
throw runtime.newErrnoECHILDError();
}
runtime.getGlobalVariables().set(
"$?",
RubyProcess.RubyStatus.newProcessStatus(runtime, status[0]));
return runtime.newFixnum(pid);
}
@JRubyMethod(name = "wait", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject wait(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
if (args.length > 0) {
return waitpid(recv, args);
}
int[] status = new int[1];
int pid = runtime.getPosix().wait(status);
if (pid == -1) {
throw runtime.newErrnoECHILDError();
}
runtime.getGlobalVariables().set(
"$?",
RubyProcess.RubyStatus.newProcessStatus(runtime, status[0]));
return runtime.newFixnum(pid);
}
@JRubyMethod(name = "waitall", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject waitall(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
POSIX posix = runtime.getPosix();
RubyArray results = recv.getRuntime().newArray();
int[] status = new int[1];
int result = posix.wait(status);
while (result != -1) {
results.append(runtime.newArray(runtime.newFixnum(result), RubyProcess.RubyStatus.newProcessStatus(runtime, status[0])));
result = posix.wait(status);
}
return results;
}
@JRubyMethod(name = "setsid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setsid(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().setsid());
}
@JRubyMethod(name = "setpgrp", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setpgrp(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().setpgid(0, 0));
}
@JRubyMethod(name = "egid=", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject egid_set(IRubyObject recv, IRubyObject arg) {
recv.getRuntime().getPosix().setegid((int)arg.convertToInteger().getLongValue());
return RubyFixnum.zero(recv.getRuntime());
}
@JRubyMethod(name = "euid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject euid(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().geteuid());
}
@JRubyMethod(name = "uid=", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject uid_set(IRubyObject recv, IRubyObject arg) {
recv.getRuntime().getPosix().setuid((int)arg.convertToInteger().getLongValue());
return RubyFixnum.zero(recv.getRuntime());
}
@JRubyMethod(name = "gid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject gid(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().getgid());
}
@JRubyMethod(name = "maxgroups", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject maxgroups(IRubyObject recv) {
throw recv.getRuntime().newNotImplementedError("Process#maxgroups not yet implemented");
}
@JRubyMethod(name = "getpriority", required = 2, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject getpriority(IRubyObject recv, IRubyObject arg1, IRubyObject arg2) {
int which = (int)arg1.convertToInteger().getLongValue();
int who = (int)arg2.convertToInteger().getLongValue();
int result = recv.getRuntime().getPosix().getpriority(which, who);
return recv.getRuntime().newFixnum(result);
}
@JRubyMethod(name = "uid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject uid(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().getuid());
}
@JRubyMethod(name = "waitpid2", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject waitpid2(IRubyObject recv, IRubyObject[] args) {
Ruby runtime = recv.getRuntime();
int pid = -1;
int flags = 0;
if (args.length > 0) {
pid = (int)args[0].convertToInteger().getLongValue();
}
if (args.length > 1) {
flags = (int)args[1].convertToInteger().getLongValue();
}
int[] status = new int[1];
pid = runtime.getPosix().waitpid(pid, status, flags);
if (pid == -1) {
throw runtime.newErrnoECHILDError();
}
return runtime.newArray(runtime.newFixnum(pid), RubyProcess.RubyStatus.newProcessStatus(runtime, status[0]));
}
@JRubyMethod(name = "initgroups", required = 2, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject initgroups(IRubyObject recv, IRubyObject arg1, IRubyObject arg2) {
throw recv.getRuntime().newNotImplementedError("Process#initgroups not yet implemented");
}
@JRubyMethod(name = "maxgroups=", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject maxgroups_set(IRubyObject recv, IRubyObject arg) {
throw recv.getRuntime().newNotImplementedError("Process#maxgroups_set not yet implemented");
}
@JRubyMethod(name = "ppid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject ppid(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().getppid());
}
@JRubyMethod(name = "gid=", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject gid_set(IRubyObject recv, IRubyObject arg) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().setgid((int)arg.convertToInteger().getLongValue()));
}
@JRubyMethod(name = "wait2", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject wait2(IRubyObject recv, IRubyObject[] args) {
return waitpid2(recv, args);
}
@JRubyMethod(name = "euid=", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject euid_set(IRubyObject recv, IRubyObject arg) {
recv.getRuntime().getPosix().seteuid((int)arg.convertToInteger().getLongValue());
return RubyFixnum.zero(recv.getRuntime());
}
@JRubyMethod(name = "setpriority", required = 3, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setpriority(IRubyObject recv, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3) {
int which = (int)arg1.convertToInteger().getLongValue();
int who = (int)arg2.convertToInteger().getLongValue();
int prio = (int)arg3.convertToInteger().getLongValue();
int result = recv.getRuntime().getPosix().setpriority(which, who, prio);
return recv.getRuntime().newFixnum(result);
}
@JRubyMethod(name = "setpgid", required = 2, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject setpgid(IRubyObject recv, IRubyObject arg1, IRubyObject arg2) {
int pid = (int)arg1.convertToInteger().getLongValue();
int gid = (int)arg2.convertToInteger().getLongValue();
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().setpgid(pid, gid));
}
@JRubyMethod(name = "getpgid", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject getpgid(IRubyObject recv, IRubyObject arg) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().getpgid((int)arg.convertToInteger().getLongValue()));
}
@JRubyMethod(name = "getrlimit", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject getrlimit(IRubyObject recv, IRubyObject arg) {
throw recv.getRuntime().newNotImplementedError("Process#getrlimit not yet implemented");
}
@JRubyMethod(name = "egid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject egid(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().getegid());
}
private static String[] signals = new String[] {"EXIT", "HUP", "INT", "QUIT", "ILL", "TRAP",
"ABRT", "POLL", "FPE", "KILL", "BUS", "SEGV", "SYS", "PIPE", "ALRM", "TERM", "URG", "STOP",
"TSTP", "CONT", "CHLD", "TTIN", "TTOU", "XCPU", "XFSZ", "VTALRM", "PROF", "USR1", "USR2"};
private static int parseSignalString(Ruby runtime, String value) {
int startIndex = 0;
boolean negative = value.startsWith("-");
if (negative) startIndex++;
boolean signalString = value.startsWith("SIG", startIndex);
if (signalString) startIndex += 3;
String signalName = value.substring(startIndex);
// FIXME: This table will get moved into POSIX library so we can get all actual supported
// signals. This is a quick fix to support basic signals until that happens.
for (int i = 0; i < signals.length; i++) {
if (signals[i].equals(signalName)) return negative ? -i : i;
}
throw runtime.newArgumentError("unsupported name `SIG" + signalName + "'");
}
@JRubyMethod(name = "kill", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject kill(IRubyObject recv, IRubyObject[] args) {
if (args.length < 2) {
throw recv.getRuntime().newArgumentError("wrong number of arguments -- kill(sig, pid...)");
}
Ruby runtime = recv.getRuntime();
int signal;
if (args[0] instanceof RubyFixnum) {
signal = (int) ((RubyFixnum) args[0]).getLongValue();
} else if (args[0] instanceof RubySymbol) {
signal = parseSignalString(runtime, args[0].toString());
} else if (args[0] instanceof RubyString) {
signal = parseSignalString(runtime, args[0].toString());
} else {
signal = parseSignalString(runtime, args[0].checkStringType().toString());
}
boolean processGroupKill = signal < 0;
if (processGroupKill) signal = -signal;
POSIX posix = runtime.getPosix();
for (int i = 1; i < args.length; i++) {
int pid = RubyNumeric.num2int(args[i]);
// FIXME: It may be possible to killpg on systems which support it. POSIX library
// needs to tell whether a particular method works or not
if (pid == 0) pid = runtime.getPosix().getpid();
posix.kill(processGroupKill ? -pid : pid, signal);
}
return runtime.newFixnum(args.length - 1);
}
@JRubyMethod(name = "detach", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject detach(ThreadContext context, IRubyObject recv, IRubyObject arg) {
final int pid = (int)arg.convertToInteger().getLongValue();
Ruby runtime = recv.getRuntime();
BlockCallback callback = new BlockCallback() {
public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) {
int[] status = new int[1];
int result = context.getRuntime().getPosix().waitpid(pid, status, 0);
return context.getRuntime().newFixnum(result);
}
};
return RubyThread.newInstance(
runtime.getThread(),
IRubyObject.NULL_ARRAY,
CallBlock.newCallClosure(recv, (RubyModule)recv, Arity.NO_ARGUMENTS, callback, context));
}
@JRubyMethod(name = "times", frame = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject times(IRubyObject recv, Block unusedBlock) {
Ruby runtime = recv.getRuntime();
double currentTime = System.currentTimeMillis() / 1000.0;
double startTime = runtime.getStartTime() / 1000.0;
RubyFloat zero = runtime.newFloat(0.0);
return RubyStruct.newStruct(runtime.getTmsStruct(),
new IRubyObject[] { runtime.newFloat(currentTime - startTime), zero, zero, zero },
Block.NULL_BLOCK);
}
@JRubyMethod(name = "pid", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject pid(IRubyObject recv) {
return recv.getRuntime().newFixnum(recv.getRuntime().getPosix().getpid());
}
@JRubyMethod(name = "fork", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject fork(ThreadContext context, IRubyObject recv, Block block) {
return RubyKernel.fork(context, recv, block);
}
@JRubyMethod(name = "exit", optional = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject exit(IRubyObject recv, IRubyObject[] args) {
return RubyKernel.exit(recv, args);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001 Ed Sinjiashvili <slorcim@users.sourceforge.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.util.List;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.CallBlock;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ObjectMarshal;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
/**
* @author jpetersen
*/
@JRubyClass(name="Range", include="Enumerable")
public class RubyRange extends RubyObject {
private IRubyObject begin;
private IRubyObject end;
private boolean isExclusive;
public static RubyClass createRangeClass(Ruby runtime) {
RubyClass result = runtime.defineClass("Range", runtime.getObject(), RANGE_ALLOCATOR);
runtime.setRange(result);
result.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyRange;
}
};
result.setMarshal(RANGE_MARSHAL);
result.includeModule(runtime.getEnumerable());
// We override Enumerable#member? since ranges in 1.8.1 are continuous.
// result.defineMethod("member?", callbackFactory.getMethod("include_p", RubyKernel.IRUBY_OBJECT));
// result.defineMethod("===", callbackFactory.getMethod("include_p", RubyKernel.IRUBY_OBJECT));
result.defineAnnotatedMethods(RubyRange.class);
return result;
}
private static final ObjectAllocator RANGE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyRange(runtime, klass);
}
};
private RubyRange(Ruby runtime, RubyClass klass) {
super(runtime, klass);
begin = end = runtime.getNil();
}
public static RubyRange newRange(Ruby runtime, ThreadContext context, IRubyObject begin, IRubyObject end, boolean isExclusive) {
RubyRange range = new RubyRange(runtime, runtime.getRange());
range.init(context, begin, end, isExclusive);
return range;
}
public static RubyRange newExclusiveRange(Ruby runtime, ThreadContext context, IRubyObject begin, IRubyObject end) {
RubyRange range = new RubyRange(runtime, runtime.getRange());
range.init(context, begin, end, true);
return range;
}
public static RubyRange newInclusiveRange(Ruby runtime, ThreadContext context, IRubyObject begin, IRubyObject end) {
RubyRange range = new RubyRange(runtime, runtime.getRange());
range.init(context, begin, end, false);
return range;
}
protected void copySpecialInstanceVariables(IRubyObject clone) {
RubyRange range = (RubyRange)clone;
range.begin = begin;
range.end = end;
range.isExclusive = isExclusive;
}
final long[] begLen(long len, int err){
long beg = RubyNumeric.num2long(this.begin);
long end = RubyNumeric.num2long(this.end);
if (beg < 0) {
beg += len;
if (beg < 0) {
if (err != 0) throw getRuntime().newRangeError(beg + ".." + (isExclusive ? "." : "") + end + " out of range");
return null;
}
}
if (err == 0 || err == 2) {
if (beg > len) {
if (err != 0) throw getRuntime().newRangeError(beg + ".." + (isExclusive ? "." : "") + end + " out of range");
return null;
}
if (end > len) end = len;
}
if (end < 0) end += len;
if (!isExclusive) end++;
len = end - beg;
if (len < 0) len = 0;
return new long[]{beg, len};
}
private void init(ThreadContext context, IRubyObject begin, IRubyObject end, boolean isExclusive) {
if (!(begin instanceof RubyFixnum && end instanceof RubyFixnum)) {
try {
IRubyObject result = begin.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", end);
if (result.isNil()) throw getRuntime().newArgumentError("bad value for range");
} catch (RaiseException re) {
throw getRuntime().newArgumentError("bad value for range");
}
}
this.begin = begin;
this.end = end;
this.isExclusive = isExclusive;
}
@JRubyMethod(name = "initialize", required = 2, optional = 1, frame = true)
public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block unusedBlock) {
init(context, args[0], args[1], args.length > 2 && args[2].isTrue());
return getRuntime().getNil();
}
@JRubyMethod(name = {"first", "begin"})
public IRubyObject first() {
return begin;
}
@JRubyMethod(name = {"last", "end"})
public IRubyObject last() {
return end;
}
@JRubyMethod(name = "hash")
public RubyFixnum hash(ThreadContext context) {
long hash = isExclusive ? 1 : 0;
long h = hash;
long v = begin.callMethod(context, MethodIndex.HASH, "hash").convertToInteger().getLongValue();
hash ^= v << 1;
v = end.callMethod(context, MethodIndex.HASH, "hash").convertToInteger().getLongValue();
hash ^= v << 9;
hash ^= h << 24;
return getRuntime().newFixnum(hash);
}
private static byte[] DOTDOTDOT = "...".getBytes();
private static byte[] DOTDOT = "..".getBytes();
@JRubyMethod(name = "inspect")
public IRubyObject inspect(ThreadContext context) {
RubyString str = inspect(context, begin).strDup(context.getRuntime());
RubyString str2 = inspect(context, end);
str.cat(isExclusive ? DOTDOTDOT : DOTDOT);
str.concat(str2);
str.infectBy(str2);
return str;
}
@JRubyMethod(name = "to_s")
public IRubyObject to_s(ThreadContext context) {
RubyString str = RubyString.objAsString(context, begin).strDup(context.getRuntime());
RubyString str2 = RubyString.objAsString(context, end);
str.cat(isExclusive ? DOTDOTDOT : DOTDOT);
str.concat(str2);
str.infectBy(str2);
return str;
}
@JRubyMethod(name = "exclude_end?")
public RubyBoolean exclude_end_p() {
return getRuntime().newBoolean(isExclusive);
}
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
if (this == other) return getRuntime().getTrue();
if (!(other instanceof RubyRange)) return getRuntime().getFalse();
RubyRange otherRange = (RubyRange) other;
if (equalInternal(context, begin, otherRange.begin) &&
equalInternal(context, end, otherRange.end) &&
isExclusive == otherRange.isExclusive) return getRuntime().getTrue();
return getRuntime().getFalse();
}
@JRubyMethod(name = "eql?", required = 1)
public IRubyObject eql_p(ThreadContext context, IRubyObject other) {
if (this == other) return getRuntime().getTrue();
if (!(other instanceof RubyRange)) return getRuntime().getFalse();
RubyRange otherRange = (RubyRange)other;
if (eqlInternal(context, begin, otherRange.begin) &&
eqlInternal(context, end, otherRange.end) &&
isExclusive == otherRange.isExclusive) return getRuntime().getTrue();
return getRuntime().getFalse();
}
private static abstract class RangeCallBack {
abstract void call(ThreadContext context, IRubyObject arg);
}
private static final class StepBlockCallBack extends RangeCallBack implements BlockCallback {
final Block block;
IRubyObject iter;
final IRubyObject step;
StepBlockCallBack(Block block, IRubyObject iter, IRubyObject step) {
this.block = block;
this.iter = iter;
this.step = step;
}
public IRubyObject call(ThreadContext context, IRubyObject[] args, Block originalBlock) {
call(context, args[0]);
return context.getRuntime().getNil();
}
void call(ThreadContext context, IRubyObject arg) {
if (iter instanceof RubyFixnum) {
iter = RubyFixnum.newFixnum(context.getRuntime(), ((RubyFixnum)iter).getLongValue() - 1);
} else {
iter = iter.callMethod(context, MethodIndex.OP_MINUS, "-", RubyFixnum.one(context.getRuntime()));
}
if (iter == RubyFixnum.zero(context.getRuntime())) {
block.yield(context, arg);
iter = step;
}
}
}
private IRubyObject rangeLt(ThreadContext context, IRubyObject a, IRubyObject b) {
IRubyObject result = a.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", b);
if (result.isNil()) return null;
return RubyComparable.cmpint(context, result, a, b) < 0 ? getRuntime().getTrue() : null;
}
private IRubyObject rangeLe(ThreadContext context, IRubyObject a, IRubyObject b) {
IRubyObject result = a.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", b);
if (result.isNil()) return null;
int c = RubyComparable.cmpint(context, result, a, b);
if (c == 0) return RubyFixnum.zero(getRuntime());
return c < 0 ? getRuntime().getTrue() : null;
}
private void rangeEach(ThreadContext context, RangeCallBack callback) {
IRubyObject v = begin;
if (isExclusive) {
while (rangeLt(context, v, end) != null) {
callback.call(context, v);
v = v.callMethod(context, "succ");
}
} else {
IRubyObject c;
while ((c = rangeLe(context, v, end)) != null && c.isTrue()) {
callback.call(context, v);
if (c == RubyFixnum.zero(getRuntime())) break;
v = v.callMethod(context, "succ");
}
}
}
@JRubyMethod(name = "each", frame = true)
public IRubyObject each(ThreadContext context, final Block block) {
final Ruby runtime = context.getRuntime();
if (begin instanceof RubyFixnum && end instanceof RubyFixnum) {
long lim = ((RubyFixnum) end).getLongValue();
if (!isExclusive) lim++;
for (long i = ((RubyFixnum) begin).getLongValue(); i < lim; i++) {
block.yield(context, RubyFixnum.newFixnum(runtime, i));
}
} else if (begin instanceof RubyString) {
((RubyString) begin).upto(context, end, isExclusive, block);
} else {
if (!begin.respondsTo("succ")) throw getRuntime().newTypeError(
"can't iterate from " + begin.getMetaClass().getName());
rangeEach(context, new RangeCallBack() {
@Override
void call(ThreadContext context, IRubyObject arg) {
block.yield(context, arg);
}
});
}
return this;
}
@JRubyMethod(name = "step", optional = 1, frame = true)
public IRubyObject step(ThreadContext context, IRubyObject[] args, Block block) {
final Ruby runtime = context.getRuntime();
final IRubyObject step;
if (args.length == 0) {
step = RubyFixnum.one(runtime);
} else {
step = args[0];
}
long unit = RubyNumeric.num2long(step);
if (unit < 0) throw runtime.newArgumentError("step can't be negative");
if (begin instanceof RubyFixnum && end instanceof RubyFixnum) {
if (unit == 0) throw runtime.newArgumentError("step can't be 0");
long e = ((RubyFixnum)end).getLongValue();
if (!isExclusive) e++;
for (long i = ((RubyFixnum)begin).getLongValue(); i < e; i += unit) {
block.yield(context, RubyFixnum.newFixnum(runtime, i));
}
} else {
IRubyObject tmp = begin.checkStringType();
if (!tmp.isNil()) {
if (unit == 0) throw runtime.newArgumentError("step can't be 0");
// rb_iterate((VALUE(*)_((VALUE)))str_step, (VALUE)args, step_i, (VALUE)iter);
StepBlockCallBack callback = new StepBlockCallBack(block, RubyFixnum.one(runtime), step);
Block blockCallback = CallBlock.newCallClosure(this, runtime.getRange(), Arity.singleArgument(), callback, context);
((RubyString)tmp).upto(context, end, isExclusive, blockCallback);
} else if (begin instanceof RubyNumeric) {
if (equalInternal(context, step, RubyFixnum.zero(runtime))) {
throw runtime.newArgumentError("step can't be 0");
}
final String method;
final int methodIndex;
if (isExclusive) {
method = "<";
methodIndex = MethodIndex.OP_LT;
} else {
method = "<=";
methodIndex = MethodIndex.OP_LE;
}
IRubyObject beg = begin;
while (beg.callMethod(context, methodIndex, method, end).isTrue()) {
block.yield(context, beg);
beg = beg.callMethod(context, MethodIndex.OP_PLUS, "+", step);
}
} else {
if (unit == 0) throw runtime.newArgumentError("step can't be 0");
if (!begin.respondsTo("succ")) throw runtime.newTypeError(
"can't iterate from " + begin.getMetaClass().getName());
// range_each_func(range, step_i, b, e, args);
rangeEach(context, new StepBlockCallBack(block, RubyFixnum.one(runtime), step));
}
}
return this;
}
@JRubyMethod(name = {"include?", "member?", "==="}, required = 1)
public RubyBoolean include_p(ThreadContext context, IRubyObject obj) {
if (rangeLe(context, begin, obj) != null) {
if (isExclusive) {
if (rangeLt(context, obj, end) != null) return context.getRuntime().getTrue();
} else {
if (rangeLe(context, obj, end) != null) return context.getRuntime().getTrue();
}
}
return context.getRuntime().getFalse();
}
private static final ObjectMarshal RANGE_MARSHAL = new ObjectMarshal() {
public void marshalTo(Ruby runtime, Object obj, RubyClass type,
MarshalStream marshalStream) throws IOException {
RubyRange range = (RubyRange)obj;
marshalStream.registerLinkTarget(range);
List<Variable<IRubyObject>> attrs = range.getVariableList();
attrs.add(new VariableEntry<IRubyObject>("begin", range.begin));
attrs.add(new VariableEntry<IRubyObject>("end", range.end));
attrs.add(new VariableEntry<IRubyObject>("excl", range.isExclusive ? runtime.getTrue() : runtime.getFalse()));
marshalStream.dumpVariables(attrs);
}
public Object unmarshalFrom(Ruby runtime, RubyClass type,
UnmarshalStream unmarshalStream) throws IOException {
RubyRange range = (RubyRange)type.allocate();
unmarshalStream.registerLinkTarget(range);
unmarshalStream.defaultVariablesUnmarshal(range);
range.begin = range.removeInternalVariable("begin");
range.end = range.removeInternalVariable("end");
range.isExclusive = range.removeInternalVariable("excl").isTrue();
return range;
}
};
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.util.Numeric.f_add;
import static org.jruby.util.Numeric.f_cmp;
import static org.jruby.util.Numeric.f_div;
import static org.jruby.util.Numeric.f_equal_p;
import static org.jruby.util.Numeric.f_expt;
import static org.jruby.util.Numeric.f_floor;
import static org.jruby.util.Numeric.f_gcd;
import static org.jruby.util.Numeric.f_idiv;
import static org.jruby.util.Numeric.f_mul;
import static org.jruby.util.Numeric.f_negate;
import static org.jruby.util.Numeric.f_negative_p;
import static org.jruby.util.Numeric.f_one_p;
import static org.jruby.util.Numeric.f_rshift;
import static org.jruby.util.Numeric.f_sub;
import static org.jruby.util.Numeric.f_to_f;
import static org.jruby.util.Numeric.f_to_i;
import static org.jruby.util.Numeric.f_to_r;
import static org.jruby.util.Numeric.f_to_s;
import static org.jruby.util.Numeric.f_truncate;
import static org.jruby.util.Numeric.f_xor;
import static org.jruby.util.Numeric.f_zero_p;
import static org.jruby.util.Numeric.i_gcd;
import static org.jruby.util.Numeric.i_ilog2;
import static org.jruby.util.Numeric.ldexp;
import org.joni.encoding.specific.ASCIIEncoding;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.common.IRubyWarnings;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Arity;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.Frame;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.Numeric;
/**
* 1.9 rational.c as of revision: 18876
*/
@JRubyClass(name = "Rational", parent = "Numeric", include = "Precision")
public class RubyRational extends RubyNumeric {
public static RubyClass createRationalClass(Ruby runtime) {
RubyClass rationalc = runtime.defineClass("Rational", runtime.getNumeric(), RATIONAL_ALLOCATOR); // because one can Complex.send(:allocate)
runtime.setRational(rationalc);
rationalc.index = ClassIndex.RATIONAL;
rationalc.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyRational;
}
};
ThreadContext context = runtime.getCurrentContext();
rationalc.callMethod(context, "private_class_method", runtime.newSymbol("allocate"));
rationalc.defineAnnotatedMethods(RubyRational.class);
return rationalc;
}
private static ObjectAllocator RATIONAL_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyRational(runtime, klass, RubyFixnum.zero(runtime), RubyFixnum.one(runtime));
}
};
/** internal
*
*/
private RubyRational(Ruby runtime, IRubyObject clazz, IRubyObject num, IRubyObject den) {
super(runtime, (RubyClass)clazz);
this.num = num;
this.den = den;
}
/** rb_rational_raw
*
*/
static RubyRational newRationalRaw(Ruby runtime, IRubyObject x, RubyObject y) {
return new RubyRational(runtime, runtime.getRational(), x, y);
}
/** rb_rational_raw1
*
*/
static RubyRational newRationalRaw(Ruby runtime, IRubyObject x) {
return new RubyRational(runtime, runtime.getRational(), x, RubyFixnum.one(runtime));
}
/** rb_rational_new1
*
*/
static IRubyObject newRationalCanonicalize(ThreadContext context, IRubyObject x) {
return newRationalCanonicalize(context, x, RubyFixnum.one(context.getRuntime()));
}
/** rb_rational_new
*
*/
private static IRubyObject newRationalCanonicalize(ThreadContext context, IRubyObject x, IRubyObject y) {
return canonicalizeInternal(context, context.getRuntime().getRational(), x, y);
}
/** f_rational_new2
*
*/
private static IRubyObject newRational(ThreadContext context, IRubyObject clazz, IRubyObject x, IRubyObject y) {
assert x instanceof RubyRational && y instanceof RubyRational;
return canonicalizeInternal(context, clazz, x, y);
}
/** f_rational_new1
*
*/
private static IRubyObject newRational(ThreadContext context, IRubyObject clazz, IRubyObject x) {
assert x instanceof RubyRational;
return canonicalizeInternal(context, clazz, x, RubyFixnum.one(context.getRuntime()));
}
/** f_rational_new_no_reduce2
*
*/
private static IRubyObject newRationalNoReduce(ThreadContext context, IRubyObject clazz, IRubyObject x, IRubyObject y) {
assert x instanceof RubyRational && y instanceof RubyRational;
return canonicalizeInternalNoReduce(context, clazz, x, y);
}
/** f_rational_new_no_reduce1
*
*/
private static IRubyObject newRationalNoReduce(ThreadContext context, IRubyObject clazz, IRubyObject x) {
assert x instanceof RubyRational;
return canonicalizeInternalNoReduce(context, clazz, x, RubyFixnum.one(context.getRuntime()));
}
/** f_rational_new_bang2
*
*/
private static RubyRational newRationalBang(ThreadContext context, IRubyObject clazz, IRubyObject x, IRubyObject y) {
assert !f_negative_p(context, y) && !(f_zero_p(context, y));
return new RubyRational(context.getRuntime(), clazz, x, y);
}
/** f_rational_new_bang1
*
*/
private static RubyRational newRationalBang(ThreadContext context, IRubyObject clazz, IRubyObject x) {
return newRationalBang(context, clazz, x, RubyFixnum.one(context.getRuntime()));
}
private IRubyObject num;
private IRubyObject den;
/** nurat_s_new_bang
*
*/
@Deprecated
public static IRubyObject newInstanceBang(ThreadContext context, IRubyObject recv, IRubyObject[]args) {
switch (args.length) {
case 1: return newInstanceBang(context, recv, args[0]);
case 2: return newInstanceBang(context, recv, args[0], args[1]);
}
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 1);
return null;
}
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject newInstanceBang(ThreadContext context, IRubyObject recv, IRubyObject num) {
return newInstanceBang(context, recv, num, RubyFixnum.one(context.getRuntime()));
}
@JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject newInstanceBang(ThreadContext context, IRubyObject recv, IRubyObject num, IRubyObject den) {
if (!(num instanceof RubyInteger)) num = f_to_i(context, num);
if (!(den instanceof RubyInteger)) den = f_to_i(context, den);
Ruby runtime = context.getRuntime();
IRubyObject res = f_cmp(context, den, RubyFixnum.zero(runtime));
if (res == RubyFixnum.minus_one(runtime)) {
num = f_negate(context, num);
den = f_negate(context, den);
} else if (res == RubyFixnum.zero(runtime)) {
throw runtime.newZeroDivisionError();
}
return new RubyRational(runtime, recv, num, den);
}
/** nurat_int_check
*
*/
private static void intCheck(IRubyObject num) {
if (!(num instanceof RubyFixnum ) && !(num instanceof RubyBignum)) throw num.getRuntime().newArgumentError("not an integer");
}
/** nurat_s_canonicalize_internal
*
*/
private static IRubyObject canonicalizeInternal(ThreadContext context, IRubyObject clazz, IRubyObject num, IRubyObject den) {
Ruby runtime = context.getRuntime();
IRubyObject res = f_cmp(context, den, RubyFixnum.zero(runtime));
if (res == RubyFixnum.minus_one(runtime)) {
num = f_negate(context, num);
den = f_negate(context, den);
} else if (res == RubyFixnum.zero(runtime)) {
throw runtime.newZeroDivisionError();
}
IRubyObject gcd = f_gcd(context, num, den);
num = f_idiv(context, num, gcd);
den = f_idiv(context, den, gcd);
if (f_one_p(context, den) && ((RubyModule)clazz).fastHasConstant("Unify")) return num;
return new RubyRational(context.getRuntime(), clazz, num, den);
}
/** nurat_s_canonicalize_internal_no_reduce
*
*/
private static IRubyObject canonicalizeInternalNoReduce(ThreadContext context, IRubyObject clazz, IRubyObject num, IRubyObject den) {
Ruby runtime = context.getRuntime();
IRubyObject res = f_cmp(context, den, RubyFixnum.zero(runtime));
if (res == RubyFixnum.minus_one(runtime)) {
num = f_negate(context, num);
den = f_negate(context, den);
} else if (res == RubyFixnum.zero(runtime)) {
throw runtime.newZeroDivisionError();
}
if (f_equal_p(context, den, RubyFixnum.one(runtime)) && ((RubyModule)clazz).fastHasConstant("Unify")) return num;
return new RubyRational(context.getRuntime(), clazz, num, den);
}
/** nurat_s_new
*
*/
@Deprecated
public static IRubyObject newInstance(ThreadContext context, IRubyObject clazz, IRubyObject[]args) {
switch (args.length) {
case 1: return newInstance(context, clazz, args[0]);
case 2: return newInstance(context, clazz, args[0], args[1]);
}
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 1);
return null;
}
@JRubyMethod(name = "new", meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject clazz, IRubyObject num) {
intCheck(num);
return canonicalizeInternal(context, clazz, num, RubyFixnum.one(context.getRuntime()));
}
@JRubyMethod(name = "new", meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject clazz, IRubyObject num, IRubyObject den) {
intCheck(num);
intCheck(den);
return canonicalizeInternal(context, clazz, num, den);
}
/** rb_Rational1
*
*/
public static IRubyObject newRationalConvert(ThreadContext context, IRubyObject x) {
return newRationalConvert(context, x, RubyFixnum.one(context.getRuntime()));
}
/** rb_Rational/rb_Rational2
*
*/
public static IRubyObject newRationalConvert(ThreadContext context, IRubyObject x, IRubyObject y) {
return convert(context, context.getRuntime().getRational(), x, y);
}
@Deprecated
public static IRubyObject convert(ThreadContext context, IRubyObject clazz, IRubyObject[]args) {
switch (args.length) {
case 0: return convert(context, clazz);
case 1: return convert(context, clazz, args[0]);
case 2: return convert(context, clazz, args[0], args[1]);
}
Arity.raiseArgumentError(context.getRuntime(), args.length, 0, 2);
return null;
}
/** nurat_s_convert
*
*/
@JRubyMethod(name = "convert", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject convert(ThreadContext context, IRubyObject recv) {
IRubyObject nil = context.getRuntime().getNil();
return convertCommon(context, recv, nil, nil);
}
/** nurat_s_convert
*
*/
@JRubyMethod(name = "convert", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject convert(ThreadContext context, IRubyObject recv, IRubyObject a1) {
return convertCommon(context, recv, a1, context.getRuntime().getNil());
}
/** nurat_s_convert
*
*/
@JRubyMethod(name = "convert", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject convert(ThreadContext context, IRubyObject recv, IRubyObject a1, IRubyObject a2) {
return convertCommon(context, recv, a1, a2);
}
private static IRubyObject convertCommon(ThreadContext context, IRubyObject recv, IRubyObject a1, IRubyObject a2) {
if (a1 instanceof RubyComplex) {
RubyComplex a1Complex = (RubyComplex)a1;
if (a1Complex.getImage() instanceof RubyFloat || !f_zero_p(context, a1Complex.getImage())) {
IRubyObject s = f_to_s(context, a1);
throw context.getRuntime().newArgumentError("can't accept " + s.convertToString());
}
a1 = a1Complex.getReal();
}
if (a2 instanceof RubyComplex) {
RubyComplex a2Complex = (RubyComplex)a2;
if (a2Complex.getImage() instanceof RubyFloat || !f_zero_p(context, a2Complex.getImage())) {
IRubyObject s = f_to_s(context, a2);
throw context.getRuntime().newArgumentError("can't accept " + s.convertToString());
}
a2 = a2Complex.getReal();
}
Frame frame = context.getCurrentFrame();
IRubyObject backref = frame.getBackRef();
if (backref != null && backref instanceof RubyMatchData) ((RubyMatchData)backref).use();
if (a1 instanceof RubyFloat) {
a1 = f_to_r(context, a1);
} else if (a1 instanceof RubyString) {
a1 = str_to_r_strict(context, a1);
}
if (a2 instanceof RubyFloat) {
a2 = f_to_r(context, a2);
} else if (a2 instanceof RubyString) {
a2 = str_to_r_strict(context, a2);
}
frame.setBackRef(backref);
if (a1 instanceof RubyRational) {
if (a2.isNil() || f_zero_p(context, a2)) return a1;
return f_div(context, a1, a2);
}
if (a2 instanceof RubyRational) {
return f_div(context, a1, a2);
}
return a2.isNil() ? newInstance(context, recv, a1) : newInstance(context, recv, a1, a2);
}
/** nurat_s_induced_from
*
*/
@JRubyMethod(name = "induced_from", meta = true)
public static IRubyObject induced_from(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return f_to_r(context, arg);
}
/** nurat_numerator
*
*/
@JRubyMethod(name = "numerator")
public IRubyObject numerator(ThreadContext context) {
return num;
}
/** nurat_denominator
*
*/
@JRubyMethod(name = "denominator")
public IRubyObject denominator(ThreadContext context) {
return den;
}
/** f_imul
*
*/
private static IRubyObject f_imul(ThreadContext context, long a, long b) {
Ruby runtime = context.getRuntime();
if (a == 0 || b == 0) {
return RubyFixnum.zero(runtime);
} else if (a == 1) {
return RubyFixnum.newFixnum(runtime, b);
} else if (b == 1) {
return RubyFixnum.newFixnum(runtime, a);
}
long c = a * b;
if(c / a != b) {
return RubyBignum.newBignum(runtime, a).op_mul(context, RubyBignum.newBignum(runtime, b));
}
return RubyFixnum.newFixnum(runtime, c);
}
/** f_addsub
*
*/
private IRubyObject f_addsub(ThreadContext context, IRubyObject anum, IRubyObject aden, IRubyObject bnum, IRubyObject bden, boolean plus) {
Ruby runtime = context.getRuntime();
IRubyObject num, den, g, a, b;
if (anum instanceof RubyFixnum && aden instanceof RubyFixnum &&
bnum instanceof RubyFixnum && bden instanceof RubyFixnum) {
long an = ((RubyFixnum)anum).getLongValue();
long ad = ((RubyFixnum)aden).getLongValue();
long bn = ((RubyFixnum)bnum).getLongValue();
long bd = ((RubyFixnum)bden).getLongValue();
long ig = i_gcd(ad, bd);
g = RubyFixnum.newFixnum(runtime, ig);
a = f_imul(context, an, bd / ig);
b = f_imul(context, bn, ad / ig);
} else {
g = f_gcd(context, aden, bden);
a = f_mul(context, anum, f_idiv(context, bden, g));
b = f_mul(context, bnum, f_idiv(context, aden, g));
}
IRubyObject c = plus ? f_add(context, a, b) : f_sub(context, a, b);
b = f_idiv(context, aden, g);
g = f_gcd(context, c, g);
num = f_idiv(context, c, g);
a = f_idiv(context, bden, g);
den = f_mul(context, a, b);
return RubyRational.newRationalNoReduce(context, getMetaClass(), num, den);
}
/** nurat_add
*
*/
@JRubyMethod(name = "+")
public IRubyObject op_add(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
return f_addsub(context, num, den, other, RubyFixnum.one(context.getRuntime()), true);
case ClassIndex.FLOAT:
return f_add(context, f_to_f(context, this), other);
case ClassIndex.RATIONAL:
RubyRational otherRational = (RubyRational)other;
return f_addsub(context, num, den, otherRational.num, otherRational.den, true);
}
return coerceBin(context, "+", other);
}
/** nurat_sub
*
*/
@JRubyMethod(name = "-")
public IRubyObject op_sub(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
return f_addsub(context, num, den, other, RubyFixnum.one(context.getRuntime()), false);
case ClassIndex.FLOAT:
return f_sub(context, f_to_f(context, this), other);
case ClassIndex.RATIONAL:
RubyRational otherRational = (RubyRational)other;
return f_addsub(context, num, den, otherRational.num, otherRational.den, false);
}
return coerceBin(context, "-", other);
}
/** f_muldiv
*
*/
private IRubyObject f_muldiv(ThreadContext context, IRubyObject anum, IRubyObject aden, IRubyObject bnum, IRubyObject bden, boolean mult) {
if (!mult) {
if (f_negative_p(context, bnum)) {
anum = f_negate(context, anum);
bnum = f_negate(context, bnum);
}
IRubyObject tmp = bnum;
bnum = bden;
bden = tmp;
}
final IRubyObject num, den;
if (anum instanceof RubyFixnum && aden instanceof RubyFixnum &&
bnum instanceof RubyFixnum && bden instanceof RubyFixnum) {
long an = ((RubyFixnum)anum).getLongValue();
long ad = ((RubyFixnum)aden).getLongValue();
long bn = ((RubyFixnum)bnum).getLongValue();
long bd = ((RubyFixnum)bden).getLongValue();
long g1 = i_gcd(an, bd);
long g2 = i_gcd(ad, bn);
num = f_imul(context, an / g1, bn / g2);
den = f_imul(context, ad / g2, bd / g1);
} else {
IRubyObject g1 = f_gcd(context, anum, bden);
IRubyObject g2 = f_gcd(context, aden, bnum);
num = f_mul(context, f_idiv(context, anum, g1), f_idiv(context, bnum, g2));
den = f_mul(context, f_idiv(context, aden, g2), f_idiv(context, bden, g1));
}
return RubyRational.newRationalNoReduce(context, getMetaClass(), num, den);
}
/** nurat_mul
*
*/
@JRubyMethod(name = "*")
public IRubyObject op_mul(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
return f_muldiv(context, num, den, other, RubyFixnum.one(context.getRuntime()), true);
case ClassIndex.FLOAT:
return f_mul(context, f_to_f(context, this), other);
case ClassIndex.RATIONAL:
RubyRational otherRational = (RubyRational)other;
return f_muldiv(context, num, den, otherRational.num, otherRational.den, true);
}
return coerceBin(context, "*", other);
}
/** nurat_div
*
*/
@JRubyMethod(name = "/")
public IRubyObject op_div(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
if (f_zero_p(context, other)) throw context.getRuntime().newZeroDivisionError();
return f_muldiv(context, num, den, other, RubyFixnum.one(context.getRuntime()), false);
case ClassIndex.FLOAT:
return f_to_f(context, this).callMethod(context, "/", other);
case ClassIndex.RATIONAL:
if (f_zero_p(context, other)) throw context.getRuntime().newZeroDivisionError();
RubyRational otherRational = (RubyRational)other;
return f_muldiv(context, num, den, otherRational.num, otherRational.den, false);
}
return coerceBin(context, "/", other);
}
/** nurat_fdiv
*
*/
@JRubyMethod(name = "fdiv")
public IRubyObject op_fdiv(ThreadContext context, IRubyObject other) {
return f_div(context, f_to_f(context, this), other);
}
/** nurat_expt
*
*/
@JRubyMethod(name = "**")
public IRubyObject op_expt(ThreadContext context, IRubyObject other) {
Ruby runtime = context.getRuntime();
if (f_zero_p(context, other)) {
return RubyRational.newRationalBang(context, getMetaClass(), RubyFixnum.one(runtime));
}
if (other instanceof RubyRational) {
RubyRational otherRational = (RubyRational)other;
if (f_one_p(context, otherRational.den)) other = otherRational.num;
}
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
final IRubyObject tnum, tden;
IRubyObject res = f_cmp(context, other, RubyFixnum.zero(runtime));
if (res == RubyFixnum.one(runtime)) {
tnum = f_expt(context, num, other);
tden = f_expt(context, den, other);
} else if (res == RubyFixnum.minus_one(runtime)){
tnum = f_expt(context, den, f_negate(context, other));
tden = f_expt(context, num, f_negate(context, other));
} else {
tnum = tden = RubyFixnum.one(runtime);
}
return RubyRational.newRational(context, getMetaClass(), tnum, tden);
case ClassIndex.FLOAT:
case ClassIndex.RATIONAL:
return f_expt(context, f_to_f(context, this), other);
}
return coerceBin(context, "**", other);
}
/** nurat_cmp
*
*/
@JRubyMethod(name = "<=>")
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
if (den instanceof RubyFixnum && ((RubyFixnum)den).getLongValue() == 1) return f_cmp(context, num, other);
return f_cmp(context, this, RubyRational.newRationalBang(context, getMetaClass(), other));
case ClassIndex.FLOAT:
return f_cmp(context, f_to_f(context, this), other);
case ClassIndex.RATIONAL:
RubyRational otherRational = (RubyRational)other;
final IRubyObject num1, num2;
if (num instanceof RubyFixnum && den instanceof RubyFixnum &&
otherRational.num instanceof RubyFixnum && otherRational.den instanceof RubyFixnum) {
num1 = f_imul(context, ((RubyFixnum)num).getLongValue(), ((RubyFixnum)otherRational.den).getLongValue());
num2 = f_imul(context, ((RubyFixnum)otherRational.num).getLongValue(), ((RubyFixnum)den).getLongValue());
} else {
num1 = f_mul(context, num, otherRational.den);
num2 = f_mul(context, otherRational.num, den);
}
return f_cmp(context, f_sub(context, num1, num2), RubyFixnum.zero(context.getRuntime()));
}
return coerceBin(context, "<=>", other);
}
/** nurat_equal_p
*
*/
@JRubyMethod(name = "==")
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
Ruby runtime = context.getRuntime();
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
if (f_zero_p(context, num) && f_zero_p(context, den)) return runtime.getTrue();
if (!(den instanceof RubyFixnum) || ((RubyFixnum)den).getLongValue() != 1) return runtime.getFalse();
if (f_equal_p(context, num, other)) return runtime.getTrue();
return runtime.getFalse();
case ClassIndex.FLOAT:
return f_equal_p(context, f_to_f(context, this), other) ? runtime.getTrue() : runtime.getFalse();
case ClassIndex.RATIONAL:
RubyRational otherRational = (RubyRational)other;
if (f_zero_p(context, num) && f_zero_p(context, otherRational.num)) return runtime.getTrue();
if (f_equal_p(context, num, otherRational.num) && f_equal_p(context, den, otherRational.den)) return runtime.getTrue();
return runtime.getFalse();
}
return f_equal_p(context, other, this) ? runtime.getTrue() : runtime.getFalse();
}
/** nurat_coerce
*
*/
@JRubyMethod(name = "coerce")
public IRubyObject op_coerce(ThreadContext context, IRubyObject other) {
Ruby runtime = context.getRuntime();
switch (other.getMetaClass().index) {
case ClassIndex.FIXNUM:
case ClassIndex.BIGNUM:
return runtime.newArray(RubyRational.newRationalBang(context, getMetaClass(), other), this);
case ClassIndex.FLOAT:
return runtime.newArray(other, f_to_f(context, this));
}
throw runtime.newTypeError(other.getMetaClass() + " can't be coerced into " + getMetaClass());
}
/** nurat_idiv
*
*/
@JRubyMethod(name = "div")
public IRubyObject op_idiv(ThreadContext context, IRubyObject other) {
return f_floor(context, f_div(context, this, other));
}
/** nurat_mod
*
*/
@JRubyMethod(name = {"modulo", "%"})
public IRubyObject op_mod(ThreadContext context, IRubyObject other) {
IRubyObject val = f_floor(context, f_div(context, this, other));
return f_sub(context, this, f_mul(context, other, val));
}
/** nurat_divmod
*
*/
@JRubyMethod(name = "divmod")
public IRubyObject op_divmod(ThreadContext context, IRubyObject other) {
IRubyObject val = f_floor(context, f_div(context, this, other));
return context.getRuntime().newArray(val, f_sub(context, this, f_mul(context, other, val)));
}
/** nurat_rem
*
*/
@JRubyMethod(name = "remainder")
public IRubyObject op_rem(ThreadContext context, IRubyObject other) {
IRubyObject val = f_truncate(context, f_div(context, this, other));
return f_sub(context, this, f_mul(context, other, val));
}
/** nurat_abs
*
*/
@JRubyMethod(name = "abs")
public IRubyObject op_abs(ThreadContext context) {
if (!f_negative_p(context, this)) return this;
return f_negate(context, this);
}
/** nurat_floor
*
*/
@JRubyMethod(name = "floor")
public IRubyObject op_floor(ThreadContext context) {
return f_idiv(context, num, den);
}
/** nurat_ceil
*
*/
@JRubyMethod(name = "ceil")
public IRubyObject op_ceil(ThreadContext context) {
return f_negate(context, f_idiv(context, f_negate(context, num), den));
}
/** nurat_truncate
*
*/
@JRubyMethod(name = {"truncate", "to_i"})
public IRubyObject op_truncate(ThreadContext context) {
if (f_negative_p(context, num)) {
return f_negate(context, f_idiv(context, f_negate(context, num), den));
}
return f_idiv(context, num, den);
}
/** nurat_round
*
*/
@JRubyMethod(name = "round")
public IRubyObject op_round(ThreadContext context) {
IRubyObject two = RubyFixnum.two(context.getRuntime());
if (f_negative_p(context, num)) {
IRubyObject tnum = f_negate(context, num);
tnum = f_add(context, f_mul(context, tnum, two), den);
IRubyObject tden = f_mul(context, den, two);
return f_negate(context, f_idiv(context, tnum, tden));
} else {
IRubyObject tnum = f_add(context, f_mul(context, num, two), den);
IRubyObject tden = f_mul(context, den, two);
return f_idiv(context, tnum, tden);
}
}
/** nurat_to_f
*
*/
private static long ML = (long)(Math.log(Double.MAX_VALUE) / Math.log(2.0) - 1);
@JRubyMethod(name = "to_f")
public IRubyObject to_f(ThreadContext context) {
Ruby runtime = context.getRuntime();
if (f_zero_p(context, num)) return runtime.newFloat(0);
IRubyObject num = this.num;
IRubyObject den = this.den;
boolean minus = false;
if (f_negative_p(context, num)) {
num = f_negate(context, num);
minus = true;
}
long nl = i_ilog2(context, num);
long dl = i_ilog2(context, den);
long ne = 0;
if (nl > ML) {
ne = nl - ML;
num = f_rshift(context, num, RubyFixnum.newFixnum(runtime, ne));
}
long de = 0;
if (dl > ML) {
de = dl - ML;
den = f_rshift(context, den, RubyFixnum.newFixnum(runtime, de));
}
long e = ne - de;
if (e > 1023 || e < -1022) {
runtime.getWarnings().warn(IRubyWarnings.ID.FLOAT_OUT_OF_RANGE, "out of Float range", getMetaClass());
return runtime.newFloat(e > 0 ? Double.MAX_VALUE : 0);
}
double f = RubyNumeric.num2dbl(num) / RubyNumeric.num2dbl(den);
if (minus) {
f = -f;
f = ldexp(f, e);
}
if (Double.isInfinite(f) || Double.isNaN(f)) {
runtime.getWarnings().warn(IRubyWarnings.ID.FLOAT_OUT_OF_RANGE, "out of Float range", getMetaClass());
}
return runtime.newFloat(f);
}
/** nurat_to_r
*
*/
@JRubyMethod(name = "to_r")
public IRubyObject to_r(ThreadContext context) {
return this;
}
/** nurat_to_r
*
*/
@JRubyMethod(name = "hash")
public IRubyObject hash(ThreadContext context) {
return f_xor(context, num, den);
}
/** nurat_to_s
*
*/
@JRubyMethod(name = "to_s")
public IRubyObject to_s(ThreadContext context) {
return RuntimeHelpers.invoke(context, context.getRuntime().getKernel(), "format", context.getRuntime().newString("%d/%d"), num, den);
}
/** nurat_inspect
*
*/
@JRubyMethod(name = "inspect")
public IRubyObject inspect(ThreadContext context) {
return RuntimeHelpers.invoke(context, context.getRuntime().getKernel(), "format", context.getRuntime().newString("(%d/%d)"), num, den);
}
/** nurat_marshal_dump
*
*/
@JRubyMethod(name = "marshal_dump")
public IRubyObject marshal_dump(ThreadContext context) {
return context.getRuntime().newArray(num, den);
}
/** nurat_marshal_load
*
*/
@JRubyMethod(name = "marshal_load")
public IRubyObject marshal_load(ThreadContext context, IRubyObject arg) {
RubyArray a = arg.convertToArray();
num = a.size() > 0 ? a.eltInternal(0) : context.getRuntime().getNil();
den = a.size() > 1 ? a.eltInternal(1) : context.getRuntime().getNil();
if (f_zero_p(context, den)) throw context.getRuntime().newZeroDivisionError();
return this;
}
/** rb_gcd
*
*/
@JRubyMethod(name = "gcd")
public IRubyObject gcd(ThreadContext context, IRubyObject other) {
intCheck(other);
return f_gcd(context, this, other);
}
/** rb_lcm
*
*/
@JRubyMethod(name = "lcm")
public IRubyObject lcm(ThreadContext context, IRubyObject other) {
intCheck(other);
return Numeric.f_lcm(context, this, other);
}
/** rb_gcdlcm
*
*/
@JRubyMethod(name = "gcdlcm")
public IRubyObject gcdlcm(ThreadContext context, IRubyObject other) {
intCheck(other);
return context.getRuntime().newArray(f_gcd(context, this, other), Numeric.f_lcm(context, this, other));
}
static RubyArray str_to_r_internal(ThreadContext context, IRubyObject recv) {
RubyString s = recv.callMethod(context, "strip").convertToString();
ByteList bytes = s.getByteList();
Ruby runtime = context.getRuntime();
if (bytes.realSize == 0) return runtime.newArray(runtime.getNil(), recv);
IRubyObject m = RubyRegexp.newRegexp(runtime, Numeric.RationalPatterns.rat_pat).callMethod(context, "match", s);
if (!m.isNil()) {
IRubyObject si = m.callMethod(context, "[]", RubyFixnum.one(runtime));
IRubyObject nu = m.callMethod(context, "[]", RubyFixnum.two(runtime));
IRubyObject de = m.callMethod(context, "[]", RubyFixnum.three(runtime));
IRubyObject re = m.callMethod(context, "post_match");
RubyArray a = nu.callMethod(context, "split", RubyRegexp.newRegexp(runtime, Numeric.RationalPatterns.an_e_pat)).convertToArray();
IRubyObject ifp = a.eltInternal(0);
IRubyObject exp = a.size() != 2 ? runtime.getNil() : a.eltInternal(1);
a = ifp.callMethod(context, "split", RubyRegexp.newRegexp(runtime, Numeric.RationalPatterns.a_dot_pat)).convertToArray();
IRubyObject ip = a.eltInternal(0);
IRubyObject fp = a.size() != 2 ? runtime.getNil() : a.eltInternal(1);
IRubyObject v = RubyRational.newRationalCanonicalize(context, f_to_i(context, ip));
if (!fp.isNil()) {
bytes = fp.convertToString().getByteList();
int count = 0;
byte[]buf = bytes.bytes;
int i = bytes.begin;
int end = i + bytes.realSize;
while (i < end) if (ASCIIEncoding.INSTANCE.isDigit(buf[i++])) count++;
IRubyObject l = f_expt(context, RubyFixnum.newFixnum(runtime, 10), RubyFixnum.newFixnum(runtime, count));
v = f_mul(context, v, l);
v = f_add(context, v, f_to_i(context, fp));
v = f_div(context, v, l);
}
if (!exp.isNil()) {
v = f_mul(context, v, f_expt(context, RubyFixnum.newFixnum(runtime, 10), f_to_i(context, exp)));
}
if (!si.isNil()) {
bytes = si.convertToString().getByteList();
if (bytes.length() > 0 && bytes.get(0) == '-') v = f_negate(context, v);
}
if (!de.isNil()) {
v = f_div(context, v, f_to_i(context, de));
}
return runtime.newArray(v, re);
}
return runtime.newArray(runtime.getNil(), recv);
}
private static IRubyObject str_to_r_strict(ThreadContext context, IRubyObject recv) {
RubyArray a = str_to_r_internal(context, recv);
if (a.eltInternal(0).isNil() || a.eltInternal(1).convertToString().getByteList().length() > 0) {
IRubyObject s = recv.callMethod(context, "inspect");
throw context.getRuntime().newArgumentError("invalid value for Rational: " + s.convertToString());
}
return a.eltInternal(0);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 David Corbin <dcorbin@users.sourceforge.net>
* Copyright (C) 2006 Nick Sieger <nicksieger@gmail.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
import java.util.Map;
import org.joni.Matcher;
import org.joni.NameEntry;
import org.joni.Option;
import org.joni.Regex;
import org.joni.Region;
import org.joni.Syntax;
import org.joni.WarnCallback;
import org.joni.encoding.Encoding;
import org.joni.exception.JOniException;
import static org.jruby.anno.FrameField.*;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.parser.ReOptions;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.Frame;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.KCode;
import org.jruby.util.TypeConverter;
/**
*
*/
@JRubyClass(name="Regexp")
public class RubyRegexp extends RubyObject implements ReOptions, WarnCallback {
private KCode kcode;
private Regex pattern;
private ByteList str;
private static final int REGEXP_LITERAL_F = 1 << 11;
private static final int REGEXP_KCODE_DEFAULT = 1 << 12;
public void setLiteral() {
flags |= REGEXP_LITERAL_F;
}
public void clearLiteral() {
flags &= ~REGEXP_LITERAL_F;
}
public boolean isLiteral() {
return (flags & REGEXP_LITERAL_F) != 0;
}
public void setKCodeDefault() {
flags |= REGEXP_KCODE_DEFAULT;
}
public void clearKCodeDefault() {
flags &= ~REGEXP_KCODE_DEFAULT;
}
public boolean isKCodeDefault() {
return (flags & REGEXP_KCODE_DEFAULT) != 0;
}
public KCode getKCode() {
return kcode;
}
private static Map<ByteList, Regex> getPatternCache() {
Map<ByteList, Regex> cache = patternCache.get();
if (cache == null) {
cache = new ConcurrentHashMap<ByteList, Regex>(5);
patternCache = new SoftReference<Map<ByteList, Regex>>(cache);
}
return cache;
}
static volatile SoftReference<Map<ByteList, Regex>> patternCache = new SoftReference<Map<ByteList, Regex>>(null);
public static RubyClass createRegexpClass(Ruby runtime) {
RubyClass regexpClass = runtime.defineClass("Regexp", runtime.getObject(), REGEXP_ALLOCATOR);
runtime.setRegexp(regexpClass);
regexpClass.index = ClassIndex.REGEXP;
regexpClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyRegexp;
}
};
regexpClass.defineConstant("IGNORECASE", runtime.newFixnum(RE_OPTION_IGNORECASE));
regexpClass.defineConstant("EXTENDED", runtime.newFixnum(RE_OPTION_EXTENDED));
regexpClass.defineConstant("MULTILINE", runtime.newFixnum(RE_OPTION_MULTILINE));
regexpClass.defineAnnotatedMethods(RubyRegexp.class);
return regexpClass;
}
private static ObjectAllocator REGEXP_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyRegexp instance = new RubyRegexp(runtime, klass);
return instance;
}
};
/** used by allocator
*
*/
private RubyRegexp(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
/** default constructor
*
*/
private RubyRegexp(Ruby runtime) {
super(runtime, runtime.getRegexp());
}
// used only by the compiler/interpreter (will set the literal flag)
public static RubyRegexp newRegexp(Ruby runtime, String pattern, int options) {
return newRegexp(runtime, ByteList.create(pattern), options);
}
// used only by the compiler/interpreter (will set the literal flag)
public static RubyRegexp newRegexp(Ruby runtime, ByteList pattern, int options) {
RubyRegexp regexp = newRegexp(runtime, pattern, options, false);
regexp.setLiteral();
return regexp;
}
public static RubyRegexp newRegexp(Ruby runtime, ByteList pattern, int options, boolean quote) {
RubyRegexp regexp = new RubyRegexp(runtime);
regexp.initialize(pattern, options, quote);
return regexp;
}
// internal usage
static RubyRegexp newRegexp(Ruby runtime, Regex regex) {
RubyRegexp regexp = new RubyRegexp(runtime);
regexp.pattern = regex;
regexp.str = ByteList.EMPTY_BYTELIST;
return regexp;
}
public void warn(String message) {
getRuntime().getWarnings().warn(ID.MISCELLANEOUS, message);
}
@JRubyMethod(name = "kcode")
public IRubyObject kcode(ThreadContext context) {
return (!isKCodeDefault() && kcode != null) ?
context.getRuntime().newString(kcode.name()) : context.getRuntime().getNil();
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.REGEXP;
}
public Regex getPattern() {
return pattern;
}
private void check() {
if (pattern == null || str == null) throw getRuntime().newTypeError("uninitialized Regexp");
}
@JRubyMethod(name = "hash")
@Override
public RubyFixnum hash() {
check();
int hashval = (int)pattern.getOptions();
int len = this.str.realSize;
int p = this.str.begin;
while (len-->0) {
hashval = hashval * 33 + str.bytes[p++];
}
hashval = hashval + (hashval>>5);
return getRuntime().newFixnum(hashval);
}
@JRubyMethod(name = {"==", "eql?"}, required = 1)
@Override
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
if(this == other) return context.getRuntime().getTrue();
if(!(other instanceof RubyRegexp)) return context.getRuntime().getFalse();
RubyRegexp otherRegex = (RubyRegexp)other;
check();
otherRegex.check();
return context.getRuntime().newBoolean(str.equal(otherRegex.str) &&
kcode == otherRegex.kcode && pattern.getOptions() == otherRegex.pattern.getOptions());
}
@JRubyMethod(name = "~", reads = {LASTLINE, BACKREF}, writes = BACKREF)
public IRubyObject op_match2(ThreadContext context) {
Ruby runtime = context.getRuntime();
IRubyObject line = context.getCurrentFrame().getLastLine();
if(!(line instanceof RubyString)) {
context.getCurrentFrame().setBackRef(runtime.getNil());
return runtime.getNil();
}
int start = search(context, (RubyString)line, 0, false);
if(start < 0) {
return runtime.getNil();
} else {
return runtime.newFixnum(start);
}
}
/** rb_reg_eqq
*
*/
@JRubyMethod(name = "===", required = 1, writes = BACKREF)
public IRubyObject eqq(ThreadContext context, IRubyObject str) {
Ruby runtime = context.getRuntime();
if(!(str instanceof RubyString)) str = str.checkStringType();
if (str.isNil()) {
context.getCurrentFrame().setBackRef(runtime.getNil());
return runtime.getFalse();
}
int start = search(context, (RubyString)str, 0, false);
return (start < 0) ? runtime.getFalse() : runtime.getTrue();
}
private static final int REGEX_QUOTED = 1;
private void initialize(ByteList bytes, int options, boolean quote) {
if (!isTaint() && getRuntime().getSafeLevel() >= 4) throw getRuntime().newSecurityError("Insecure: can't modify regexp");
checkFrozen();
if (isLiteral()) throw getRuntime().newSecurityError("can't modify literal regexp");
setKCode(options);
Map<ByteList, Regex> cache = getPatternCache();
Regex pat = cache.get(bytes);
if (pat != null &&
pat.getEncoding() == kcode.getEncoding() &&
pat.getOptions() == (options & 0xf) &&
((pat.getUserOptions() & REGEX_QUOTED) != 0) == quote) { // cache hit
pattern = pat;
} else {
if (quote) bytes = quote(bytes, getRuntime().getKCode());
makeRegexp(bytes, bytes.begin, bytes.realSize, options & 0xf, kcode.getEncoding());
if (quote) pattern.setUserOptions(REGEX_QUOTED);
cache.put(bytes, pattern);
}
str = bytes;
}
private void makeRegexp(ByteList bytes, int start, int len, int flags, Encoding enc) {
try {
pattern = new Regex(bytes.bytes, start, start + len, flags, enc, Syntax.DEFAULT, this);
} catch(Exception e) {
rb_reg_raise(bytes.bytes, start, len, e.getMessage(), flags);
}
}
private final void rb_reg_raise(byte[] s, int start, int len, String err,int flags) {
throw getRuntime().newRegexpError(err + ": " + rb_reg_desc(s,start, len,flags));
}
private final StringBuilder rb_reg_desc(byte[] s, int start, int len, int flags) {
StringBuilder sb = new StringBuilder("/");
rb_reg_expr_str(sb, s, start, len);
sb.append("/");
if((flags & ReOptions.RE_OPTION_MULTILINE) != 0) sb.append("m");
if((flags & ReOptions.RE_OPTION_IGNORECASE) != 0) sb.append("i");
if((flags & ReOptions.RE_OPTION_EXTENDED) != 0) sb.append("x");
if (kcode != null && !isKCodeDefault()) {
sb.append(kcode.name().charAt(0));
}
return sb;
}
private final void rb_reg_expr_str(StringBuilder sb, byte[] s, int start, int len) {
int p,pend;
boolean need_escape = false;
p = start;
pend = start+len;
Encoding enc = kcode.getEncoding();
while(p<pend) {
if(s[p] == '/' || (!(' ' == s[p] || (!Character.isWhitespace(s[p]) &&
!Character.isISOControl(s[p]))) &&
enc.length(s[p])==1)) {
need_escape = true;
break;
}
p += enc.length(s[p]);
}
if(!need_escape) {
sb.append(new ByteList(s,start,len,false).toString());
} else {
p = 0;
while(p < pend) {
if(s[p] == '\\') {
int n = enc.length(s[p+1]) + 1;
sb.append(new ByteList(s,p,n,false).toString());
p += n;
continue;
} else if(s[p] == '/') {
sb.append("\\/");
} else if(enc.length(s[p])!=1) {
sb.append(new ByteList(s,p,enc.length(s[p]),false).toString());
p += enc.length(s[p]);
continue;
} else if((' ' == s[p] || (!Character.isWhitespace(s[p]) &&
!Character.isISOControl(s[p])))) {
sb.append((char)(s[p]&0xFF));
} else if(!Character.isWhitespace((char)(s[p]&0xFF))) {
sb.append('\\');
sb.append(Integer.toString((int)(s[p]&0377),8));
} else {
sb.append((char)(s[p]&0xFF));
}
p++;
}
}
}
/** rb_reg_init_copy
*/
@JRubyMethod(name = "initialize_copy", required = 1)
@Override
public IRubyObject initialize_copy(IRubyObject re) {
if(this == re) return this;
checkFrozen();
if (getMetaClass().getRealClass() != re.getMetaClass().getRealClass()) {
throw getRuntime().newTypeError("wrong argument type");
}
RubyRegexp regexp = (RubyRegexp)re;
regexp.check();
initialize(regexp.str, regexp.getOptions(), false);
return this;
}
/** rb_set_kcode
*/
private int getKcode() {
if(kcode == KCode.NONE) {
return 16;
} else if(kcode == KCode.EUC) {
return 32;
} else if(kcode == KCode.SJIS) {
return 48;
} else if(kcode == KCode.UTF8) {
return 64;
}
return 0;
}
/**
*/
private void setKCode(int options) {
clearKCodeDefault();
switch(options & ~0xf) {
case 0:
default:
setKCodeDefault();
kcode = getRuntime().getKCode();
break;
case 16:
kcode = KCode.NONE;
break;
case 32:
kcode = KCode.EUC;
break;
case 48:
kcode = KCode.SJIS;
break;
case 64:
kcode = KCode.UTF8;
break;
}
}
/** rb_reg_options
*/
private int getOptions() {
check();
int options = (int)(pattern.getOptions() & (RE_OPTION_IGNORECASE|RE_OPTION_MULTILINE|RE_OPTION_EXTENDED));
if(!isKCodeDefault()) {
options |= getKcode();
}
return options;
}
/** rb_reg_initialize_m
*/
@JRubyMethod(name = "initialize", optional = 3, visibility = Visibility.PRIVATE)
public IRubyObject initialize_m(IRubyObject[] args) {
ByteList bytes;
int regexFlags = 0;
if(args[0] instanceof RubyRegexp) {
if(args.length > 1) {
getRuntime().getWarnings().warn(ID.REGEXP_IGNORED_FLAGS, "flags" + (args.length == 3 ? " and encoding" : "") + " ignored");
}
RubyRegexp regexp = (RubyRegexp)args[0];
regexp.check();
regexFlags = (int)regexp.pattern.getOptions() & 0xF;
if (!regexp.isKCodeDefault() && regexp.kcode != null && regexp.kcode != KCode.NIL) {
if (regexp.kcode == KCode.NONE) {
regexFlags |= 16;
} else if (regexp.kcode == KCode.EUC) {
regexFlags |= 32;
} else if (regexp.kcode == KCode.SJIS) {
regexFlags |= 48;
} else if (regexp.kcode == KCode.UTF8) {
regexFlags |= 64;
}
}
bytes = regexp.str;
} else {
if (args.length >= 2) {
if (args[1] instanceof RubyFixnum) {
regexFlags = RubyNumeric.fix2int(args[1]);
} else if (args[1].isTrue()) {
regexFlags = RE_OPTION_IGNORECASE;
}
}
if (args.length == 3 && !args[2].isNil()) {
ByteList kcodeBytes = args[2].convertToString().getByteList();
char first = kcodeBytes.length() > 0 ? kcodeBytes.charAt(0) : 0;
regexFlags &= ~0x70;
switch (first) {
case 'n': case 'N':
regexFlags |= 16;
break;
case 'e': case 'E':
regexFlags |= 32;
break;
case 's': case 'S':
regexFlags |= 48;
break;
case 'u': case 'U':
regexFlags |= 64;
break;
default:
break;
}
}
bytes = args[0].convertToString().getByteList();
}
initialize(bytes, regexFlags, false);
return this;
}
@JRubyMethod(name = {"new", "compile"}, required = 1, optional = 2, meta = true)
public static RubyRegexp newInstance(IRubyObject recv, IRubyObject[] args) {
RubyClass klass = (RubyClass)recv;
RubyRegexp re = (RubyRegexp) klass.allocate();
re.callInit(args, Block.NULL_BLOCK);
return re;
}
@JRubyMethod(name = "options")
public IRubyObject options() {
return getRuntime().newFixnum(getOptions());
}
/** rb_reg_search
*/
public int search(ThreadContext context, RubyString str, int pos, boolean reverse) {
Ruby runtime = context.getRuntime();
Frame frame = context.getCurrentRubyFrame();
ByteList value = str.getByteList();
if (pos > value.realSize || pos < 0) {
frame.setBackRef(runtime.getNil());
return -1;
}
return performSearch(reverse, pos, value, frame, runtime, context, str);
}
private int performSearch(boolean reverse, int pos, ByteList value, Frame frame, Ruby runtime, ThreadContext context, RubyString str) {
check();
int realSize = value.realSize;
int begin = value.begin;
int range = reverse ? -pos : realSize - pos;
Matcher matcher = pattern.matcher(value.bytes, begin, begin + realSize);
int result = matcher.search(begin + pos, begin + pos + range, Option.NONE);
if (result < 0) {
frame.setBackRef(runtime.getNil());
return result;
}
updateBackRef(context, str, frame, matcher);
return result;
}
final RubyMatchData updateBackRef(ThreadContext context, RubyString str, Frame frame, Matcher matcher) {
Ruby runtime = context.getRuntime();
IRubyObject backref = frame.getBackRef();
final RubyMatchData match;
if (backref == null || backref.isNil() || ((RubyMatchData)backref).used()) {
match = new RubyMatchData(runtime);
} else {
match = (RubyMatchData)backref;
match.setTaint(runtime.getSafeLevel() >= 3);
}
match.regs = matcher.getRegion(); // lazy, null when no groups defined
match.begin = matcher.getBegin();
match.end = matcher.getEnd();
match.str = (RubyString)str.strDup(runtime).freeze(context);
match.pattern = pattern;
frame.setBackRef(match);
match.infectBy(this);
match.infectBy(str);
return match;
}
/** rb_reg_match
*
*/
@JRubyMethod(name = "=~", required = 1, reads = BACKREF, writes = BACKREF)
@Override
public IRubyObject op_match(ThreadContext context, IRubyObject str) {
int start;
if(str.isNil()) {
context.getCurrentFrame().setBackRef(context.getRuntime().getNil());
return str;
}
start = search(context, str.convertToString(), 0, false);
if (start < 0) return context.getRuntime().getNil();
return RubyFixnum.newFixnum(context.getRuntime(), start);
}
/** rb_reg_match_m
*
*/
@JRubyMethod(name = "match", required = 1, reads = BACKREF)
public IRubyObject match_m(ThreadContext context, IRubyObject str) {
if (op_match(context, str).isNil()) return context.getRuntime().getNil();
IRubyObject result = context.getCurrentFrame().getBackRef();
if (result instanceof RubyMatchData) {
((RubyMatchData)result).use();
}
return result;
}
public RubyString regsub(RubyString str, RubyString src, Matcher matcher) {
Region regs = matcher.getRegion();
int mbeg = matcher.getBegin();
int mend = matcher.getEnd();
int p,s,e;
p = s = 0;
int no = -1;
ByteList bs = str.getByteList();
ByteList srcbs = src.getByteList();
e = bs.length();
RubyString val = null;
Encoding enc = kcode.getEncoding();
int beg, end;
while(s < e) {
int ss = s;
char c = bs.charAt(s++);
if(enc.length((byte)c) != 1) {
s += enc.length((byte)c) - 1;
continue;
}
if (c != '\\' || s == e) continue;
if (val == null) val = RubyString.newString(getRuntime(), new ByteList(ss - p));
val.cat(bs.bytes, bs.begin + p, ss - p);
c = bs.charAt(s++);
p = s;
switch(c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
no = c - '0';
break;
case '&':
no = 0;
break;
case '`':
beg = regs == null ? mbeg : regs.beg[0];
val.cat(srcbs.bytes, srcbs.begin, beg);
continue;
case '\'':
end = regs == null ? mend : regs.end[0];
val.cat(srcbs.bytes, srcbs.begin + end, src.getByteList().realSize - end);
continue;
case '+':
if (regs == null) {
if (mbeg == -1) {
no = 0;
continue;
}
} else {
no = regs.numRegs-1;
while(regs.beg[no] == -1 && no > 0) no--;
if (no == 0) continue;
}
break;
case '\\':
val.cat(bs.bytes, s - 1, 1);
continue;
default:
val.cat(bs.bytes, s - 2, 2);
continue;
}
if (regs != null) {
if (no >= 0) {
if (no >= regs.numRegs || regs.beg[no] == -1) continue;
val.cat(srcbs.bytes, srcbs.begin + regs.beg[no], regs.end[no] - regs.beg[no]);
}
} else {
if (no != 0 || mbeg == -1) continue;
val.cat(srcbs.bytes, srcbs.begin + mbeg, mend - mbeg);
}
}
if(p < e) {
if(val == null) {
val = RubyString.newString(getRuntime(), bs.makeShared(p, e-p));
} else {
val.cat(bs.bytes, bs.begin + p, e - p);
}
}
if (val == null) return str;
return val;
}
final int adjustStartPos(RubyString str, int pos, boolean reverse) {
check();
ByteList value = str.getByteList();
return pattern.adjustStartPosition(value.bytes, value.begin, value.realSize, pos, reverse);
}
@JRubyMethod(name = "casefold?")
public IRubyObject casefold_p(ThreadContext context) {
check();
return context.getRuntime().newBoolean((pattern.getOptions() & RE_OPTION_IGNORECASE) != 0);
}
/** rb_reg_source
*
*/
@JRubyMethod(name = "source")
public IRubyObject source() {
Ruby runtime = getRuntime();
check();
RubyString str = RubyString.newStringShared(runtime, this.str);
if(isTaint()) {
str.taint(runtime.getCurrentContext());
}
return str;
}
final int length() {
return str.realSize;
}
/** rb_reg_inspect
*
*/
@JRubyMethod(name = "inspect")
@Override
public IRubyObject inspect() {
check();
return getRuntime().newString(ByteList.create(rb_reg_desc(str.bytes, str.begin, str.realSize, pattern.getOptions()).toString()));
}
private final static int EMBEDDABLE = RE_OPTION_MULTILINE|RE_OPTION_IGNORECASE|RE_OPTION_EXTENDED;
@JRubyMethod(name = "to_s")
@Override
public IRubyObject to_s() {
RubyString ss = getRuntime().newString("(?");
check();
int options = pattern.getOptions();
int ptr = str.begin;
int len = str.realSize;
byte[] bytes = str.bytes;
again: do {
if (len >= 4 && bytes[ptr] == '(' && bytes[ptr + 1] == '?') {
boolean err = true;
ptr += 2;
if ((len -= 2) > 0) {
do {
if (bytes[ptr] == 'm') {
options |= RE_OPTION_MULTILINE;
} else if (bytes[ptr] == 'i') {
options |= RE_OPTION_IGNORECASE;
} else if (bytes[ptr] == 'x') {
options |= RE_OPTION_EXTENDED;
} else {
break;
}
ptr++;
} while(--len > 0);
}
if (len > 1 && bytes[ptr] == '-') {
++ptr;
--len;
do {
if (bytes[ptr] == 'm') {
options &= ~RE_OPTION_MULTILINE;
} else if (bytes[ptr] == 'i') {
options &= ~RE_OPTION_IGNORECASE;
} else if (bytes[ptr] == 'x') {
options &= ~RE_OPTION_EXTENDED;
} else {
break;
}
ptr++;
} while(--len > 0);
}
if (bytes[ptr] == ')') {
--len;
++ptr;
continue again;
}
if (bytes[ptr] == ':' && bytes[ptr + len - 1] == ')') {
try {
new Regex(bytes, ++ptr, ptr + (len-=2) ,Option.DEFAULT, kcode.getEncoding(), Syntax.DEFAULT);
err = false;
} catch (JOniException e) {
err = true;
}
}
if (err) {
options = (int)pattern.getOptions();
ptr = str.begin;
len = str.realSize;
}
}
if ((options & RE_OPTION_MULTILINE) !=0 ) ss.cat((byte)'m');
if ((options & RE_OPTION_IGNORECASE) !=0 ) ss.cat((byte)'i');
if ((options & RE_OPTION_EXTENDED) !=0 ) ss.cat((byte)'x');
if ((options & EMBEDDABLE) != EMBEDDABLE) {
ss.cat((byte)'-');
if ((options & RE_OPTION_MULTILINE) == 0) ss.cat((byte)'m');
if ((options & RE_OPTION_IGNORECASE) == 0) ss.cat((byte)'i');
if ((options & RE_OPTION_EXTENDED) == 0) ss.cat((byte)'x');
}
ss.cat((byte)':');
rb_reg_expr_str(ss, ptr, len);
ss.cat((byte)')');
ss.infectBy(this);
return ss;
} while(true);
}
private final void rb_reg_expr_str(RubyString ss, int s, int len) {
int p = s;
int pend = p + len;
boolean need_escape = false;
Encoding enc = kcode.getEncoding();
while (p < pend) {
if (str.bytes[p] == '/' || (!enc.isPrint(str.bytes[p] & 0xff) && enc.length(str.bytes[p]) == 1)) {
need_escape = true;
break;
}
p += enc.length(str.bytes[p]);
}
if (!need_escape) {
ss.cat(str.bytes, s, len);
} else {
p = s;
while (p<pend) {
if (str.bytes[p] == '\\') {
int n = enc.length(str.bytes[p+1]) + 1;
ss.cat(str.bytes, p, n);
p += n;
continue;
} else if (str.bytes[p] == '/') {
ss.cat((byte)'\\');
ss.cat(str.bytes, p, 1);
} else if (enc.length(str.bytes[p]) != 1) {
ss.cat(str.bytes, p, enc.length(str.bytes[p]));
p += enc.length(str.bytes[p]);
continue;
} else if (enc.isPrint(str.bytes[p] & 0xff)) {
ss.cat(str.bytes,p,1);
} else if (!enc.isSpace(str.bytes[p] & 0xff)) {
ss.cat(ByteList.create(Integer.toString(str.bytes[p] & 0377, 8)));
} else {
ss.cat(str.bytes, p, 1);
}
p++;
}
}
}
/** rb_reg_s_quote
*
*/
@JRubyMethod(name = {"quote", "escape"}, required = 1, optional = 1, meta = true)
public static RubyString quote(IRubyObject recv, IRubyObject[] args) {
IRubyObject kcode = args.length == 2 ? args[1] : null;
IRubyObject str = args[0];
KCode code = recv.getRuntime().getKCode();
if (kcode != null && !kcode.isNil()) {
code = KCode.create(recv.getRuntime(), kcode.toString());
}
RubyString src = str.convertToString();
RubyString dst = RubyString.newString(recv.getRuntime(), quote(src.getByteList(), code));
dst.infectBy(src);
return dst;
}
/** rb_reg_quote
*
*/
public static ByteList quote(ByteList str, KCode kcode) {
ByteList bs = str;
int tix = 0;
int s = bs.begin;
char c;
int send = s+bs.length();
Encoding enc = kcode.getEncoding();
meta_found: do {
for(; s<send; s++) {
c = (char)(bs.bytes[s]&0xFF);
if(enc.length((byte)c) != 1) {
int n = enc.length((byte)c);
while(n-- > 0 && s < send) {
s++;
}
s--;
continue;
}
switch (c) {
case '[': case ']': case '{': case '}':
case '(': case ')': case '|': case '-':
case '*': case '.': case '\\':
case '?': case '+': case '^': case '$':
case ' ': case '#':
case '\t': case '\f': case '\n': case '\r':
break meta_found;
}
}
return bs;
} while(false);
ByteList b1 = new ByteList(send*2);
System.arraycopy(bs.bytes,bs.begin,b1.bytes,b1.begin,s-bs.begin);
tix += (s-bs.begin);
for(; s<send; s++) {
c = (char)(bs.bytes[s]&0xFF);
if(enc.length((byte)c) != 1) {
int n = enc.length((byte)c);
while(n-- > 0 && s < send) {
b1.bytes[tix++] = bs.bytes[s++];
}
s--;
continue;
}
switch(c) {
case '[': case ']': case '{': case '}':
case '(': case ')': case '|': case '-':
case '*': case '.': case '\\':
case '?': case '+': case '^': case '$':
case '#':
b1.bytes[tix++] = '\\';
break;
case ' ':
b1.bytes[tix++] = '\\';
b1.bytes[tix++] = ' ';
continue;
case '\t':
b1.bytes[tix++] = '\\';
b1.bytes[tix++] = 't';
continue;
case '\n':
b1.bytes[tix++] = '\\';
b1.bytes[tix++] = 'n';
continue;
case '\r':
b1.bytes[tix++] = '\\';
b1.bytes[tix++] = 'r';
continue;
case '\f':
b1.bytes[tix++] = '\\';
b1.bytes[tix++] = 'f';
continue;
}
b1.bytes[tix++] = (byte)c;
}
b1.realSize = tix;
return b1;
}
/** rb_reg_nth_match
*
*/
public static IRubyObject nth_match(int nth, IRubyObject match) {
if (match.isNil()) return match;
RubyMatchData m = (RubyMatchData)match;
int start, end;
if (m.regs == null) {
if (nth >= 1) return match.getRuntime().getNil();
if (nth < 0 && ++nth <= 0) return match.getRuntime().getNil();
start = m.begin;
end = m.end;
} else {
if (nth >= m.regs.numRegs) return match.getRuntime().getNil();
if (nth < 0 && (nth+=m.regs.numRegs) <= 0) return match.getRuntime().getNil();
start = m.regs.beg[nth];
end = m.regs.end[nth];
}
if (start == -1) return match.getRuntime().getNil();
RubyString str = m.str.makeShared(match.getRuntime(), start, end - start);
str.infectBy(match);
return str;
}
/** rb_reg_last_match
*
*/
public static IRubyObject last_match(IRubyObject match) {
return nth_match(0, match);
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public static IRubyObject last_match_s(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
switch (args.length) {
case 0:
return last_match_s(context, recv);
case 1:
return last_match_s(context, recv, args[0]);
default:
Arity.raiseArgumentError(recv.getRuntime(), args.length, 0, 1);
return null; // not reached
}
}
/** rb_reg_s_last_match / match_getter
*
*/
@JRubyMethod(name = "last_match", meta = true, reads = BACKREF)
public static IRubyObject last_match_s(ThreadContext context, IRubyObject recv) {
IRubyObject match = context.getCurrentFrame().getBackRef();
if (match instanceof RubyMatchData) ((RubyMatchData)match).use();
return match;
}
/** rb_reg_s_last_match
*
*/
@JRubyMethod(name = "last_match", meta = true, reads = BACKREF)
public static IRubyObject last_match_s(ThreadContext context, IRubyObject recv, IRubyObject nth) {
IRubyObject match = context.getCurrentFrame().getBackRef();
if (match.isNil()) return match;
return nth_match(((RubyMatchData)match).backrefNumber(nth), match);
}
/** rb_reg_match_pre
*
*/
public static IRubyObject match_pre(IRubyObject match) {
if (match.isNil()) return match;
RubyMatchData m = (RubyMatchData)match;
int beg = m.regs == null ? m.begin : m.regs.beg[0];
if(beg == -1) match.getRuntime().getNil();
RubyString str = m.str.makeShared(match.getRuntime(), 0, beg);
str.infectBy(match);
return str;
}
/** rb_reg_match_post
*
*/
public static IRubyObject match_post(IRubyObject match) {
if (match.isNil()) return match;
RubyMatchData m = (RubyMatchData)match;
int end;
if (m.regs == null) {
if (m.begin == -1) return match.getRuntime().getNil();
end = m.end;
} else {
if (m.regs.beg[0] == -1) return match.getRuntime().getNil();
end = m.regs.end[0];
}
RubyString str = m.str.makeShared(match.getRuntime(), end, m.str.getByteList().realSize - end);
str.infectBy(match);
return str;
}
/** rb_reg_match_last
*
*/
public static IRubyObject match_last(IRubyObject match) {
if (match.isNil()) return match;
RubyMatchData m = (RubyMatchData)match;
if (m.regs == null || m.regs.beg[0] == -1) return match.getRuntime().getNil();
int i;
for (i=m.regs.numRegs-1; m.regs.beg[i]==-1 && i>0; i--);
if (i == 0) return match.getRuntime().getNil();
return nth_match(i,match);
}
/** rb_reg_s_union
*
*/
@JRubyMethod(name = "union", rest = true, meta = true)
public static IRubyObject union(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length == 0) {
return newRegexp(recv.getRuntime(), ByteList.create("(?!)"), 0, false);
} else if (args.length == 1) {
IRubyObject v = TypeConverter.convertToTypeWithCheck(args[0], recv.getRuntime().getRegexp(), 0, "to_regexp");
if(!v.isNil()) {
return v;
} else {
// newInstance here
return newRegexp(recv.getRuntime(), quote(recv,args).getByteList(), 0, false);
}
} else {
KCode kcode = null;
IRubyObject kcode_re = recv.getRuntime().getNil();
RubyString source = recv.getRuntime().newString();
IRubyObject[] _args = new IRubyObject[3];
for (int i = 0; i < args.length; i++) {
if (0 < i) {
source.cat((byte)'|');
}
IRubyObject v = TypeConverter.convertToTypeWithCheck(args[i], recv.getRuntime().getRegexp(), 0, "to_regexp");
if (!v.isNil()) {
if (!((RubyRegexp)v).isKCodeDefault()) {
if (kcode == null) {
kcode_re = v;
kcode = ((RubyRegexp)v).kcode;
} else if (((RubyRegexp)v).kcode != kcode) {
IRubyObject str1 = kcode_re.inspect();
IRubyObject str2 = v.inspect();
throw recv.getRuntime().newArgumentError("mixed kcode " + str1 + " and " + str2);
}
}
v = ((RubyRegexp)v).to_s();
} else {
v = quote(recv, new IRubyObject[]{args[i]});
}
source.append(v);
}
_args[0] = source;
_args[1] = recv.getRuntime().getNil();
if (kcode == null) {
_args[2] = recv.getRuntime().getNil();
} else if (kcode == KCode.NONE) {
_args[2] = recv.getRuntime().newString("n");
} else if (kcode == KCode.EUC) {
_args[2] = recv.getRuntime().newString("e");
} else if (kcode == KCode.SJIS) {
_args[2] = recv.getRuntime().newString("s");
} else if (kcode == KCode.UTF8) {
_args[2] = recv.getRuntime().newString("u");
}
return recv.callMethod(context, "new", _args);
}
}
/** rb_reg_names
*
*/
@JRubyMethod(name = "names", compat = CompatVersion.RUBY1_9)
public IRubyObject names() {
if (pattern.numberOfNames() == 0) return getRuntime().newEmptyArray();
RubyArray ary = getRuntime().newArray(pattern.numberOfNames());
for (Iterator<NameEntry> i = pattern.namedBackrefIterator(); i.hasNext();) {
NameEntry e = i.next();
ary.append(RubyString.newStringShared(getRuntime(), e.name, e.nameP, e.nameEnd - e.nameP));
}
return ary;
}
/** rb_reg_named_captures
*
*/
@JRubyMethod(name = "named_captures", compat = CompatVersion.RUBY1_9)
public IRubyObject named_captures(ThreadContext context) {
RubyHash hash = RubyHash.newHash(getRuntime());
if (pattern.numberOfNames() == 0) return hash;
for (Iterator<NameEntry> i = pattern.namedBackrefIterator(); i.hasNext();) {
NameEntry e = i.next();
int[]backrefs = e.getBackRefs();
RubyArray ary = getRuntime().newArray(backrefs.length);
for (int backref : backrefs) ary.append(RubyFixnum.newFixnum(getRuntime(), backref));
hash.fastASet(RubyString.newStringShared(getRuntime(), e.name, e.nameP, e.nameEnd - e.nameP).freeze(context), ary);
}
return hash;
}
public static RubyRegexp unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
RubyRegexp result = newRegexp(input.getRuntime(), input.unmarshalString(), input.unmarshalInt(), false);
input.registerLinkTarget(result);
return result;
}
public static void marshalTo(RubyRegexp regexp, MarshalStream output) throws java.io.IOException {
output.registerLinkTarget(regexp);
output.writeString(new String(regexp.str.bytes,regexp.str.begin,regexp.str.realSize));
output.writeInt(regexp.pattern.getOptions() & EMBEDDABLE);
}
}
package org.jruby;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* @author nicksieger
*/
public interface RubyRuntimeAdapter {
IRubyObject eval(Ruby runtime, String script);
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.SignalFacade;
import org.jruby.util.NoFunctionalitySignalFacade;
@JRubyModule(name="Signal")
public class RubySignal {
private final static SignalFacade SIGNALS = getSignalFacade();
private final static SignalFacade getSignalFacade() {
try {
Class realFacadeClass = Class.forName("org.jruby.util.SunSignalFacade");
return (SignalFacade)realFacadeClass.newInstance();
} catch(Throwable e) {
return new NoFunctionalitySignalFacade();
}
}
// NOTE: The indicies here match exactly the signal values; do not reorder
public static final String[] NAMES = {
"EXIT", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "EMT",
"FPE", "KILL", "BUS", "SEGV", "SYS", "PIPE", "ALRM", "TERM", "URG",
"STOP", "TSTP", "CONT", "CHLD", "TTIN", "TTOU", "IO", "XCPU",
"XFSZ", "VTALRM", "PROF", "WINCH", "INFO", "USR1", "USR2"};
public static void createSignal(Ruby runtime) {
RubyModule mSignal = runtime.defineModule("Signal");
mSignal.defineAnnotatedMethods(RubySignal.class);
}
@JRubyMethod(name = "trap", required = 1, optional = 1, frame = true, meta = true)
public static IRubyObject trap(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = recv.getRuntime();
runtime.getLoadService().require("jsignal");
return RuntimeHelpers.invoke(context, runtime.getKernel(), "__jtrap", args, block);
}
@JRubyMethod(name = "list", meta = true)
public static IRubyObject list(ThreadContext context, IRubyObject recv) {
Ruby runtime = recv.getRuntime();
RubyHash names = RubyHash.newHash(runtime);
for (int i = 0; i < NAMES.length; i++) {
names.op_aset(context, runtime.newString(NAMES[i]), runtime.newFixnum(i));
}
// IOT is also 6
names.op_aset(context, runtime.newString("IOT"), runtime.newFixnum(6));
// CLD is also 20
names.op_aset(context, runtime.newString("CLD"), runtime.newFixnum(20));
return names;
}
@JRubyMethod(name = "__jtrap_kernel", required = 3,meta = true)
public static IRubyObject __jtrap_kernel(final IRubyObject recv, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3) {
return SIGNALS.trap(recv, arg1, arg2, arg3);
}
}// RubySignal
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2004 David Corbin <dcorbin@users.sourceforge.net>
* Copyright (C) 2005 Tim Azzopardi <tim@tigerfive.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
* Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.anno.FrameField.BACKREF;
import static org.jruby.anno.FrameField.LASTLINE;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import org.joni.Matcher;
import org.joni.Option;
import org.joni.Regex;
import org.joni.Region;
import org.joni.encoding.Encoding;
import org.joni.encoding.specific.ASCIIEncoding;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.java.MiniJava;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.Frame;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.Numeric;
import org.jruby.util.Pack;
import org.jruby.util.Sprintf;
import org.jruby.util.string.JavaCrypt;
/**
* Implementation of Ruby String class
*
* Concurrency: no synchronization is required among readers, but
* all users must synchronize externally with writers.
*
*/
@JRubyClass(name="String", include={"Enumerable", "Comparable"})
public class RubyString extends RubyObject {
private static final ASCIIEncoding ASCII = ASCIIEncoding.INSTANCE;
// string doesn't share any resources
private static final int SHARE_LEVEL_NONE = 0;
// string has it's own ByteList, but it's pointing to a shared buffer (byte[])
private static final int SHARE_LEVEL_BUFFER = 1;
// string doesn't have it's own ByteList (values)
private static final int SHARE_LEVEL_BYTELIST = 2;
private volatile int shareLevel = SHARE_LEVEL_NONE;
private ByteList value;
private static ObjectAllocator STRING_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return RubyString.newEmptyString(runtime, klass);
}
};
public static RubyClass createStringClass(Ruby runtime) {
RubyClass stringClass = runtime.defineClass("String", runtime.getObject(), STRING_ALLOCATOR);
runtime.setString(stringClass);
stringClass.index = ClassIndex.STRING;
stringClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyString;
}
};
stringClass.includeModule(runtime.getComparable());
stringClass.includeModule(runtime.getEnumerable());
stringClass.defineAnnotatedMethods(RubyString.class);
return stringClass;
}
/** short circuit for String key comparison
*
*/
@Override
public final boolean eql(IRubyObject other) {
if (other.getMetaClass() == getRuntime().getString()) return value.equal(((RubyString)other).value);
return super.eql(other);
}
private RubyString(Ruby runtime, RubyClass rubyClass, CharSequence value) {
super(runtime, rubyClass);
assert value != null;
this.value = new ByteList(ByteList.plain(value), false);
}
private RubyString(Ruby runtime, RubyClass rubyClass, byte[] value) {
super(runtime, rubyClass);
assert value != null;
this.value = new ByteList(value);
}
private RubyString(Ruby runtime, RubyClass rubyClass, ByteList value) {
super(runtime, rubyClass);
assert value != null;
this.value = value;
}
private RubyString(Ruby runtime, RubyClass rubyClass, ByteList value, boolean objectSpace) {
super(runtime, rubyClass, objectSpace);
assert value != null;
this.value = value;
}
/** Create a new String which uses the same Ruby runtime and the same
* class like this String.
*
* This method should be used to satisfy RCR #38.
* @deprecated
*/
public RubyString newString(CharSequence s) {
return new RubyString(getRuntime(), getType(), s);
}
/** Create a new String which uses the same Ruby runtime and the same
* class like this String.
*
* This method should be used to satisfy RCR #38.
* @deprecated
*/
public RubyString newString(ByteList s) {
return new RubyString(getRuntime(), getMetaClass(), s);
}
// Methods of the String class (rb_str_*):
/** rb_str_new2
*
*/
public static RubyString newString(Ruby runtime, CharSequence str) {
return new RubyString(runtime, runtime.getString(), str);
}
public static RubyString newEmptyString(Ruby runtime) {
return newEmptyString(runtime, runtime.getString());
}
public static RubyString newEmptyString(Ruby runtime, RubyClass metaClass) {
RubyString empty = new RubyString(runtime, metaClass, ByteList.EMPTY_BYTELIST);
empty.shareLevel = SHARE_LEVEL_BYTELIST;
return empty;
}
public static RubyString newUnicodeString(Ruby runtime, String str) {
try {
return new RubyString(runtime, runtime.getString(), new ByteList(str.getBytes("UTF8"), false));
} catch (UnsupportedEncodingException uee) {
return new RubyString(runtime, runtime.getString(), str);
}
}
@Deprecated
public static RubyString newString(Ruby runtime, RubyClass clazz, CharSequence str) {
return new RubyString(runtime, clazz, str);
}
public static RubyString newString(Ruby runtime, byte[] bytes) {
return new RubyString(runtime, runtime.getString(), bytes);
}
public static RubyString newString(Ruby runtime, byte[] bytes, int start, int length) {
byte[] copy = new byte[length];
System.arraycopy(bytes, start, copy, 0, length);
return new RubyString(runtime, runtime.getString(), new ByteList(copy, false));
}
public static RubyString newString(Ruby runtime, ByteList bytes) {
return new RubyString(runtime, runtime.getString(), bytes);
}
public static RubyString newStringLight(Ruby runtime, ByteList bytes) {
return new RubyString(runtime, runtime.getString(), bytes, false);
}
public static RubyString newStringShared(Ruby runtime, RubyString orig) {
orig.shareLevel = SHARE_LEVEL_BYTELIST;
RubyString str = new RubyString(runtime, runtime.getString(), orig.value);
str.shareLevel = SHARE_LEVEL_BYTELIST;
return str;
}
public static RubyString newStringShared(Ruby runtime, ByteList bytes) {
return newStringShared(runtime, runtime.getString(), bytes);
}
public static RubyString newStringShared(Ruby runtime, RubyClass clazz, ByteList bytes) {
RubyString str = new RubyString(runtime, clazz, bytes);
str.shareLevel = SHARE_LEVEL_BYTELIST;
return str;
}
public static RubyString newStringShared(Ruby runtime, byte[] bytes, int start, int length) {
RubyString str = new RubyString(runtime, runtime.getString(), new ByteList(bytes, start, length, false));
str.shareLevel = SHARE_LEVEL_BUFFER;
return str;
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.STRING;
}
@Override
public Class getJavaClass() {
return String.class;
}
@Override
public RubyString convertToString() {
return this;
}
@Override
public String toString() {
return value.toString();
}
/** rb_str_dup
*
*/
@Deprecated
public final RubyString strDup() {
return strDup(getRuntime(), getMetaClass());
}
public final RubyString strDup(Ruby runtime) {
return strDup(runtime, getMetaClass());
}
@Deprecated
final RubyString strDup(RubyClass clazz) {
return strDup(getRuntime(), getMetaClass());
}
final RubyString strDup(Ruby runtime, RubyClass clazz) {
shareLevel = SHARE_LEVEL_BYTELIST;
RubyString dup = new RubyString(runtime, clazz, value);
dup.shareLevel = SHARE_LEVEL_BYTELIST;
dup.infectBy(this);
return dup;
}
public final RubyString makeShared(Ruby runtime, int index, int len) {
if (len == 0) {
RubyString s = newEmptyString(runtime, getMetaClass());
s.infectBy(this);
return s;
}
if (shareLevel == SHARE_LEVEL_NONE) shareLevel = SHARE_LEVEL_BUFFER;
RubyString shared = new RubyString(runtime, getMetaClass(), value.makeShared(index, len));
shared.shareLevel = SHARE_LEVEL_BUFFER;
shared.infectBy(this);
return shared;
}
final void modifyCheck() {
if ((flags & FROZEN_F) != 0) throw getRuntime().newFrozenError("string");
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't modify string");
}
}
private final void modifyCheck(byte[] b, int len) {
if (value.bytes != b || value.realSize != len) throw getRuntime().newRuntimeError("string modified");
}
private final void frozenCheck() {
if (isFrozen()) throw getRuntime().newRuntimeError("string frozen");
}
/** rb_str_modify
*
*/
public final void modify() {
modifyCheck();
if (shareLevel != SHARE_LEVEL_NONE) {
if (shareLevel == SHARE_LEVEL_BYTELIST) {
value = value.dup();
} else {
value.unshare();
}
shareLevel = SHARE_LEVEL_NONE;
}
value.invalidate();
}
/** rb_str_modify (with length bytes ensured)
*
*/
public final void modify(int length) {
modifyCheck();
if (shareLevel != SHARE_LEVEL_NONE) {
if (shareLevel == SHARE_LEVEL_BYTELIST) {
value = value.dup(length);
} else {
value.unshare(length);
}
shareLevel = SHARE_LEVEL_NONE;
} else {
value.ensure(length);
}
value.invalidate();
}
private final void view(ByteList bytes) {
modifyCheck();
value = bytes;
shareLevel = SHARE_LEVEL_NONE;
}
private final void view(byte[]bytes) {
modifyCheck();
value.replace(bytes);
shareLevel = SHARE_LEVEL_NONE;
value.invalidate();
}
private final void view(int index, int len) {
modifyCheck();
if (shareLevel != SHARE_LEVEL_NONE) {
if (shareLevel == SHARE_LEVEL_BYTELIST) {
// if len == 0 then shared empty
value = value.makeShared(index, len);
shareLevel = SHARE_LEVEL_BUFFER;
} else {
value.view(index, len);
}
} else {
value.view(index, len);
// FIXME this below is temporary, but its much safer for COW (it prevents not shared Strings with begin != 0)
// this allows now e.g.: ByteList#set not to be begin aware
shareLevel = SHARE_LEVEL_BUFFER;
}
value.invalidate();
}
public static String bytesToString(byte[] bytes, int beg, int len) {
return new String(ByteList.plain(bytes, beg, len));
}
public static String byteListToString(ByteList bytes) {
return bytesToString(bytes.unsafeBytes(), bytes.begin(), bytes.length());
}
public static String bytesToString(byte[] bytes) {
return bytesToString(bytes, 0, bytes.length);
}
public static byte[] stringToBytes(String string) {
return ByteList.plain(string);
}
public static boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
public static boolean isUpper(int c) {
return c >= 'A' && c <= 'Z';
}
public static boolean isLower(int c) {
return c >= 'a' && c <= 'z';
}
public static boolean isLetter(int c) {
return isUpper(c) || isLower(c);
}
public static boolean isAlnum(int c) {
return isUpper(c) || isLower(c) || isDigit(c);
}
public static boolean isPrint(int c) {
return c >= 0x20 && c <= 0x7E;
}
@Override
public RubyString asString() {
return this;
}
@Override
public IRubyObject checkStringType() {
return this;
}
@JRubyMethod(name = {"to_s", "to_str"})
@Override
public IRubyObject to_s() {
Ruby runtime = getRuntime();
if (getMetaClass().getRealClass() != runtime.getString()) {
return strDup(runtime, runtime.getString());
}
return this;
}
/* rb_str_cmp_m */
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
if (other instanceof RubyString) {
return context.getRuntime().newFixnum(op_cmp((RubyString)other));
}
// deal with case when "other" is not a string
if (other.respondsTo("to_str") && other.respondsTo("<=>")) {
IRubyObject result = other.callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", this);
if (result instanceof RubyNumeric) {
return ((RubyNumeric) result).op_uminus(context);
}
}
return context.getRuntime().getNil();
}
/**
*
*/
@JRubyMethod(name = "==", required = 1)
@Override
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
Ruby runtime = context.getRuntime();
if (this == other) return runtime.getTrue();
if (!(other instanceof RubyString)) {
if (!other.respondsTo("to_str")) return runtime.getFalse();
return other.callMethod(context, MethodIndex.EQUALEQUAL, "==", this).isTrue() ? runtime.getTrue() : runtime.getFalse();
}
return value.equal(((RubyString)other).value) ? runtime.getTrue() : runtime.getFalse();
}
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus(ThreadContext context, IRubyObject other) {
RubyString str = other.convertToString();
ByteList result = new ByteList(value.realSize + str.value.realSize);
result.realSize = value.realSize + str.value.realSize;
System.arraycopy(value.bytes, value.begin, result.bytes, 0, value.realSize);
System.arraycopy(str.value.bytes, str.value.begin, result.bytes, value.realSize, str.value.realSize);
RubyString resultStr = newString(context.getRuntime(), result);
if (isTaint() || str.isTaint()) resultStr.setTaint(true);
return resultStr;
}
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_mul(ThreadContext context, IRubyObject other) {
RubyInteger otherInteger = (RubyInteger) other.convertToInteger();
long len = otherInteger.getLongValue();
if (len < 0) throw context.getRuntime().newArgumentError("negative argument");
// we limit to int because ByteBuffer can only allocate int sizes
if (len > 0 && Integer.MAX_VALUE / len < value.length()) {
throw context.getRuntime().newArgumentError("argument too big");
}
ByteList newBytes = new ByteList(value.length() * (int)len);
for (int i = 0; i < len; i++) {
newBytes.append(value);
}
RubyString newString = new RubyString(context.getRuntime(), getMetaClass(), newBytes);
newString.setTaint(isTaint());
return newString;
}
@JRubyMethod(name = "%", required = 1)
public IRubyObject op_format(ThreadContext context, IRubyObject arg) {
final RubyString s;
IRubyObject tmp = arg.checkArrayType();
if (tmp.isNil()) {
tmp = arg;
}
// FIXME: Should we make this work with platform's locale,
// or continue hardcoding US?
s = Sprintf.sprintf(context.getRuntime(), Locale.US, value, tmp);
s.infectBy(this);
return s;
}
@JRubyMethod(name = "hash")
@Override
public RubyFixnum hash() {
return getRuntime().newFixnum(value.hashCode());
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof RubyString) {
RubyString string = (RubyString) other;
if (string.value.equal(value)) return true;
}
return false;
}
/** rb_obj_as_string
*
*/
public static RubyString objAsString(ThreadContext context, IRubyObject obj) {
if (obj instanceof RubyString) return (RubyString) obj;
IRubyObject str = obj.callMethod(context, MethodIndex.TO_S, "to_s");
if (!(str instanceof RubyString)) return (RubyString) obj.anyToString();
if (obj.isTaint()) str.setTaint(true);
return (RubyString) str;
}
/** rb_str_cmp
*
*/
public int op_cmp(RubyString other) {
return value.cmp(other.value);
}
/** rb_to_id
*
*/
@Override
public String asJavaString() {
// TODO: This used to intern; but it didn't appear to change anything
// turning that off, and it's unclear if it was needed. Plus, we intern
//
return toString();
}
public IRubyObject doClone(){
return newString(getRuntime(), value.dup());
}
public RubyString cat(byte[] str) {
modify(value.realSize + str.length);
System.arraycopy(str, 0, value.bytes, value.begin + value.realSize, str.length);
value.realSize += str.length;
return this;
}
public RubyString cat(byte[] str, int beg, int len) {
modify(value.realSize + len);
System.arraycopy(str, beg, value.bytes, value.begin + value.realSize, len);
value.realSize += len;
return this;
}
public RubyString cat(ByteList str) {
modify(value.realSize + str.realSize);
System.arraycopy(str.bytes, str.begin, value.bytes, value.begin + value.realSize, str.realSize);
value.realSize += str.realSize;
return this;
}
public RubyString cat(byte ch) {
modify(value.realSize + 1);
value.bytes[value.begin + value.realSize] = ch;
value.realSize++;
return this;
}
/** rb_str_replace_m
*
*/
@JRubyMethod(name = {"replace", "initialize_copy"}, required = 1)
public RubyString replace(IRubyObject other) {
if (this == other) return this;
modifyCheck();
RubyString otherStr = stringValue(other);
otherStr.shareLevel = shareLevel = SHARE_LEVEL_BYTELIST;
value = otherStr.value;
infectBy(other);
return this;
}
@JRubyMethod(name = "reverse")
public RubyString reverse(ThreadContext context) {
if (value.length() <= 1) return strDup(context.getRuntime());
ByteList buf = new ByteList(value.length()+2);
buf.realSize = value.length();
int src = value.length() - 1;
int dst = 0;
while (src >= 0) buf.set(dst++, value.get(src--));
RubyString rev = new RubyString(context.getRuntime(), getMetaClass(), buf);
rev.infectBy(this);
return rev;
}
@JRubyMethod(name = "reverse!")
public RubyString reverse_bang() {
if (value.length() > 1) {
modify();
for (int i = 0; i < (value.length() / 2); i++) {
byte b = (byte) value.get(i);
value.set(i, value.get(value.length() - i - 1));
value.set(value.length() - i - 1, b);
}
}
return this;
}
/** rb_str_s_new
*
*/
public static RubyString newInstance(IRubyObject recv, IRubyObject[] args, Block block) {
RubyString newString = newStringShared(recv.getRuntime(), ByteList.EMPTY_BYTELIST);
newString.setMetaClass((RubyClass) recv);
newString.callInit(args, block);
return newString;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with zero or one arguments
*/
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
switch (args.length) {
case 0:
return this;
case 1:
return initialize(args[0]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 0, 1);
return null; // not reached
}
}
@JRubyMethod(frame = true, visibility = Visibility.PRIVATE)
@Override
public IRubyObject initialize() {
return this;
}
@JRubyMethod(frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject arg0) {
replace(arg0);
return this;
}
@JRubyMethod
public IRubyObject casecmp(IRubyObject other) {
int compare = value.caseInsensitiveCmp(stringValue(other).value);
return RubyFixnum.newFixnum(getRuntime(), compare);
}
/** rb_str_match
*
*/
@JRubyMethod(name = "=~")
@Override
public IRubyObject op_match(ThreadContext context, IRubyObject other) {
if (other instanceof RubyRegexp) return ((RubyRegexp) other).op_match(context, this);
if (other instanceof RubyString) {
throw context.getRuntime().newTypeError("type mismatch: String given");
}
return other.callMethod(context, "=~", this);
}
/** rb_str_match2
*
*/
@JRubyMethod(name = "~", reads = {LASTLINE, BACKREF}, writes = BACKREF)
public IRubyObject op_match2(ThreadContext context) {
return RubyRegexp.newRegexp(context.getRuntime(), value, 0, false).op_match2(context);
}
/**
* String#match(pattern)
*
* rb_str_match_m
*
* @param pattern Regexp or String
*/
@JRubyMethod
public IRubyObject match(ThreadContext context, IRubyObject pattern) {
return getPattern(pattern, false).callMethod(context, "match", this);
}
/** rb_str_capitalize
*
*/
@JRubyMethod
public IRubyObject capitalize(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.capitalize_bang(context);
return str;
}
/** rb_str_capitalize_bang
*
*/
@JRubyMethod(name = "capitalize!")
public IRubyObject capitalize_bang(ThreadContext context) {
if (value.realSize == 0) {
modifyCheck();
return context.getRuntime().getNil();
}
modify();
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
int c = buf[s] & 0xff;
if (ASCII.isLower(c)) {
buf[s] = (byte)ASCIIEncoding.asciiToUpper(c);
modify = true;
}
while (++s < send) {
c = (char)(buf[s] & 0xff);
if (ASCII.isUpper(c)) {
buf[s] = (byte)ASCIIEncoding.asciiToLower(c);
modify = true;
}
}
if (modify) return this;
return context.getRuntime().getNil();
}
@JRubyMethod(name = ">=")
public IRubyObject op_ge(ThreadContext context, IRubyObject other) {
if (other instanceof RubyString) {
return context.getRuntime().newBoolean(op_cmp((RubyString) other) >= 0);
}
return RubyComparable.op_ge(context, this, other);
}
@JRubyMethod(name = ">")
public IRubyObject op_gt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyString) {
return context.getRuntime().newBoolean(op_cmp((RubyString) other) > 0);
}
return RubyComparable.op_gt(context, this, other);
}
@JRubyMethod(name = "<=")
public IRubyObject op_le(ThreadContext context, IRubyObject other) {
if (other instanceof RubyString) {
return context.getRuntime().newBoolean(op_cmp((RubyString) other) <= 0);
}
return RubyComparable.op_le(context, this, other);
}
@JRubyMethod(name = "<")
public IRubyObject op_lt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyString) {
return context.getRuntime().newBoolean(op_cmp((RubyString) other) < 0);
}
return RubyComparable.op_lt(context, this, other);
}
@JRubyMethod(name = "eql?")
public IRubyObject str_eql_p(ThreadContext context, IRubyObject other) {
if (!(other instanceof RubyString)) return context.getRuntime().getFalse();
RubyString otherString = (RubyString)other;
return value.equal(otherString.value) ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
/** rb_str_upcase
*
*/
@JRubyMethod
public RubyString upcase(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.upcase_bang(context);
return str;
}
/** rb_str_upcase_bang
*
*/
@JRubyMethod(name = "upcase!")
public IRubyObject upcase_bang(ThreadContext context) {
if (value.realSize == 0) {
modifyCheck();
return context.getRuntime().getNil();
}
modify();
int s = value.begin;
int send = s + value.realSize;
byte []buf = value.bytes;
boolean modify = false;
while (s < send) {
int c = buf[s] & 0xff;
if (ASCII.isLower(c)) {
buf[s] = (byte)ASCIIEncoding.asciiToUpper(c);
modify = true;
}
s++;
}
if (modify) return this;
return context.getRuntime().getNil();
}
/** rb_str_downcase
*
*/
@JRubyMethod
public RubyString downcase(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.downcase_bang(context);
return str;
}
/** rb_str_downcase_bang
*
*/
@JRubyMethod(name = "downcase!")
public IRubyObject downcase_bang(ThreadContext context) {
if (value.realSize == 0) {
modifyCheck();
return context.getRuntime().getNil();
}
modify();
int s = value.begin;
int send = s + value.realSize;
byte []buf = value.bytes;
boolean modify = false;
while (s < send) {
int c = buf[s] & 0xff;
if (ASCII.isUpper(c)) {
buf[s] = (byte)ASCIIEncoding.asciiToLower(c);
modify = true;
}
s++;
}
if (modify) return this;
return context.getRuntime().getNil();
}
/** rb_str_swapcase
*
*/
@JRubyMethod
public RubyString swapcase(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.swapcase_bang(context);
return str;
}
/** rb_str_swapcase_bang
*
*/
@JRubyMethod(name = "swapcase!")
public IRubyObject swapcase_bang(ThreadContext context) {
if (value.realSize == 0) {
modifyCheck();
return context.getRuntime().getNil();
}
modify();
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
while (s < send) {
int c = buf[s] & 0xff;
if (ASCII.isUpper(c)) {
buf[s] = (byte)ASCIIEncoding.asciiToLower(c);
modify = true;
} else if (ASCII.isLower(c)) {
buf[s] = (byte)ASCIIEncoding.asciiToUpper(c);
modify = true;
}
s++;
}
if (modify) return this;
return context.getRuntime().getNil();
}
/** rb_str_dump
*
*/
@JRubyMethod
public IRubyObject dump() {
RubyString s = new RubyString(getRuntime(), getMetaClass(), inspectIntoByteList(true));
s.infectBy(this);
return s;
}
@JRubyMethod
public IRubyObject insert(ThreadContext context, IRubyObject indexArg, IRubyObject stringArg) {
// MRI behavior: first check for ability to convert to String...
RubyString s = (RubyString)stringArg.convertToString();
ByteList insert = s.value;
// ... and then the index
int index = (int) indexArg.convertToInteger().getLongValue();
if (index < 0) index += value.length() + 1;
if (index < 0 || index > value.length()) {
throw context.getRuntime().newIndexError("index " + index + " out of range");
}
modify();
value.unsafeReplace(index, 0, insert);
this.infectBy(s);
return this;
}
/** rb_str_inspect
*
*/
@JRubyMethod
@Override
public IRubyObject inspect() {
RubyString s = getRuntime().newString(inspectIntoByteList(false));
s.infectBy(this);
return s;
}
private ByteList inspectIntoByteList(boolean ignoreKCode) {
Ruby runtime = getRuntime();
Encoding enc = runtime.getKCode().getEncoding();
final int length = value.length();
ByteList sb = new ByteList(length + 2 + length / 100);
sb.append('\"');
for (int i = 0; i < length; i++) {
int c = value.get(i) & 0xFF;
if (!ignoreKCode) {
int seqLength = enc.length((byte)c);
if (seqLength > 1 && (i + seqLength -1 < length)) {
// don't escape multi-byte characters, leave them as bytes
sb.append(value, i, seqLength);
i += seqLength - 1;
continue;
}
}
if (isAlnum(c)) {
sb.append((char)c);
} else if (c == '\"' || c == '\\') {
sb.append('\\').append((char)c);
} else if (c == '#' && isEVStr(i, length)) {
sb.append('\\').append((char)c);
} else if (isPrint(c)) {
sb.append((char)c);
} else if (c == '\n') {
sb.append('\\').append('n');
} else if (c == '\r') {
sb.append('\\').append('r');
} else if (c == '\t') {
sb.append('\\').append('t');
} else if (c == '\f') {
sb.append('\\').append('f');
} else if (c == '\u000B') {
sb.append('\\').append('v');
} else if (c == '\u0007') {
sb.append('\\').append('a');
} else if (c == '\u0008') {
sb.append('\\').append('b');
} else if (c == '\u001B') {
sb.append('\\').append('e');
} else {
sb.append(ByteList.plain(Sprintf.sprintf(runtime,"\\%03o",c)));
}
}
sb.append('\"');
return sb;
}
private boolean isEVStr(int i, int length) {
if (i+1 >= length) return false;
int c = value.get(i+1) & 0xFF;
return c == '$' || c == '@' || c == '{';
}
/** rb_str_length
*
*/
@JRubyMethod(name = {"length", "size"})
public RubyFixnum length() {
return getRuntime().newFixnum(value.length());
}
/** rb_str_empty
*
*/
@JRubyMethod(name = "empty?")
public RubyBoolean empty_p(ThreadContext context) {
return isEmpty() ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
public boolean isEmpty() {
return value.length() == 0;
}
/** rb_str_append
*
*/
public RubyString append(IRubyObject other) {
infectBy(other);
return cat(stringValue(other).value);
}
/** rb_str_concat
*
*/
@JRubyMethod(name = {"concat", "<<"})
public RubyString concat(IRubyObject other) {
if (other instanceof RubyFixnum) {
long value = ((RubyFixnum) other).getLongValue();
if (value >= 0 && value < 256) return cat((byte) value);
}
return append(other);
}
/** rb_str_crypt
*
*/
@JRubyMethod(name = "crypt")
public RubyString crypt(ThreadContext context, IRubyObject other) {
ByteList salt = stringValue(other).getByteList();
if (salt.realSize < 2) {
throw context.getRuntime().newArgumentError("salt too short(need >=2 bytes)");
}
salt = salt.makeShared(0, 2);
RubyString s = RubyString.newStringShared(context.getRuntime(), JavaCrypt.crypt(salt, this.getByteList()));
s.infectBy(this);
s.infectBy(other);
return s;
}
/* RubyString aka rb_string_value */
public static RubyString stringValue(IRubyObject object) {
return (RubyString) (object instanceof RubyString ? object :
object.convertToString());
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one or two args.
*/
public IRubyObject sub(ThreadContext context, IRubyObject[] args, Block block) {
RubyString str = strDup(context.getRuntime());
str.sub_bang(context, args, block);
return str;
}
/** rb_str_sub
*
*/
@JRubyMethod(name = "sub", frame = true)
public IRubyObject sub(ThreadContext context, IRubyObject arg0, Block block) {
RubyString str = strDup(context.getRuntime());
str.sub_bang(context, arg0, block);
return str;
}
/** rb_str_sub
*
*/
@JRubyMethod(name = "sub", frame = true)
public IRubyObject sub(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
RubyString str = strDup(context.getRuntime());
str.sub_bang(context, arg0, arg1, block);
return str;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one or two arguments.
*/
public IRubyObject sub_bang(ThreadContext context, IRubyObject[] args, Block block) {
switch (args.length) {
case 1:
return sub_bang(context, args[0], block);
case 2:
return sub_bang(context, args[0], args[1], block);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_sub_bang
*
*/
@JRubyMethod(name = "sub!", frame = true, reads = BACKREF, writes = BACKREF)
public IRubyObject sub_bang(ThreadContext context, IRubyObject arg0, Block block) {
if (block.isGiven()) {
RubyRegexp rubyRegex = getPattern(arg0, true);
Regex regex = rubyRegex.getPattern();
return subBangCommon(regex, context, true, rubyRegex, block, null, false);
} else {
throw context.getRuntime().newArgumentError("wrong number of arguments (1 for 2)");
}
}
/** rb_str_sub_bang
*
*/
@JRubyMethod(name = "sub!", frame = true, reads = BACKREF, writes = BACKREF)
public IRubyObject sub_bang(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
RubyString repl = arg1.convertToString();
RubyRegexp rubyRegex = getPattern(arg0, true);
Regex regex = rubyRegex.getPattern();
return subBangCommon(regex, context, false, rubyRegex, block, repl, repl.isTaint());
}
private IRubyObject subBangCommon(Regex regex, ThreadContext context, final boolean iter, RubyRegexp rubyRegex, Block block, RubyString repl, boolean tainted) {
int range = value.begin + value.realSize;
Matcher matcher = regex.matcher(value.bytes, value.begin, range);
Frame frame = context.getPreviousFrame();
if (matcher.search(value.begin, range, Option.NONE) >= 0) {
if (iter) {
byte[] bytes = value.bytes;
int size = value.realSize;
RubyMatchData match = rubyRegex.updateBackRef(context, this, frame, matcher);
match.use();
if (regex.numberOfCaptures() == 0) {
repl = objAsString(context, block.yield(context, substr(matcher.getBegin(), matcher.getEnd() - matcher.getBegin())));
} else {
Region region = matcher.getRegion();
repl = objAsString(context, block.yield(context, substr(region.beg[0], region.end[0] - region.beg[0])));
}
modifyCheck(bytes, size);
frozenCheck();
frame.setBackRef(match);
} else {
repl = rubyRegex.regsub(repl, this, matcher);
rubyRegex.updateBackRef(context, this, frame, matcher);
}
final int beg;
final int plen;
if (regex.numberOfCaptures() == 0) {
beg = matcher.getBegin();
plen = matcher.getEnd() - beg;
} else {
Region region = matcher.getRegion();
beg = region.beg[0];
plen = region.end[0] - beg;
}
ByteList replValue = repl.value;
if (replValue.realSize > plen) {
modify(value.realSize + replValue.realSize - plen);
} else {
modify();
}
if (repl.isTaint()) {
tainted = true;
}
if (replValue.realSize != plen) {
int src = value.begin + beg + plen;
int dst = value.begin + beg + replValue.realSize;
int length = value.realSize - beg - plen;
System.arraycopy(value.bytes, src, value.bytes, dst, length);
}
System.arraycopy(replValue.bytes, replValue.begin, value.bytes, value.begin + beg, replValue.realSize);
value.realSize += replValue.realSize - plen;
if (tainted) {
setTaint(true);
}
return this;
} else {
frame.setBackRef(context.getRuntime().getNil());
return context.getRuntime().getNil();
}
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one or two arguments.
*/
public IRubyObject gsub(ThreadContext context, IRubyObject[] args, Block block) {
switch (args.length) {
case 1:
return gsub(context, args[0], block);
case 2:
return gsub(context, args[0], args[1], block);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_gsub
*
*/
@JRubyMethod(name = "gsub", frame = true, reads = BACKREF, writes = BACKREF)
public IRubyObject gsub(ThreadContext context, IRubyObject arg0, Block block) {
return gsub(context, arg0, block, false);
}
/** rb_str_gsub
*
*/
@JRubyMethod(name = "gsub", frame = true, reads = BACKREF, writes = BACKREF)
public IRubyObject gsub(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
return gsub(context, arg0, arg1, block, false);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one or two arguments.
*/
public IRubyObject gsub_bang(ThreadContext context, IRubyObject[] args, Block block) {
switch (args.length) {
case 1:
return gsub_bang(context, args[0], block);
case 2:
return gsub_bang(context, args[0], args[1], block);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_gsub_bang
*
*/
@JRubyMethod(name = "gsub!", frame = true, reads = BACKREF, writes = BACKREF)
public IRubyObject gsub_bang(ThreadContext context, IRubyObject arg0, Block block) {
return gsub(context, arg0, block, true);
}
/** rb_str_gsub_bang
*
*/
@JRubyMethod(name = "gsub!", frame = true, reads = BACKREF, writes = BACKREF)
public IRubyObject gsub_bang(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
return gsub(context, arg0, arg1, block, true);
}
private final IRubyObject gsub(ThreadContext context, IRubyObject arg0, Block block, final boolean bang) {
if (block.isGiven()) {
RubyRegexp rubyRegex = getPattern(arg0, true);
Regex regex = rubyRegex.getPattern();
return gsubCommon(regex, context, bang, true, rubyRegex, block, null, false);
} else {
throw context.getRuntime().newArgumentError("wrong number of arguments (1 for 2)");
}
}
private final IRubyObject gsub(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block, final boolean bang) {
IRubyObject repl = arg1.convertToString();
RubyRegexp rubyRegex = getPattern(arg0, true);
Regex regex = rubyRegex.getPattern();
return gsubCommon(regex, context, bang, false, rubyRegex, block, repl, repl.isTaint());
}
private IRubyObject gsubCommon(Regex regex, ThreadContext context, final boolean bang, final boolean iter, RubyRegexp rubyRegex, Block block, IRubyObject repl, boolean tainted) {
int begin = value.begin;
int range = begin + value.realSize;
Matcher matcher = regex.matcher(value.bytes, begin, range);
int beg = matcher.search(begin, range, Option.NONE);
Frame frame = context.getPreviousFrame();
if (beg < 0) {
frame.setBackRef(context.getRuntime().getNil());
return bang ? context.getRuntime().getNil() : strDup(context.getRuntime()); /* bang: true, no match, no substitution */
}
int blen = value.realSize + 30; /* len + margin */
ByteList dest = new ByteList(blen);
dest.realSize = blen;
int buf = 0;
int bp = 0;
int cp = value.begin;
int offset = 0;
RubyString val;
RubyMatchData match = null;
while (beg >= 0) {
final int begz;
final int endz;
if (iter) {
byte[] bytes = value.bytes;
int size = value.realSize;
match = rubyRegex.updateBackRef(context, this, frame, matcher);
match.use();
if (regex.numberOfCaptures() == 0) {
begz = matcher.getBegin();
endz = matcher.getEnd();
val = objAsString(context, block.yield(context, substr(context.getRuntime(), begz, endz - begz)));
} else {
Region region = matcher.getRegion();
begz = region.beg[0];
endz = region.end[0];
val = objAsString(context, block.yield(context, substr(context.getRuntime(), begz, endz - begz)));
}
modifyCheck(bytes, size);
if (bang) {
frozenCheck();
}
} else {
val = rubyRegex.regsub((RubyString) repl, this, matcher);
if (regex.numberOfCaptures() == 0) {
begz = matcher.getBegin();
endz = matcher.getEnd();
} else {
Region region = matcher.getRegion();
begz = region.beg[0];
endz = region.end[0];
}
}
if (val.isTaint()) {
tainted = true;
}
ByteList vbuf = val.value;
int len = (bp - buf) + (beg - offset) + vbuf.realSize + 3;
if (blen < len) {
while (blen < len) {
blen <<= 1;
}
len = bp - buf;
dest.realloc(blen);
dest.realSize = blen;
bp = buf + len;
}
len = beg - offset; /* copy pre-match substr */
System.arraycopy(value.bytes, cp, dest.bytes, bp, len);
bp += len;
System.arraycopy(vbuf.bytes, vbuf.begin, dest.bytes, bp, vbuf.realSize);
bp += vbuf.realSize;
offset = endz;
if (begz == endz) {
if (value.realSize <= endz) {
break;
}
len = regex.getEncoding().length(value.bytes[begin + endz]);
System.arraycopy(value.bytes, begin + endz, dest.bytes, bp, len);
bp += len;
offset = endz + len;
}
cp = begin + offset;
if (offset > value.realSize) {
break;
}
beg = matcher.search(cp, range, Option.NONE);
}
if (value.realSize > offset) {
int len = bp - buf;
if (blen - len < value.realSize - offset) {
blen = len + value.realSize - offset;
dest.realloc(blen);
bp = buf + len;
}
System.arraycopy(value.bytes, cp, dest.bytes, bp, value.realSize - offset);
bp += value.realSize - offset;
}
if (match != null) {
frame.setBackRef(match);
} else {
rubyRegex.updateBackRef(context, this, frame, matcher);
}
dest.realSize = bp - buf;
if (bang) {
view(dest);
if (tainted) {
setTaint(true);
}
return this;
} else {
RubyString destStr = new RubyString(context.getRuntime(), getMetaClass(), dest);
destStr.infectBy(this);
if (tainted) {
destStr.setTaint(true);
}
return destStr;
}
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one or two args.
*/
public IRubyObject index(ThreadContext context, IRubyObject[] args) {
switch (args.length) {
case 1:
return index(context, args[0]);
case 2:
return index(context, args[0], args[1]);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_index_m
*
*/
@JRubyMethod(reads = BACKREF, writes = BACKREF)
public IRubyObject index(ThreadContext context, IRubyObject arg0) {
return indexCommon(0, arg0, context);
}
/** rb_str_index_m
*
*/
@JRubyMethod(reads = BACKREF, writes = BACKREF)
public IRubyObject index(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
int pos = RubyNumeric.num2int(arg1);
if (pos < 0) {
pos += value.realSize;
if (pos < 0) {
if (arg0 instanceof RubyRegexp) {
context.getPreviousFrame().setBackRef(context.getRuntime().getNil());
}
return context.getRuntime().getNil();
}
}
return indexCommon(pos, arg0, context);
}
private IRubyObject indexCommon(int pos, IRubyObject sub, ThreadContext context) throws RaiseException {
if (sub instanceof RubyRegexp) {
RubyRegexp regSub = (RubyRegexp) sub;
pos = regSub.adjustStartPos(this, pos, false);
pos = regSub.search(context, this, pos, false);
} else if (sub instanceof RubyFixnum) {
int c_int = RubyNumeric.fix2int(sub);
if (c_int < 0x00 || c_int > 0xFF) {
// out of byte range
// there will be no match for sure
return context.getRuntime().getNil();
}
byte c = (byte) c_int;
byte[] bytes = value.bytes;
int end = value.begin + value.realSize;
pos += value.begin;
for (; pos < end; pos++) {
if (bytes[pos] == c) {
return RubyFixnum.newFixnum(context.getRuntime(), pos - value.begin);
}
}
return context.getRuntime().getNil();
} else if (sub instanceof RubyString) {
pos = strIndex((RubyString) sub, pos);
} else {
IRubyObject tmp = sub.checkStringType();
if (tmp.isNil()) {
throw context.getRuntime().newTypeError("type mismatch: " + sub.getMetaClass().getName() + " given");
}
pos = strIndex((RubyString) tmp, pos);
}
return pos == -1 ? context.getRuntime().getNil() : RubyFixnum.newFixnum(context.getRuntime(), pos);
}
private int strIndex(RubyString sub, int offset) {
if (offset < 0) {
offset += value.realSize;
if (offset < 0) return -1;
}
if (value.realSize - offset < sub.value.realSize) return -1;
if (sub.value.realSize == 0) return offset;
return value.indexOf(sub.value, offset);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one or two arguments.
*/
public IRubyObject rindex(ThreadContext context, IRubyObject[] args) {
switch (args.length) {
case 1:
return rindex(context, args[0]);
case 2:
return rindex(context, args[0], args[1]);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_rindex_m
*
*/
@JRubyMethod(reads = BACKREF, writes = BACKREF)
public IRubyObject rindex(ThreadContext context, IRubyObject arg0) {
return rindexCommon(arg0, value.realSize, context);
}
/** rb_str_rindex_m
*
*/
@JRubyMethod(reads = BACKREF, writes = BACKREF)
public IRubyObject rindex(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
int pos = RubyNumeric.num2int(arg1);
if (pos < 0) {
pos += value.realSize;
if (pos < 0) {
if (arg0 instanceof RubyRegexp) {
context.getPreviousFrame().setBackRef(context.getRuntime().getNil());
}
return context.getRuntime().getNil();
}
}
if (pos > value.realSize) pos = value.realSize;
return rindexCommon(arg0, pos, context);
}
private IRubyObject rindexCommon(final IRubyObject sub, int pos, ThreadContext context) throws RaiseException {
if (sub instanceof RubyRegexp) {
RubyRegexp regSub = (RubyRegexp) sub;
if (regSub.length() > 0) {
pos = regSub.adjustStartPos(this, pos, true);
pos = regSub.search(context, this, pos, true);
}
if (pos >= 0) {
return RubyFixnum.newFixnum(context.getRuntime(), pos);
}
} else if (sub instanceof RubyString) {
pos = strRindex((RubyString) sub, pos);
if (pos >= 0) return RubyFixnum.newFixnum(context.getRuntime(), pos);
} else if (sub instanceof RubyFixnum) {
int c_int = RubyNumeric.fix2int(sub);
if (c_int < 0x00 || c_int > 0xFF) {
// out of byte range
// there will be no match for sure
return context.getRuntime().getNil();
}
byte c = (byte) c_int;
byte[] bytes = value.bytes;
int pbeg = value.begin;
int p = pbeg + pos;
if (pos == value.realSize) {
if (pos == 0) {
return context.getRuntime().getNil();
}
--p;
}
while (pbeg <= p) {
if (bytes[p] == c) {
return RubyFixnum.newFixnum(context.getRuntime(), p - value.begin);
}
p--;
}
return context.getRuntime().getNil();
} else {
IRubyObject tmp = sub.checkStringType();
if (tmp.isNil()) throw context.getRuntime().newTypeError("type mismatch: " + sub.getMetaClass().getName() + " given");
pos = strRindex((RubyString) tmp, pos);
if (pos >= 0) return RubyFixnum.newFixnum(context.getRuntime(), pos);
}
return context.getRuntime().getNil();
}
private int strRindex(RubyString sub, int pos) {
int subLength = sub.value.realSize;
/* substring longer than string */
if (value.realSize < subLength) return -1;
if (value.realSize - pos < subLength) pos = value.realSize - subLength;
return value.lastIndexOf(sub.value, pos);
}
/* rb_str_substr */
public IRubyObject substr(int beg, int len) {
return substr(getRuntime(), beg, len);
}
public IRubyObject substr(Ruby runtime, int beg, int len) {
int length = value.length();
if (len < 0 || beg > length) return getRuntime().getNil();
if (beg < 0) {
beg += length;
if (beg < 0) return getRuntime().getNil();
}
int end = Math.min(length, beg + len);
return makeShared(getRuntime(), beg, end - beg);
}
/* rb_str_replace */
public IRubyObject replace(int beg, int len, RubyString replaceWith) {
if (beg + len >= value.length()) len = value.length() - beg;
modify();
value.unsafeReplace(beg,len,replaceWith.value);
return infectBy(replaceWith);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the versions with one or two args
*/
public IRubyObject op_aref(ThreadContext context, IRubyObject[] args) {
switch (args.length) {
case 1:
return op_aref(context, args[0]);
case 2:
return op_aref(context, args[0], args[1]);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_aref, rb_str_aref_m
*
*/
@JRubyMethod(name = {"[]", "slice"}, reads = BACKREF, writes = BACKREF)
public IRubyObject op_aref(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
if (arg1 instanceof RubyRegexp) {
if(((RubyRegexp)arg1).search(context, this, 0, false) >= 0) {
return RubyRegexp.nth_match(RubyNumeric.fix2int(arg2), context.getCurrentFrame().getBackRef());
}
return context.getRuntime().getNil();
}
return substr(context.getRuntime(), RubyNumeric.fix2int(arg1), RubyNumeric.fix2int(arg2));
}
/** rb_str_aref, rb_str_aref_m
*
*/
@JRubyMethod(name = {"[]", "slice"}, reads = BACKREF, writes = BACKREF)
public IRubyObject op_aref(ThreadContext context, IRubyObject arg) {
if (arg instanceof RubyRegexp) {
if(((RubyRegexp)arg).search(context, this, 0, false) >= 0) {
return RubyRegexp.nth_match(0, context.getCurrentFrame().getBackRef());
}
return context.getRuntime().getNil();
} else if (arg instanceof RubyString) {
return value.indexOf(stringValue(arg).value) != -1 ?
arg : context.getRuntime().getNil();
} else if (arg instanceof RubyRange) {
long[] begLen = ((RubyRange) arg).begLen(value.length(), 0);
return begLen == null ? context.getRuntime().getNil() :
substr(context.getRuntime(), (int) begLen[0], (int) begLen[1]);
}
int idx = (int) arg.convertToInteger().getLongValue();
if (idx < 0) idx += value.length();
if (idx < 0 || idx >= value.length()) return context.getRuntime().getNil();
return context.getRuntime().newFixnum(value.get(idx) & 0xFF);
}
/**
* rb_str_subpat_set
*
*/
private void subpatSet(ThreadContext context, RubyRegexp regexp, int nth, IRubyObject repl) {
RubyMatchData match;
int start, end, len;
if (regexp.search(context, this, 0, false) < 0) throw context.getRuntime().newIndexError("regexp not matched");
match = (RubyMatchData)context.getCurrentFrame().getBackRef();
if (match.regs == null) {
if (nth >= 1) throw context.getRuntime().newIndexError("index " + nth + " out of regexp");
if (nth < 0) {
if(-nth >= 1) throw context.getRuntime().newIndexError("index " + nth + " out of regexp");
nth += 1;
}
start = match.begin;
if(start == -1) throw context.getRuntime().newIndexError("regexp group " + nth + " not matched");
end = match.end;
} else {
if(nth >= match.regs.numRegs) throw context.getRuntime().newIndexError("index " + nth + " out of regexp");
if(nth < 0) {
if(-nth >= match.regs.numRegs) throw context.getRuntime().newIndexError("index " + nth + " out of regexp");
nth += match.regs.numRegs;
}
start = match.regs.beg[nth];
if(start == -1) throw context.getRuntime().newIndexError("regexp group " + nth + " not matched");
end = match.regs.end[nth];
}
len = end - start;
replace(start, len, stringValue(repl));
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with two or three args.
*/
public IRubyObject op_aset(ThreadContext context, IRubyObject[] args) {
switch (args.length) {
case 2:
return op_aset(context, args[0], args[1]);
case 3:
return op_aset(context, args[0], args[1], args[2]);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 2, 3);
return null; // not reached
}
}
/** rb_str_aset, rb_str_aset_m
*
*/
@JRubyMethod(name = "[]=", reads = BACKREF)
public IRubyObject op_aset(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
if (arg0 instanceof RubyFixnum || arg0.respondsTo("to_int")) { // FIXME: RubyNumeric or RubyInteger instead?
int idx = RubyNumeric.fix2int(arg0);
if (idx < 0) idx += value.length();
if (idx < 0 || idx >= value.length()) {
throw context.getRuntime().newIndexError("string index out of bounds");
}
if (arg1 instanceof RubyFixnum) {
modify();
value.set(idx, (byte) RubyNumeric.fix2int(arg1));
} else {
replace(idx, 1, stringValue(arg1));
}
return arg1;
}
if (arg0 instanceof RubyRegexp) {
RubyString repl = stringValue(arg1);
subpatSet(context, (RubyRegexp) arg0, 0, repl);
return repl;
}
if (arg0 instanceof RubyString) {
RubyString orig = (RubyString)arg0;
int beg = value.indexOf(orig.value);
if (beg < 0) throw context.getRuntime().newIndexError("string not matched");
replace(beg, orig.value.length(), stringValue(arg1));
return arg1;
}
if (arg0 instanceof RubyRange) {
long[] begLen = ((RubyRange) arg0).begLen(value.realSize, 2);
replace((int) begLen[0], (int) begLen[1], stringValue(arg1));
return arg1;
}
throw context.getRuntime().newTypeError("wrong argument type");
}
/** rb_str_aset, rb_str_aset_m
*
*/
@JRubyMethod(name = "[]=", reads = BACKREF)
public IRubyObject op_aset(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
if (arg0 instanceof RubyRegexp) {
RubyString repl = stringValue(arg2);
int nth = RubyNumeric.fix2int(arg1);
subpatSet(context, (RubyRegexp) arg0, nth, repl);
return repl;
}
RubyString repl = stringValue(arg2);
int beg = RubyNumeric.fix2int(arg0);
int len = RubyNumeric.fix2int(arg1);
if (len < 0) throw context.getRuntime().newIndexError("negative length");
int strLen = value.length();
if (beg < 0) beg += strLen;
if (beg < 0 || (beg > 0 && beg > strLen)) {
throw context.getRuntime().newIndexError("string index out of bounds");
}
if (beg + len > strLen) len = strLen - beg;
replace(beg, len, repl);
return repl;
}
/**
* Variable arity version for compatibility. Not bound as a Ruby method.
* @deprecated Use the versions with one or two args.
*/
public IRubyObject slice_bang(ThreadContext context, IRubyObject[] args) {
switch (args.length) {
case 1:
return slice_bang(context, args[0]);
case 2:
return slice_bang(context, args[0], args[1]);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_slice_bang
*
*/
@JRubyMethod(name = "slice!", reads = BACKREF, writes = BACKREF)
public IRubyObject slice_bang(ThreadContext context, IRubyObject arg0) {
IRubyObject result = op_aref(context, arg0);
if (result.isNil()) return result;
op_aset(context, arg0, RubyString.newEmptyString(context.getRuntime()));
return result;
}
/** rb_str_slice_bang
*
*/
@JRubyMethod(name = "slice!", reads = BACKREF, writes = BACKREF)
public IRubyObject slice_bang(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
IRubyObject result = op_aref(context, arg0, arg1);
if (result.isNil()) return result;
op_aset(context, arg0, arg1, RubyString.newEmptyString(context.getRuntime()));
return result;
}
@JRubyMethod(name = {"succ", "next"})
public IRubyObject succ(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.succ_bang();
return str;
}
@JRubyMethod(name = {"succ!", "next!"})
public IRubyObject succ_bang() {
if (value.length() == 0) {
modifyCheck();
return this;
}
modify();
boolean alnumSeen = false;
int pos = -1;
int c = 0;
int n = 0;
for (int i = value.length() - 1; i >= 0; i--) {
c = value.get(i) & 0xFF;
if (isAlnum(c)) {
alnumSeen = true;
if ((isDigit(c) && c < '9') || (isLower(c) && c < 'z') || (isUpper(c) && c < 'Z')) {
value.set(i, (byte)(c + 1));
pos = -1;
break;
}
pos = i;
n = isDigit(c) ? '1' : (isLower(c) ? 'a' : 'A');
value.set(i, (byte)(isDigit(c) ? '0' : (isLower(c) ? 'a' : 'A')));
}
}
if (!alnumSeen) {
for (int i = value.length() - 1; i >= 0; i--) {
c = value.get(i) & 0xFF;
if (c < 0xff) {
value.set(i, (byte)(c + 1));
pos = -1;
break;
}
pos = i;
n = '\u0001';
value.set(i, 0);
}
}
if (pos > -1) {
// This represents left most digit in a set of incremented
// values? Therefore leftmost numeric must be '1' and not '0'
// 999 -> 1000, not 999 -> 0000. whereas chars should be
// zzz -> aaaa and non-alnum byte values should be "\377" -> "\001\000"
value.insert(pos, (byte) n);
}
return this;
}
/** rb_str_upto_m
*
*/
@JRubyMethod(name = "upto", required = 1, frame = true)
public IRubyObject upto(ThreadContext context, IRubyObject str, Block block) {
return upto(context, str, false, block);
}
/* rb_str_upto */
public IRubyObject upto(ThreadContext context, IRubyObject str, boolean excl, Block block) {
RubyString end = str.convertToString();
int n = value.cmp(end.value);
if (n > 0 || (excl && n == 0)) return this;
IRubyObject afterEnd = end.callMethod(context, "succ");
RubyString current = this;
while (!current.op_equal(context, afterEnd).isTrue()) {
block.yield(context, current);
if (!excl && current.op_equal(context, end).isTrue()) break;
current = current.callMethod(context, "succ").convertToString();
if (excl && current.op_equal(context, end).isTrue()) break;
if (current.value.realSize > end.value.realSize || current.value.realSize == 0) break;
}
return this;
}
/** rb_str_include
*
*/
@JRubyMethod(name = "include?", required = 1)
public RubyBoolean include_p(ThreadContext context, IRubyObject obj) {
if (obj instanceof RubyFixnum) {
int c = RubyNumeric.fix2int(obj);
for (int i = 0; i < value.length(); i++) {
if (value.get(i) == (byte)c) {
return context.getRuntime().getTrue();
}
}
return context.getRuntime().getFalse();
}
ByteList str = stringValue(obj).value;
return context.getRuntime().newBoolean(value.indexOf(str) != -1);
}
/**
* Variable-arity version for compatibility. Not bound as a Ruby method.
* @deprecated Use the versions with zero or one args.
*/
public IRubyObject to_i(IRubyObject[] args) {
switch (args.length) {
case 0:
return to_i();
case 1:
return to_i(args[0]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 0, 1);
return null; // not reached
}
}
/** rb_str_to_i
*
*/
@JRubyMethod(name = "to_i")
public IRubyObject to_i() {
return RubyNumeric.str2inum(getRuntime(), this, 10);
}
/** rb_str_to_i
*
*/
@JRubyMethod(name = "to_i")
public IRubyObject to_i(IRubyObject arg0) {
long base = arg0.convertToInteger().getLongValue();
return RubyNumeric.str2inum(getRuntime(), this, (int) base);
}
/** rb_str_oct
*
*/
@JRubyMethod(name = "oct")
public IRubyObject oct(ThreadContext context) {
if (isEmpty()) return context.getRuntime().newFixnum(0);
int base = 8;
int ix = value.begin;
while(ix < value.begin+value.realSize && ASCII.isSpace(value.bytes[ix] & 0xff)) {
ix++;
}
int pos = (value.bytes[ix] == '-' || value.bytes[ix] == '+') ? ix+1 : ix;
if((pos+1) < value.begin+value.realSize && value.bytes[pos] == '0') {
if(value.bytes[pos+1] == 'x' || value.bytes[pos+1] == 'X') {
base = 16;
} else if(value.bytes[pos+1] == 'b' || value.bytes[pos+1] == 'B') {
base = 2;
} else if(value.bytes[pos+1] == 'd' || value.bytes[pos+1] == 'D') {
base = 10;
}
}
return RubyNumeric.str2inum(context.getRuntime(), this, base);
}
/** rb_str_hex
*
*/
@JRubyMethod(name = "hex")
public IRubyObject hex(ThreadContext context) {
return RubyNumeric.str2inum(context.getRuntime(), this, 16);
}
/** rb_str_to_f
*
*/
@JRubyMethod(name = "to_f")
public IRubyObject to_f() {
return RubyNumeric.str2fnum(getRuntime(), this);
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
* @deprecated Use the versions with zero, one, or two args.
*/
public RubyArray split(ThreadContext context, IRubyObject[] args) {
switch (args.length) {
case 0:
return split(context);
case 1:
return split(context, args[0]);
case 2:
return split(context, args[0], args[1]);
default:
Arity.raiseArgumentError(context.getRuntime(), args.length, 0, 2);
return null; // not reached
}
}
/** rb_str_split_m
*
*/
@JRubyMethod(writes = BACKREF)
public RubyArray split(ThreadContext context) {
return split(context, context.getRuntime().getNil());
}
/** rb_str_split_m
*
*/
@JRubyMethod(writes = BACKREF)
public RubyArray split(ThreadContext context, IRubyObject arg0) {
return splitCommon(arg0, false, 0, 0, context);
}
/** rb_str_split_m
*
*/
@JRubyMethod(writes = BACKREF)
public RubyArray split(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
final int lim = RubyNumeric.fix2int(arg1);
if (lim <= 0) {
return splitCommon(arg0, false, lim, 1, context);
} else {
if (lim == 1) return value.realSize == 0 ? context.getRuntime().newArray() : context.getRuntime().newArray(this);
return splitCommon(arg0, true, lim, 1, context);
}
}
private RubyArray splitCommon(IRubyObject spat, final boolean limit, final int lim, final int i, ThreadContext context) {
final RubyArray result;
if (spat.isNil() && (spat = context.getRuntime().getGlobalVariables().get("$;")).isNil()) {
result = awkSplit(limit, lim, i);
} else {
if (spat instanceof RubyString && ((RubyString) spat).value.realSize == 1) {
RubyString strSpat = (RubyString) spat;
if (strSpat.value.bytes[strSpat.value.begin] == (byte) ' ') {
result = awkSplit(limit, lim, i);
} else {
result = split(context, spat, limit, lim, i);
}
} else {
result = split(context, spat, limit, lim, i);
}
}
if (!limit && lim == 0) {
while (result.size() > 0 && ((RubyString) result.eltInternal(result.size() - 1)).value.realSize == 0) {
result.pop();
}
}
return result;
}
private RubyArray split(ThreadContext context, IRubyObject pat, boolean limit, int lim, int i) {
Ruby runtime = context.getRuntime();
final Regex regex = getPattern(pat, true).getPattern();
int beg, end, start;
int begin = value.begin;
start = begin;
beg = 0;
int range = value.begin + value.realSize;
final Matcher matcher = regex.matcher(value.bytes, value.begin, range);
boolean lastNull = false;
RubyArray result = runtime.newArray();
if (regex.numberOfCaptures() == 0) { // shorter path, no captures defined, no region will be returned
while ((end = matcher.search(start, range, Option.NONE)) >= 0) {
if (start == end + begin && matcher.getBegin() == matcher.getEnd()) {
if (value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if (lastNull) {
result.append(substr(runtime, beg, regex.getEncoding().length(value.bytes[begin + beg])));
beg = start - begin;
} else {
if (start == range) {
start++;
} else {
start += regex.getEncoding().length(value.bytes[start]);
}
lastNull = true;
continue;
}
} else {
result.append(substr(beg, end - beg));
beg = matcher.getEnd();
start = begin + matcher.getEnd();
}
lastNull = false;
if (limit && lim <= ++i) break;
}
} else {
while ((end = matcher.search(start, range, Option.NONE)) >= 0) {
final Region region = matcher.getRegion();
if (start == end + begin && region.beg[0] == region.end[0]) {
if (value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if (lastNull) {
result.append(substr(beg, regex.getEncoding().length(value.bytes[begin + beg])));
beg = start - begin;
} else {
if (start == range) {
start++;
} else {
start += regex.getEncoding().length(value.bytes[start]);
}
lastNull = true;
continue;
}
} else {
result.append(substr(beg, end - beg));
beg = start = region.end[0];
start += begin;
}
lastNull = false;
for (int idx=1; idx<region.numRegs; idx++) {
if (region.beg[idx] == -1) continue;
if (region.beg[idx] == region.end[idx]) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(region.beg[idx], region.end[idx] - region.beg[idx]));
}
}
if (limit && lim <= ++i) break;
}
}
// only this case affects backrefs
context.getCurrentFrame().setBackRef(runtime.getNil());
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.realSize == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(beg, value.realSize - beg));
}
}
return result;
}
private RubyArray awkSplit(boolean limit, int lim, int i) {
Ruby runtime = getRuntime();
RubyArray result = runtime.newArray();
byte[]bytes = value.bytes;
int p = value.begin;
int endp = p + value.realSize;
boolean skip = true;
int end, beg = 0;
for (end = beg = 0; p < endp; p++) {
if (skip) {
if (ASCII.isSpace(bytes[p] & 0xff)) {
beg++;
} else {
end = beg + 1;
skip = false;
if (limit && lim <= i) break;
}
} else {
if (ASCII.isSpace(bytes[p] & 0xff)) {
result.append(makeShared(runtime, beg, end - beg));
skip = true;
beg = end + 1;
if (limit) i++;
} else {
end++;
}
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.realSize == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(makeShared(runtime, beg, value.realSize - beg));
}
}
return result;
}
/** get_pat
*
*/
private final RubyRegexp getPattern(IRubyObject obj, boolean quote) {
if (obj instanceof RubyRegexp) {
return (RubyRegexp)obj;
} else if (!(obj instanceof RubyString)) {
IRubyObject val = obj.checkStringType();
if (val.isNil()) throw getRuntime().newTypeError("wrong argument type " + obj.getMetaClass() + " (expected Regexp)");
obj = val;
}
return RubyRegexp.newRegexp(getRuntime(), ((RubyString)obj).value, 0, quote);
}
/** rb_str_scan
*
*/
@JRubyMethod(name = "scan", required = 1, frame = true, reads = BACKREF, writes = BACKREF)
public IRubyObject scan(ThreadContext context, IRubyObject arg, Block block) {
Ruby runtime = context.getRuntime();
Frame frame = context.getPreviousFrame();
final RubyRegexp rubyRegex = getPattern(arg, true);
final Regex regex = rubyRegex.getPattern();
int range = value.begin + value.realSize;
final Matcher matcher = regex.matcher(value.bytes, value.begin, range);
matcher.value = 0; // implicit start argument to scanOnce(NG)
IRubyObject result;
if (!block.isGiven()) {
RubyArray ary = runtime.newArray();
if (regex.numberOfCaptures() == 0) {
while ((result = scanOnceNG(rubyRegex, matcher, range)) != null) ary.append(result);
} else {
while ((result = scanOnce(rubyRegex, matcher, range)) != null) ary.append(result);
}
if (ary.size() > 0) {
rubyRegex.updateBackRef(context, this, frame, matcher);
} else {
frame.setBackRef(runtime.getNil());
}
return ary;
} else {
byte[]bytes = value.bytes;
int size = value.realSize;
RubyMatchData match = null;
if (regex.numberOfCaptures() == 0) {
while ((result = scanOnceNG(rubyRegex, matcher, range)) != null) {
match = rubyRegex.updateBackRef(context, this, frame, matcher);
match.use();
block.yield(context, result);
modifyCheck(bytes, size);
}
} else {
while ((result = scanOnce(rubyRegex, matcher, range)) != null) {
match = rubyRegex.updateBackRef(context, this, frame, matcher);
match.use();
block.yield(context, result);
modifyCheck(bytes, size);
}
}
frame.setBackRef(match == null ? runtime.getNil() : match);
return this;
}
}
/**
* rb_enc_check
*/
@SuppressWarnings("unused")
private Encoding encodingCheck(RubyRegexp pattern) {
// For 1.9 compatibility, should check encoding compat between string and pattern
return pattern.getKCode().getEncoding();
}
// no group version
private IRubyObject scanOnceNG(RubyRegexp regex, Matcher matcher, int range) {
if (matcher.search(matcher.value + value.begin, range, Option.NONE) >= 0) {
int end = matcher.getEnd();
if (matcher.getBegin() == end) {
if (value.realSize > end) {
matcher.value = end + regex.getPattern().getEncoding().length(value.bytes[value.begin + end]);
} else {
matcher.value = end + 1;
}
} else {
matcher.value = end;
}
return substr(matcher.getBegin(), end - matcher.getBegin()).infectBy(regex);
}
return null;
}
// group version
private IRubyObject scanOnce(RubyRegexp regex, Matcher matcher, int range) {
if (matcher.search(matcher.value + value.begin, range, Option.NONE) >= 0) {
Region region = matcher.getRegion();
int end = region.end[0];
if (region.beg[0] == end) {
if (value.realSize > end) {
matcher.value = end + regex.getPattern().getEncoding().length(value.bytes[value.begin + end]);
} else {
matcher.value = end + 1;
}
} else {
matcher.value = end;
}
RubyArray result = getRuntime().newArray(region.numRegs);
for (int i=1; i<region.numRegs; i++) {
int beg = region.beg[i];
if (beg == -1) {
result.append(getRuntime().getNil());
} else {
result.append(substr(beg, region.end[i] - beg).infectBy(regex));
}
}
return result;
}
return null;
}
private static final ByteList SPACE_BYTELIST = new ByteList(ByteList.plain(" "));
private final IRubyObject justify(IRubyObject arg0, char jflag) {
Ruby runtime = getRuntime();
int width = RubyFixnum.num2int(arg0);
int f, flen = 0;
byte[]fbuf;
IRubyObject pad;
f = SPACE_BYTELIST.begin;
flen = SPACE_BYTELIST.realSize;
fbuf = SPACE_BYTELIST.bytes;
pad = runtime.getNil();
return justifyCommon(width, jflag, flen, fbuf, f, runtime, pad);
}
private final IRubyObject justify(IRubyObject arg0, IRubyObject arg1, char jflag) {
Ruby runtime = getRuntime();
int width = RubyFixnum.num2int(arg0);
int f, flen = 0;
byte[]fbuf;
IRubyObject pad;
pad = arg1.convertToString();
ByteList fList = ((RubyString)pad).value;
f = fList.begin;
flen = fList.realSize;
if (flen == 0) throw runtime.newArgumentError("zero width padding");
fbuf = fList.bytes;
return justifyCommon(width, jflag, flen, fbuf, f, runtime, pad);
}
private IRubyObject justifyCommon(int width, char jflag, int flen, byte[] fbuf, int f, Ruby runtime, IRubyObject pad) {
if (width < 0 || value.realSize >= width) return strDup(runtime);
ByteList res = new ByteList(width);
res.realSize = width;
int p = res.begin;
int pend;
byte[] pbuf = res.bytes;
if (jflag != 'l') {
int n = width - value.realSize;
pend = p + ((jflag == 'r') ? n : n / 2);
if (flen <= 1) {
while (p < pend) {
pbuf[p++] = fbuf[f];
}
} else {
int q = f;
while (p + flen <= pend) {
System.arraycopy(fbuf, f, pbuf, p, flen);
p += flen;
}
while (p < pend) {
pbuf[p++] = fbuf[q++];
}
}
}
System.arraycopy(value.bytes, value.begin, pbuf, p, value.realSize);
if (jflag != 'r') {
p += value.realSize;
pend = res.begin + width;
if (flen <= 1) {
while (p < pend) {
pbuf[p++] = fbuf[f];
}
} else {
while (p + flen <= pend) {
System.arraycopy(fbuf, f, pbuf, p, flen);
p += flen;
}
while (p < pend) {
pbuf[p++] = fbuf[f++];
}
}
}
RubyString resStr = new RubyString(runtime, getMetaClass(), res);
resStr.infectBy(this);
if (flen > 0) {
resStr.infectBy(pad);
}
return resStr;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated use the one or two argument versions.
*/
public IRubyObject ljust(IRubyObject [] args) {
switch (args.length) {
case 1:
return ljust(args[0]);
case 2:
return ljust(args[0], args[1]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_ljust
*
*/
@JRubyMethod
public IRubyObject ljust(IRubyObject arg0) {
return justify(arg0, 'l');
}
/** rb_str_ljust
*
*/
@JRubyMethod
public IRubyObject ljust(IRubyObject arg0, IRubyObject arg1) {
return justify(arg0, arg1, 'l');
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated use the one or two argument versions.
*/
public IRubyObject rjust(IRubyObject [] args) {
switch (args.length) {
case 1:
return rjust(args[0]);
case 2:
return rjust(args[0], args[1]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_rjust
*
*/
@JRubyMethod
public IRubyObject rjust(IRubyObject arg0) {
return justify(arg0, 'r');
}
/** rb_str_rjust
*
*/
@JRubyMethod
public IRubyObject rjust(IRubyObject arg0, IRubyObject arg1) {
return justify(arg0, arg1, 'r');
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated use the one or two argument versions.
*/
public IRubyObject center(IRubyObject [] args) {
switch (args.length) {
case 1:
return center(args[0]);
case 2:
return center(args[0], args[1]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 1, 2);
return null; // not reached
}
}
/** rb_str_center
*
*/
@JRubyMethod
public IRubyObject center(IRubyObject arg0) {
return justify(arg0, 'c');
}
/** rb_str_center
*
*/
@JRubyMethod
public IRubyObject center(IRubyObject arg0, IRubyObject arg1) {
return justify(arg0, arg1, 'c');
}
@JRubyMethod(name = "chop")
public IRubyObject chop(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.chop_bang();
return str;
}
/** rb_str_chop_bang
*
*/
@JRubyMethod(name = "chop!")
public IRubyObject chop_bang() {
int end = value.realSize - 1;
if (end < 0) return getRuntime().getNil();
if ((value.bytes[value.begin + end]) == '\n') {
if (end > 0 && (value.bytes[value.begin + end - 1]) == '\r') end--;
}
view(0, end);
return this;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby
*
* @param args
* @return
* @deprecated Use the zero or one argument versions.
*/
public RubyString chomp(IRubyObject[] args) {
switch (args.length) {
case 0:
return chomp();
case 1:
return chomp(args[0]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 0, 1);
return null; // not reached
}
}
/** rb_str_chop
*
*/
@JRubyMethod
public RubyString chomp() {
RubyString str = strDup(getRuntime());
str.chomp_bang();
return str;
}
/** rb_str_chop
*
*/
@JRubyMethod
public RubyString chomp(IRubyObject arg0) {
RubyString str = strDup(getRuntime());
str.chomp_bang(arg0);
return str;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the zero or one argument versions.
*/
public IRubyObject chomp_bang(IRubyObject[] args) {
switch (args.length) {
case 0:
return chomp_bang();
case 1:
return chomp_bang(args[0]);
default:
Arity.raiseArgumentError(getRuntime(), args.length, 0, 1);
return null; // not reached
}
}
/**
* rb_str_chomp_bang
*
* In the common case, removes CR and LF characters in various ways depending on the value of
* the optional args[0].
* If args.length==0 removes one instance of CR, CRLF or LF from the end of the string.
* If args.length>0 and args[0] is "\n" then same behaviour as args.length==0 .
* If args.length>0 and args[0] is "" then removes trailing multiple LF or CRLF (but no CRs at
* all(!)).
* @param args See method description.
*/
@JRubyMethod(name = "chomp!")
public IRubyObject chomp_bang() {
IRubyObject rsObj;
int len = value.length();
if (len == 0) return getRuntime().getNil();
byte[]buff = value.bytes;
rsObj = getRuntime().getGlobalVariables().get("$/");
if (rsObj == getRuntime().getGlobalVariables().getDefaultSeparator()) {
int realSize = value.realSize;
int begin = value.begin;
if (buff[begin + len - 1] == (byte)'\n') {
realSize--;
if (realSize > 0 && buff[begin + realSize - 1] == (byte)'\r') realSize--;
view(0, realSize);
} else if (buff[begin + len - 1] == (byte)'\r') {
realSize--;
view(0, realSize);
} else {
modifyCheck();
return getRuntime().getNil();
}
return this;
}
return chompBangCommon(rsObj);
}
/**
* rb_str_chomp_bang
*
* In the common case, removes CR and LF characters in various ways depending on the value of
* the optional args[0].
* If args.length==0 removes one instance of CR, CRLF or LF from the end of the string.
* If args.length>0 and args[0] is "\n" then same behaviour as args.length==0 .
* If args.length>0 and args[0] is "" then removes trailing multiple LF or CRLF (but no CRs at
* all(!)).
* @param args See method description.
*/
@JRubyMethod(name = "chomp!")
public IRubyObject chomp_bang(IRubyObject arg0) {
return chompBangCommon(arg0);
}
private IRubyObject chompBangCommon(IRubyObject rsObj) {
if (rsObj.isNil()) {
return getRuntime().getNil();
}
RubyString rs = rsObj.convertToString();
int len = value.realSize;
int begin = value.begin;
if (len == 0) {
return getRuntime().getNil();
}
byte[] buff = value.bytes;
int rslen = rs.value.realSize;
if (rslen == 0) {
while (len > 0 && buff[begin + len - 1] == (byte) '\n') {
len--;
if (len > 0 && buff[begin + len - 1] == (byte) '\r') {
len--;
}
}
if (len < value.realSize) {
view(0, len);
return this;
}
return getRuntime().getNil();
}
if (rslen > len) {
return getRuntime().getNil();
}
byte newline = rs.value.bytes[rslen - 1];
if (rslen == 1 && newline == (byte) '\n') {
buff = value.bytes;
int realSize = value.realSize;
if (buff[begin + len - 1] == (byte) '\n') {
realSize--;
if (realSize > 0 && buff[begin + realSize - 1] == (byte) '\r') {
realSize--;
}
view(0, realSize);
} else if (buff[begin + len - 1] == (byte) '\r') {
realSize--;
view(0, realSize);
} else {
modifyCheck();
return getRuntime().getNil();
}
return this;
}
if (buff[begin + len - 1] == newline && rslen <= 1 || value.endsWith(rs.value)) {
view(0, value.realSize - rslen);
return this;
}
return getRuntime().getNil();
}
/** rb_str_lstrip
*
*/
@JRubyMethod
public IRubyObject lstrip(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.lstrip_bang();
return str;
}
/** rb_str_lstrip_bang
*/
@JRubyMethod(name = "lstrip!")
public IRubyObject lstrip_bang() {
if (value.realSize == 0) return getRuntime().getNil();
int i=0;
while (i < value.realSize && ASCII.isSpace(value.bytes[value.begin + i] & 0xff)) i++;
if (i > 0) {
view(i, value.realSize - i);
return this;
}
return getRuntime().getNil();
}
/** rb_str_rstrip
*
*/
@JRubyMethod
public IRubyObject rstrip(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.rstrip_bang();
return str;
}
/** rb_str_rstrip_bang
*/
@JRubyMethod(name = "rstrip!")
public IRubyObject rstrip_bang() {
if (value.realSize == 0) return getRuntime().getNil();
int i=value.realSize - 1;
while (i >= 0 && value.bytes[value.begin+i] == 0) i--;
while (i >= 0 && ASCII.isSpace(value.bytes[value.begin + i] & 0xff)) i--;
if (i < value.realSize - 1) {
view(0, i + 1);
return this;
}
return getRuntime().getNil();
}
/** rb_str_strip
*
*/
@JRubyMethod
public IRubyObject strip(ThreadContext context) {
RubyString str = strDup(context.getRuntime());
str.strip_bang();
return str;
}
/** rb_str_strip_bang
*/
@JRubyMethod(name = "strip!")
public IRubyObject strip_bang() {
IRubyObject l = lstrip_bang();
IRubyObject r = rstrip_bang();
if(l.isNil() && r.isNil()) {
return l;
}
return this;
}
/** rb_str_count
*
*/
@JRubyMethod(name = "count", required = 1, rest = true)
public IRubyObject count(IRubyObject[] args) {
if (args.length < 1) throw getRuntime().newArgumentError("wrong number of arguments");
if (value.realSize == 0) return getRuntime().newFixnum(0);
boolean[]table = new boolean[TRANS_SIZE];
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(table, init);
init = false;
}
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
int i = 0;
while (s < send) if (table[buf[s++] & 0xff]) i++;
return getRuntime().newFixnum(i);
}
/** rb_str_delete
*
*/
@JRubyMethod(name = "delete", required = 1, rest = true)
public IRubyObject delete(ThreadContext context, IRubyObject[] args) {
RubyString str = strDup(context.getRuntime());
str.delete_bang(args);
return str;
}
/** rb_str_delete_bang
*
*/
@JRubyMethod(name = "delete!", required = 1, rest = true)
public IRubyObject delete_bang(IRubyObject[] args) {
if (args.length < 1) throw getRuntime().newArgumentError("wrong number of arguments");
boolean[]squeeze = new boolean[TRANS_SIZE];
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(squeeze, init);
init = false;
}
modify();
if (value.realSize == 0) return getRuntime().getNil();
int s = value.begin;
int t = s;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
while (s < send) {
if (squeeze[buf[s] & 0xff]) {
modify = true;
} else {
buf[t++] = buf[s];
}
s++;
}
value.realSize = t - value.begin;
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_squeeze
*
*/
@JRubyMethod(name = "squeeze", rest = true)
public IRubyObject squeeze(ThreadContext context, IRubyObject[] args) {
RubyString str = strDup(context.getRuntime());
str.squeeze_bang(args);
return str;
}
/** rb_str_squeeze_bang
*
*/
@JRubyMethod(name = "squeeze!", rest = true)
public IRubyObject squeeze_bang(IRubyObject[] args) {
if (value.realSize == 0) {
modifyCheck();
return getRuntime().getNil();
}
final boolean squeeze[] = new boolean[TRANS_SIZE];
if (args.length == 0) {
for (int i=0; i<TRANS_SIZE; i++) squeeze[i] = true;
} else {
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(squeeze, init);
init = false;
}
}
modify();
int s = value.begin;
int t = s;
int send = s + value.realSize;
byte[]buf = value.bytes;
int save = -1;
while (s < send) {
int c = buf[s++] & 0xff;
if (c != save || !squeeze[c]) buf[t++] = (byte)(save = c);
}
if (t - value.begin != value.realSize) { // modified
value.realSize = t - value.begin;
return this;
}
return getRuntime().getNil();
}
/** rb_str_tr
*
*/
@JRubyMethod
public IRubyObject tr(ThreadContext context, IRubyObject src, IRubyObject repl) {
RubyString str = strDup(context.getRuntime());
str.tr_trans(src, repl, false);
return str;
}
/** rb_str_tr_bang
*
*/
@JRubyMethod(name = "tr!")
public IRubyObject tr_bang(IRubyObject src, IRubyObject repl) {
return tr_trans(src, repl, false);
}
private static final class TR {
int gen, now, max;
int p, pend;
byte[]buf;
}
private static final int TRANS_SIZE = 256;
/** tr_setup_table
*
*/
private final void setup_table(boolean[]table, boolean init) {
final boolean[]buf = new boolean[TRANS_SIZE];
final TR tr = new TR();
int c;
boolean cflag = false;
tr.p = value.begin;
tr.pend = value.begin + value.realSize;
tr.buf = value.bytes;
tr.gen = tr.now = tr.max = 0;
if (value.realSize > 1 && value.bytes[value.begin] == '^') {
cflag = true;
tr.p++;
}
if (init) for (int i=0; i<TRANS_SIZE; i++) table[i] = true;
for (int i=0; i<TRANS_SIZE; i++) buf[i] = cflag;
while ((c = trnext(tr)) >= 0) buf[c & 0xff] = !cflag;
for (int i=0; i<TRANS_SIZE; i++) table[i] = table[i] && buf[i];
}
/** tr_trans
*
*/
private final IRubyObject tr_trans(IRubyObject src, IRubyObject repl, boolean sflag) {
if (value.realSize == 0) return getRuntime().getNil();
ByteList replList = repl.convertToString().value;
if (replList.realSize == 0) return delete_bang(new IRubyObject[]{src});
ByteList srcList = src.convertToString().value;
final TR trsrc = new TR();
final TR trrepl = new TR();
boolean cflag = false;
boolean modify = false;
trsrc.p = srcList.begin;
trsrc.pend = srcList.begin + srcList.realSize;
trsrc.buf = srcList.bytes;
if (srcList.realSize >= 2 && srcList.bytes[srcList.begin] == '^') {
cflag = true;
trsrc.p++;
}
trrepl.p = replList.begin;
trrepl.pend = replList.begin + replList.realSize;
trrepl.buf = replList.bytes;
trsrc.gen = trrepl.gen = 0;
trsrc.now = trrepl.now = 0;
trsrc.max = trrepl.max = 0;
int c;
final int[]trans = new int[TRANS_SIZE];
if (cflag) {
for (int i=0; i<TRANS_SIZE; i++) trans[i] = 1;
while ((c = trnext(trsrc)) >= 0) trans[c & 0xff] = -1;
while ((c = trnext(trrepl)) >= 0);
for (int i=0; i<TRANS_SIZE; i++) {
if (trans[i] >= 0) trans[i] = trrepl.now;
}
} else {
for (int i=0; i<TRANS_SIZE; i++) trans[i] = -1;
while ((c = trnext(trsrc)) >= 0) {
int r = trnext(trrepl);
if (r == -1) r = trrepl.now;
trans[c & 0xff] = r;
}
}
modify();
int s = value.begin;
int send = s + value.realSize;
byte sbuf[] = value.bytes;
if (sflag) {
int t = s;
int c0, last = -1;
while (s < send) {
c0 = sbuf[s++];
if ((c = trans[c0 & 0xff]) >= 0) {
if (last == c) continue;
last = c;
sbuf[t++] = (byte)(c & 0xff);
modify = true;
} else {
last = -1;
sbuf[t++] = (byte)c0;
}
}
if (value.realSize > (t - value.begin)) {
value.realSize = t - value.begin;
modify = true;
}
} else {
while (s < send) {
if ((c = trans[sbuf[s] & 0xff]) >= 0) {
sbuf[s] = (byte)(c & 0xff);
modify = true;
}
s++;
}
}
if (modify) return this;
return getRuntime().getNil();
}
/** trnext
*
*/
private final int trnext(TR t) {
byte [] buf = t.buf;
for (;;) {
if (t.gen == 0) {
if (t.p == t.pend) return -1;
if (t.p < t.pend -1 && buf[t.p] == '\\') t.p++;
t.now = buf[t.p++];
if (t.p < t.pend - 1 && buf[t.p] == '-') {
t.p++;
if (t.p < t.pend) {
if (t.now > ((int)buf[t.p] & 0xFF)) {
t.p++;
continue;
}
t.gen = 1;
t.max = (int)buf[t.p++] & 0xFF;
}
}
return t.now & 0xff;
} else if (++t.now < t.max) {
return t.now & 0xff;
} else {
t.gen = 0;
return t.max & 0xff;
}
}
}
/** rb_str_tr_s
*
*/
@JRubyMethod
public IRubyObject tr_s(ThreadContext context, IRubyObject src, IRubyObject repl) {
RubyString str = strDup(context.getRuntime());
str.tr_trans(src, repl, true);
return str;
}
/** rb_str_tr_s_bang
*
*/
@JRubyMethod(name = "tr_s!")
public IRubyObject tr_s_bang(IRubyObject src, IRubyObject repl) {
return tr_trans(src, repl, true);
}
/** rb_str_each_line
*
*/
@JRubyMethod(name = {"each_line", "each"}, required = 0, optional = 1, frame = true)
public IRubyObject each_line(ThreadContext context, IRubyObject[] args, Block block) {
byte newline;
int p = value.begin;
int pend = p + value.realSize;
int s;
int ptr = p;
int len = value.realSize;
int rslen;
IRubyObject line;
IRubyObject _rsep;
if (args.length == 0) {
_rsep = getRuntime().getGlobalVariables().get("$/");
} else {
_rsep = args[0];
}
if(_rsep.isNil()) {
block.yield(context, this);
return this;
}
RubyString rsep = stringValue(_rsep);
ByteList rsepValue = rsep.value;
byte[] strBytes = value.bytes;
rslen = rsepValue.realSize;
if(rslen == 0) {
newline = '\n';
} else {
newline = rsepValue.bytes[rsepValue.begin + rslen-1];
}
s = p;
p+=rslen;
for(; p < pend; p++) {
if(rslen == 0 && strBytes[p] == '\n') {
if(strBytes[++p] != '\n') {
continue;
}
while(p < pend && strBytes[p] == '\n') {
p++;
}
}
if(ptr<p && strBytes[p-1] == newline &&
(rslen <= 1 ||
ByteList.memcmp(rsepValue.bytes, rsepValue.begin, rslen, strBytes, p-rslen, rslen) == 0)) {
line = RubyString.newStringShared(getRuntime(), getMetaClass(), this.value.makeShared(s-ptr, p-s));
line.infectBy(this);
block.yield(context, line);
modifyCheck(strBytes,len);
s = p;
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
line = RubyString.newStringShared(getRuntime(), getMetaClass(), this.value.makeShared(s-ptr, p-s));
line.infectBy(this);
block.yield(context, line);
}
return this;
}
/**
* rb_str_each_byte
*/
@JRubyMethod(name = "each_byte", frame = true)
public RubyString each_byte(ThreadContext context, Block block) {
Ruby runtime = getRuntime();
// Check the length every iteration, since
// the block can modify this string.
for (int i = 0; i < value.length(); i++) {
block.yield(context, runtime.newFixnum(value.get(i) & 0xFF));
}
return this;
}
/** rb_str_intern
*
*/
public RubySymbol intern() {
String s = toString();
if (s.length() == 0) {
throw getRuntime().newArgumentError("interning empty string");
}
if (s.indexOf('\0') >= 0) {
throw getRuntime().newArgumentError("symbol string may not contain '\\0'");
}
return getRuntime().newSymbol(s);
}
@JRubyMethod(name = {"to_sym", "intern"})
public RubySymbol to_sym() {
return intern();
}
@JRubyMethod(name = "sum", optional = 1)
public RubyInteger sum(IRubyObject[] args) {
if (args.length > 1) {
throw getRuntime().newArgumentError("wrong number of arguments (" + args.length + " for 1)");
}
long bitSize = 16;
if (args.length == 1) {
long bitSizeArg = ((RubyInteger) args[0].convertToInteger()).getLongValue();
if (bitSizeArg > 0) {
bitSize = bitSizeArg;
}
}
long result = 0;
for (int i = 0; i < value.length(); i++) {
result += value.get(i) & 0xFF;
}
return getRuntime().newFixnum(bitSize == 0 ? result : result % (long) Math.pow(2, bitSize));
}
/** string_to_c
*
*/
@JRubyMethod(name = "to_c", reads = BACKREF, writes = BACKREF, compat = CompatVersion.RUBY1_9)
public IRubyObject to_c(ThreadContext context) {
Ruby runtime = context.getRuntime();
Frame frame = context.getCurrentFrame();
IRubyObject backref = frame.getBackRef();
if (backref != null && backref instanceof RubyMatchData) ((RubyMatchData)backref).use();
IRubyObject s = RuntimeHelpers.invoke(
context, this, "gsub",
RubyRegexp.newRegexp(runtime, Numeric.ComplexPatterns.underscores_pat),
runtime.newString(new ByteList(new byte[]{'_'})));
RubyArray a = RubyComplex.str_to_c_internal(context, s);
frame.setBackRef(backref);
if (!a.eltInternal(0).isNil()) {
return a.eltInternal(0);
} else {
return RubyComplex.newComplexCanonicalize(context, RubyFixnum.zero(runtime));
}
}
/** string_to_r
*
*/
@JRubyMethod(name = "to_r", reads = BACKREF, writes = BACKREF, compat = CompatVersion.RUBY1_9)
public IRubyObject to_r(ThreadContext context) {
Ruby runtime = context.getRuntime();
Frame frame = context.getCurrentFrame();
IRubyObject backref = frame.getBackRef();
if (backref != null && backref instanceof RubyMatchData) ((RubyMatchData)backref).use();
IRubyObject s = RuntimeHelpers.invoke(
context, this, "gsub",
RubyRegexp.newRegexp(runtime, Numeric.ComplexPatterns.underscores_pat),
runtime.newString(new ByteList(new byte[]{'_'})));
RubyArray a = RubyRational.str_to_r_internal(context, s);
frame.setBackRef(backref);
if (!a.eltInternal(0).isNil()) {
return a.eltInternal(0);
} else {
return RubyRational.newRationalCanonicalize(context, RubyFixnum.zero(runtime));
}
}
public static RubyString unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
RubyString result = newString(input.getRuntime(), input.unmarshalString());
input.registerLinkTarget(result);
return result;
}
/**
* @see org.jruby.util.Pack#unpack
*/
@JRubyMethod
public RubyArray unpack(IRubyObject obj) {
return Pack.unpack(getRuntime(), this.value, stringValue(obj).value);
}
public void empty() {
value = ByteList.EMPTY_BYTELIST;
shareLevel = SHARE_LEVEL_BYTELIST;
}
/**
* Mutator for internal string representation.
*
* @param value The new java.lang.String this RubyString should encapsulate
* @deprecated
*/
public void setValue(CharSequence value) {
view(ByteList.plain(value));
}
public void setValue(ByteList value) {
view(value);
}
public CharSequence getValue() {
return toString();
}
public byte[] getBytes() {
return value.bytes();
}
public ByteList getByteList() {
return value;
}
/** used by ar-jdbc
*
*/
public String getUnicodeValue() {
try {
return new String(value.bytes,value.begin,value.realSize, "UTF8");
} catch (Exception e) {
throw new RuntimeException("Something's seriously broken with encodings", e);
}
}
@Override
public IRubyObject to_java() {
return MiniJava.javaToRuby(getRuntime(), new String(getBytes()));
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
* Copyright (C) 2006 Ryan Bell <ryan.l.bell@gmail.com>
* Copyright (C) 2007 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2008 Vladimir Sizikov <vsizikov@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.ArrayList;
import java.util.List;
import org.jruby.anno.FrameField;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.TypeConverter;
import org.jruby.util.io.InvalidValueException;
import org.jruby.util.io.ModeFlags;
import org.jruby.util.io.Stream;
@JRubyClass(name="StringIO")
public class RubyStringIO extends RubyObject {
private static ObjectAllocator STRINGIO_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyStringIO(runtime, klass);
}
};
public static RubyClass createStringIOClass(final Ruby runtime) {
RubyClass stringIOClass = runtime.defineClass(
"StringIO", runtime.fastGetClass("Data"), STRINGIO_ALLOCATOR);
stringIOClass.defineAnnotatedMethods(RubyStringIO.class);
stringIOClass.includeModule(runtime.getEnumerable());
return stringIOClass;
}
@JRubyMethod(name = "open", optional = 2, frame = true, meta = true)
public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyStringIO strio = (RubyStringIO)((RubyClass)recv).newInstance(context, args, Block.NULL_BLOCK);
IRubyObject val = strio;
if (block.isGiven()) {
try {
val = block.yield(context, strio);
} finally {
strio.doFinalize();
}
}
return val;
}
protected RubyStringIO(Ruby runtime, RubyClass klass) {
super(runtime, klass);
}
private long pos = 0L;
private int lineno = 0;
private boolean eof = false;
/**
* ATTN: the value of internal might be reset to null
* (during StringIO.open with block), so watch out for that.
*/
private RubyString internal;
// Has read/write been closed or is it still open for business
private boolean closedRead = false;
private boolean closedWrite = false;
// Support IO modes that this object was opened with
ModeFlags modes;
private void initializeModes(Object modeArgument) {
try {
if (modeArgument == null) {
modes = new ModeFlags(RubyIO.getIOModesIntFromString(getRuntime(), "r+"));
} else if (modeArgument instanceof Long) {
modes = new ModeFlags(((Long)modeArgument).longValue());
} else {
modes = new ModeFlags(RubyIO.getIOModesIntFromString(getRuntime(), (String) modeArgument));
}
} catch (InvalidValueException e) {
throw getRuntime().newErrnoEINVALError();
}
setupModes();
}
@JRubyMethod(name = "initialize", optional = 2, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
Object modeArgument = null;
switch (args.length) {
case 0:
internal = RubyString.newEmptyString(getRuntime());
modeArgument = "r+";
break;
case 1:
internal = args[0].convertToString();
modeArgument = internal.isFrozen() ? "r" : "r+";
break;
case 2:
internal = args[0].convertToString();
if (args[1] instanceof RubyFixnum) {
modeArgument = RubyFixnum.fix2long(args[1]);
} else {
modeArgument = args[1].convertToString().toString();
}
break;
}
initializeModes(modeArgument);
if (modes.isWritable() && internal.isFrozen()) {
throw getRuntime().newErrnoEACCESError("Permission denied");
}
if (modes.isTruncate()) {
internal.modifyCheck();
internal.empty();
}
return this;
}
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject initialize_copy(IRubyObject other) {
RubyStringIO otherIO = (RubyStringIO) TypeConverter.convertToType(
other, getRuntime().fastGetClass("StringIO"),
MethodIndex.getIndex("to_strio"), "to_strio");
if (this == otherIO) {
return this;
}
pos = otherIO.pos;
lineno = otherIO.lineno;
eof = otherIO.eof;
closedRead = otherIO.closedRead;
closedWrite = otherIO.closedWrite;
internal = otherIO.internal;
modes = otherIO.modes;
if (otherIO.isTaint()) {
setTaint(true);
}
return this;
}
@JRubyMethod(name = "<<", required = 1)
public IRubyObject append(ThreadContext context, IRubyObject arg) {
writeInternal(context, arg);
return this;
}
@JRubyMethod(name = "binmode")
public IRubyObject binmode() {
return this;
}
@JRubyMethod(name = "close", frame=true)
public IRubyObject close() {
checkInitialized();
checkOpen();
closedRead = true;
closedWrite = true;
return getRuntime().getNil();
}
private void doFinalize() {
closedRead = true;
closedWrite = true;
internal = null;
}
@JRubyMethod(name = "closed?")
public IRubyObject closed_p() {
checkInitialized();
return getRuntime().newBoolean(closedRead && closedWrite);
}
@JRubyMethod(name = "close_read")
public IRubyObject close_read() {
checkReadable();
closedRead = true;
return getRuntime().getNil();
}
@JRubyMethod(name = "closed_read?")
public IRubyObject closed_read_p() {
checkInitialized();
return getRuntime().newBoolean(closedRead);
}
@JRubyMethod(name = "close_write")
public IRubyObject close_write() {
checkWritable();
closedWrite = true;
return getRuntime().getNil();
}
@JRubyMethod(name = "closed_write?")
public IRubyObject closed_write_p() {
checkInitialized();
return getRuntime().newBoolean(closedWrite);
}
@JRubyMethod(name = "each", optional = 1, frame = true, writes = FrameField.LASTLINE)
public IRubyObject each(ThreadContext context, IRubyObject[] args, Block block) {
IRubyObject line = gets(context, args);
while (!line.isNil()) {
block.yield(context, line);
line = gets(context, args);
}
return this;
}
@JRubyMethod(name = "each_byte", frame = true)
public IRubyObject each_byte(ThreadContext context, Block block) {
checkReadable();
Ruby runtime = context.getRuntime();
ByteList bytes = internal.getByteList();
// Check the length every iteration, since
// the block can modify this string.
while (pos < bytes.length()) {
block.yield(context, runtime.newFixnum(bytes.get((int) pos++) & 0xFF));
}
return runtime.getNil();
}
@JRubyMethod(name = "each_line", optional = 1, frame = true)
public IRubyObject each_line(ThreadContext context, IRubyObject[] args, Block block) {
return each(context, args, block);
}
@JRubyMethod(name = {"eof", "eof?"})
public IRubyObject eof() {
return getRuntime().newBoolean(isEOF());
}
private boolean isEOF() {
return (pos >= internal.getByteList().length()) || eof;
}
@JRubyMethod(name = "fcntl")
public IRubyObject fcntl() {
throw getRuntime().newNotImplementedError("fcntl not implemented");
}
@JRubyMethod(name = "fileno")
public IRubyObject fileno() {
return getRuntime().getNil();
}
@JRubyMethod(name = "flush")
public IRubyObject flush() {
return this;
}
@JRubyMethod(name = "fsync")
public IRubyObject fsync() {
return RubyFixnum.zero(getRuntime());
}
@JRubyMethod(name = "getc")
public IRubyObject getc() {
checkReadable();
if (pos >= internal.getByteList().length()) {
return getRuntime().getNil();
}
return getRuntime().newFixnum(internal.getByteList().get((int)pos++) & 0xFF);
}
private IRubyObject internalGets(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
if (pos < internal.getByteList().realSize && !eof) {
boolean isParagraph = false;
ByteList sep;
if (args.length > 0) {
if (args[0].isNil()) {
ByteList buf = internal.getByteList().makeShared(
(int)pos, internal.getByteList().realSize - (int)pos);
pos += buf.realSize;
return RubyString.newString(runtime, buf);
}
sep = args[0].convertToString().getByteList();
if (sep.realSize == 0) {
isParagraph = true;
sep = Stream.PARAGRAPH_SEPARATOR;
}
} else {
sep = ((RubyString)runtime.getGlobalVariables().get("$/")).getByteList();
}
ByteList ss = internal.getByteList();
if (isParagraph) {
swallowLF(ss);
if (pos == ss.realSize) {
return runtime.getNil();
}
}
int ix = ss.indexOf(sep, (int)pos);
ByteList add;
if (-1 == ix) {
ix = internal.getByteList().realSize;
add = new ByteList(new byte[0], false);
} else {
add = isParagraph? NEWLINE : sep;
}
ByteList line = internal.getByteList().makeShared((int)pos, ix - (int)pos);
line.unshare();
line.append(add);
line.invalidate();
pos = ix + add.realSize;
lineno++;
return RubyString.newString(runtime,line);
}
return runtime.getNil();
}
private void swallowLF(ByteList list) {
while (pos < list.realSize) {
if (list.get((int)pos) == '\n') {
pos++;
} else {
break;
}
}
}
@JRubyMethod(name = "gets", optional = 1, writes = FrameField.LASTLINE)
public IRubyObject gets(ThreadContext context, IRubyObject[] args) {
checkReadable();
IRubyObject result = internalGets(context, args);
context.getCurrentFrame().setLastLine(result);
return result;
}
@JRubyMethod(name = {"tty?", "isatty"})
public IRubyObject isatty() {
return getRuntime().getFalse();
}
@JRubyMethod(name = {"length", "size"})
public IRubyObject length() {
checkFinalized();
return getRuntime().newFixnum(internal.getByteList().length());
}
@JRubyMethod(name = "lineno")
public IRubyObject lineno() {
return getRuntime().newFixnum(lineno);
}
@JRubyMethod(name = "lineno=", required = 1)
public IRubyObject set_lineno(IRubyObject arg) {
lineno = RubyNumeric.fix2int(arg);
return getRuntime().getNil();
}
@JRubyMethod(name = "path")
public IRubyObject path() {
return getRuntime().getNil();
}
@JRubyMethod(name = "pid")
public IRubyObject pid() {
return getRuntime().getNil();
}
@JRubyMethod(name = {"pos", "tell"})
public IRubyObject pos() {
return getRuntime().newFixnum(pos);
}
@JRubyMethod(name = "pos=", required = 1)
public IRubyObject set_pos(IRubyObject arg) {
pos = RubyNumeric.fix2int(arg);
if (pos < 0) {
throw getRuntime().newErrnoEINVALError("Invalid argument");
}
return getRuntime().getNil();
}
@JRubyMethod(name = "print", rest = true)
public IRubyObject print(ThreadContext context, IRubyObject[] args) {
Ruby runtime = context.getRuntime();
if (args.length != 0) {
for (int i=0,j=args.length;i<j;i++) {
append(context, args[i]);
}
} else {
IRubyObject arg = runtime.getGlobalVariables().get("$_");
append(context, arg.isNil() ? runtime.newString("nil") : arg);
}
IRubyObject sep = runtime.getGlobalVariables().get("$\\");
if (!sep.isNil()) {
append(context, sep);
}
return getRuntime().getNil();
}
@JRubyMethod(name = "printf", required = 1, rest = true)
public IRubyObject printf(ThreadContext context, IRubyObject[] args) {
append(context, RubyKernel.sprintf(context, this, args));
return getRuntime().getNil();
}
@JRubyMethod(name = "putc", required = 1)
public IRubyObject putc(IRubyObject obj) {
checkWritable();
byte c = RubyNumeric.num2chr(obj);
checkFrozen();
internal.modify();
ByteList bytes = internal.getByteList();
if (modes.isAppendable()) {
pos = bytes.length();
bytes.append(c);
} else {
if (pos >= bytes.length()) {
bytes.length((int)pos + 1);
}
bytes.set((int) pos, c);
pos++;
}
return obj;
}
public static final ByteList NEWLINE = ByteList.create("\n");
@JRubyMethod(name = "puts", rest = true)
public IRubyObject puts(ThreadContext context, IRubyObject[] args) {
checkWritable();
// FIXME: the code below is a copy of RubyIO.puts,
// and we should avoid copy-paste.
if (args.length == 0) {
callMethod(context, "write", RubyString.newStringShared(getRuntime(), NEWLINE));
return getRuntime().getNil();
}
for (int i = 0; i < args.length; i++) {
String line;
if (args[i].isNil()) {
line = "nil";
} else {
IRubyObject tmp = args[i].checkArrayType();
if (!tmp.isNil()) {
RubyArray arr = (RubyArray) tmp;
if (getRuntime().isInspecting(arr)) {
line = "[...]";
} else {
inspectPuts(context, arr);
continue;
}
} else {
line = args[i].toString();
}
}
callMethod(context, "write", getRuntime().newString(line));
if (!line.endsWith("\n")) {
callMethod(context, "write", RubyString.newStringShared(getRuntime(), NEWLINE));
}
}
return getRuntime().getNil();
}
private IRubyObject inspectPuts(ThreadContext context, RubyArray array) {
try {
getRuntime().registerInspecting(array);
return puts(context, array.toJavaArray());
} finally {
getRuntime().unregisterInspecting(array);
}
}
@SuppressWarnings("fallthrough")
@JRubyMethod(name = "read", optional = 2)
public IRubyObject read(IRubyObject[] args) {
checkReadable();
ByteList buf = null;
int length = 0;
int oldLength = 0;
RubyString originalString = null;
switch (args.length) {
case 2:
originalString = args[1].convertToString();
// must let original string know we're modifying, so shared buffers aren't damaged
originalString.modify();
buf = originalString.getByteList();
case 1:
if (!args[0].isNil()) {
length = RubyNumeric.fix2int(args[0]);
oldLength = length;
if (length < 0) {
throw getRuntime().newArgumentError("negative length " + length + " given");
}
if (length > 0 && pos >= internal.getByteList().length()) {
eof = true;
if (buf != null) buf.realSize = 0;
return getRuntime().getNil();
} else if (eof) {
if (buf != null) buf.realSize = 0;
return getRuntime().getNil();
}
break;
}
case 0:
oldLength = -1;
length = internal.getByteList().length();
if (length <= pos) {
eof = true;
if (buf == null) {
buf = new ByteList();
} else {
buf.realSize = 0;
}
return getRuntime().newString(buf);
} else {
length -= pos;
}
break;
default:
getRuntime().newArgumentError(args.length, 0);
}
if (buf == null) {
int internalLength = internal.getByteList().length();
if (internalLength > 0) {
if (internalLength >= pos + length) {
buf = new ByteList(internal.getByteList(), (int) pos, length);
} else {
int rest = (int) (internal.getByteList().length() - pos);
if (length > rest) length = rest;
buf = new ByteList(internal.getByteList(), (int) pos, length);
}
}
} else {
int rest = (int) (internal.getByteList().length() - pos);
if (length > rest) length = rest;
// Yow...this is ugly
buf.realSize = length;
buf.replace(0, length, internal.getByteList().bytes, (int) pos, length);
}
if (buf == null) {
if (!eof) buf = new ByteList();
length = 0;
} else {
length = buf.length();
pos += length;
}
if (oldLength < 0 || oldLength > length) eof = true;
return originalString != null ? originalString : getRuntime().newString(buf);
}
@JRubyMethod(name = "readchar")
public IRubyObject readchar() {
IRubyObject c = getc();
if (c.isNil()) throw getRuntime().newEOFError();
return c;
}
@JRubyMethod(name = "readline", optional = 1, writes = FrameField.LASTLINE)
public IRubyObject readline(ThreadContext context, IRubyObject[] args) {
IRubyObject line = gets(context, args);
if (line.isNil()) throw getRuntime().newEOFError();
return line;
}
@JRubyMethod(name = "readlines", optional = 1)
public IRubyObject readlines(ThreadContext context, IRubyObject[] arg) {
checkReadable();
List<IRubyObject> lns = new ArrayList<IRubyObject>();
while (!(isEOF())) {
IRubyObject line = internalGets(context, arg);
if (line.isNil()) {
break;
}
lns.add(line);
}
return getRuntime().newArray(lns);
}
@JRubyMethod(name = "reopen", required = 0, optional = 2)
public IRubyObject reopen(IRubyObject[] args) {
if (args.length == 1 && !(args[0] instanceof RubyString)) {
return initialize_copy(args[0]);
}
// reset the state
doRewind();
closedRead = false;
closedWrite = false;
return initialize(args, Block.NULL_BLOCK);
}
@JRubyMethod(name = "rewind")
public IRubyObject rewind() {
doRewind();
return RubyFixnum.zero(getRuntime());
}
private void doRewind() {
this.pos = 0L;
this.eof = false;
this.lineno = 0;
}
@JRubyMethod(name = "seek", required = 1, optional = 1, frame=true)
public IRubyObject seek(IRubyObject[] args) {
// MRI 1.8.7 behavior:
// checkOpen();
checkFinalized();
long amount = RubyNumeric.num2long(args[0]);
int whence = Stream.SEEK_SET;
long newPosition = pos;
if (args.length > 1 && !args[0].isNil()) whence = RubyNumeric.fix2int(args[1]);
if (whence == Stream.SEEK_CUR) {
newPosition += amount;
} else if (whence == Stream.SEEK_END) {
newPosition = internal.getByteList().length() + amount;
} else {
newPosition = amount;
}
if (newPosition < 0) throw getRuntime().newErrnoEINVALError();
pos = newPosition;
eof = false;
return RubyFixnum.zero(getRuntime());
}
@JRubyMethod(name = "string=", required = 1)
public IRubyObject set_string(IRubyObject arg) {
return reopen(new IRubyObject[] { arg.convertToString() });
}
@JRubyMethod(name = "sync=", required = 1)
public IRubyObject set_sync(IRubyObject args) {
return args;
}
@JRubyMethod(name = "string")
public IRubyObject string() {
if (internal == null) {
return getRuntime().getNil();
} else {
return internal;
}
}
@JRubyMethod(name = "sync")
public IRubyObject sync() {
return getRuntime().getTrue();
}
@JRubyMethod(name = "sysread", optional = 2)
public IRubyObject sysread(IRubyObject[] args) {
IRubyObject obj = read(args);
if (isEOF()) {
if (obj.isNil() || ((RubyString) obj).getByteList().length() == 0) {
throw getRuntime().newEOFError();
}
}
return obj;
}
@JRubyMethod(name = "truncate", required = 1)
public IRubyObject truncate(IRubyObject arg) {
checkWritable();
int len = RubyFixnum.fix2int(arg);
if (len < 0) {
throw getRuntime().newErrnoEINVALError("negative legnth");
}
internal.modify();
internal.getByteList().length(len);
return arg;
}
@JRubyMethod(name = "ungetc", required = 1)
public IRubyObject ungetc(IRubyObject arg) {
checkReadable();
int c = RubyNumeric.num2int(arg);
if (pos == 0) return getRuntime().getNil();
internal.modify();
pos--;
ByteList bytes = internal.getByteList();
if (bytes.length() <= pos) {
bytes.length((int)pos + 1);
}
bytes.set((int) pos, c);
return getRuntime().getNil();
}
@JRubyMethod(name = {"write", "syswrite"}, required = 1)
public IRubyObject write(ThreadContext context, IRubyObject arg) {
return context.getRuntime().newFixnum(writeInternal(context, arg));
}
private int writeInternal(ThreadContext context, IRubyObject arg) {
checkWritable();
checkFrozen();
RubyString val = arg.asString();
internal.modify();
if (modes.isAppendable()) {
internal.getByteList().append(val.getByteList());
pos = internal.getByteList().length();
} else {
int left = internal.getByteList().length()-(int)pos;
internal.getByteList().replace((int)pos,Math.min(val.getByteList().length(),left),val.getByteList());
pos += val.getByteList().length();
}
if (val.isTaint()) {
internal.setTaint(true);
}
return val.getByteList().length();
}
/* rb: check_modifiable */
@Override
protected void checkFrozen() {
checkInitialized();
if (internal.isFrozen()) throw getRuntime().newIOError("not modifiable string");
}
/* rb: readable */
private void checkReadable() {
checkInitialized();
if (closedRead || !modes.isReadable()) {
throw getRuntime().newIOError("not opened for reading");
}
}
/* rb: writable */
private void checkWritable() {
checkInitialized();
if (closedWrite || !modes.isWritable()) {
throw getRuntime().newIOError("not opened for writing");
}
// Tainting here if we ever want it. (secure 4)
}
private void checkInitialized() {
if (modes == null) {
throw getRuntime().newIOError("uninitialized stream");
}
}
private void checkFinalized() {
if (internal == null) {
throw getRuntime().newIOError("not opened");
}
}
private void checkOpen() {
if (closedRead && closedWrite) {
throw getRuntime().newIOError("closed stream");
}
}
private void setupModes() {
closedWrite = false;
closedRead = false;
if (modes.isReadOnly()) closedWrite = true;
if (!modes.isReadable()) closedRead = true;
}
}
package org.jruby;
import org.joni.Matcher;
import org.joni.Option;
import org.joni.Regex;
import org.joni.Region;
import org.joni.encoding.Encoding;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
/**
* @author kscott
*
*/
@JRubyClass(name="StringScanner")
public class RubyStringScanner extends RubyObject {
private RubyString str;
private int pos = 0;
private int lastPos = -1;
private Region regs;
private int beg = -1;
private int end = -1;
// not to be confused with RubyObject's flags
private int scannerFlags;
private static final int MATCHED_STR_SCN_F = 1 << 11;
private static ObjectAllocator STRINGSCANNER_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyStringScanner(runtime, klass);
}
};
public static RubyClass createScannerClass(final Ruby runtime) {
RubyClass scannerClass = runtime.defineClass("StringScanner", runtime.getObject(), STRINGSCANNER_ALLOCATOR);
scannerClass.defineAnnotatedMethods(RubyStringScanner.class);
ThreadContext context = runtime.getCurrentContext();
scannerClass.setConstant("Version", runtime.newString("0.7.0").freeze(context));
scannerClass.setConstant("Id", runtime.newString("$Id: strscan.c 13506 2007-09-24 08:56:24Z nobu $").freeze(context));
RubyClass standardError = runtime.getStandardError();
RubyClass error = scannerClass.defineClassUnder(
"Error", standardError, standardError.getAllocator());
RubyClass objClass = runtime.getObject();
if (!objClass.isConstantDefined("ScanError")) {
objClass.defineConstant("ScanError", error);
}
return scannerClass;
}
private void clearMatched() {
scannerFlags &= ~MATCHED_STR_SCN_F;
}
private void setMatched() {
scannerFlags |= MATCHED_STR_SCN_F;
}
private boolean isMatched() {
return (scannerFlags & MATCHED_STR_SCN_F) != 0;
}
private void check() {
if (str == null) throw getRuntime().newArgumentError("uninitialized StringScanner object");
}
protected RubyStringScanner(Ruby runtime, RubyClass type) {
super(runtime, type);
}
// second argument is allowed, but ignored (MRI)
@JRubyMethod(name = "initialize", required = 1, optional = 1, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
str = args[0].convertToString();
return this;
}
@JRubyMethod(name = "initialize_copy", frame=true, visibility = Visibility.PRIVATE)
@Override
public IRubyObject initialize_copy(IRubyObject other) {
if (this == other) return this;
if (!(other instanceof RubyStringScanner)) {
throw getRuntime().newTypeError("wrong argument type "
+ other.getMetaClass() + " (expected StringScanner)");
}
RubyStringScanner otherScanner = (RubyStringScanner)other;
str = otherScanner.str;
pos = otherScanner.pos;
lastPos = otherScanner.lastPos;
scannerFlags = otherScanner.scannerFlags;
regs = otherScanner.regs != null ? otherScanner.regs.clone() : null;
beg = otherScanner.beg;
end = otherScanner.end;
return this;
}
@JRubyMethod(name = "reset")
public IRubyObject reset() {
check();
pos = 0;
clearMatched();
return this;
}
@JRubyMethod(name = "terminate")
public IRubyObject terminate() {
check();
pos = str.getByteList().realSize;
clearMatched();
return this;
}
@JRubyMethod(name = "clear")
public IRubyObject clear() {
check();
getRuntime().getWarnings().warning(ID.DEPRECATED_METHOD, "StringScanner#clear is obsolete; use #terminate instead", "StringScanner#clear", "#terminate");
return terminate();
}
@JRubyMethod(name = "string")
public RubyString string() {
return str;
}
@JRubyMethod(name = "string=", required = 1)
public IRubyObject set_string(ThreadContext context, IRubyObject str) {
this.str = (RubyString) str.convertToString().strDup(context.getRuntime()).freeze(context);
pos = 0;
clearMatched();
return str;
}
@JRubyMethod(name = {"concat", "<<"}, required = 1)
public IRubyObject concat(IRubyObject obj) {
check();
str.append(obj); // append will call convertToString()
return this;
}
@JRubyMethod(name = {"pos", "pointer"})
public RubyFixnum pos() {
check();
return RubyFixnum.newFixnum(getRuntime(), pos);
}
@JRubyMethod(name = {"pos=", "pointer="})
public IRubyObject set_pos(IRubyObject pos) {
check();
int i = RubyNumeric.num2int(pos);
int size = str.getByteList().realSize;
if (i < 0) i += size;
if (i < 0 || i > size) throw getRuntime().newRangeError("index out of range.");
this.pos = i;
return RubyFixnum.newFixnum(getRuntime(), i);
}
private IRubyObject extractRange(Ruby runtime, int beg, int end) {
int size = str.getByteList().realSize;
if (beg > size) return getRuntime().getNil();
if (end > size) end = size;
return str.makeShared(runtime, beg, end - beg);
}
private IRubyObject extractBegLen(Ruby runtime, int beg, int len) {
assert len >= 0;
int size = str.getByteList().realSize;
if (beg > size) return getRuntime().getNil();
if (beg + len > size) len = size - beg;
return str.makeShared(runtime, beg, len);
}
private IRubyObject scan(IRubyObject regex, boolean succptr, boolean getstr, boolean headonly) {
if (!(regex instanceof RubyRegexp)) throw getRuntime().newTypeError("wrong argument type " + regex.getMetaClass() + " (expected Regexp)");
check();
Regex pattern = ((RubyRegexp)regex).getPattern();
clearMatched();
int rest = str.getByteList().realSize - pos;
if (rest < 0) return getRuntime().getNil();
ByteList value = str.getByteList();
Matcher matcher = pattern.matcher(value.bytes, value.begin + pos, value.begin + value.realSize);
final int ret;
if (headonly) {
ret = matcher.match(value.begin + pos, value.begin + value.realSize, Option.NONE);
} else {
ret = matcher.search(value.begin + pos, value.begin + value.realSize, Option.NONE);
}
regs = matcher.getRegion();
if (regs == null) {
beg = matcher.getBegin();
end = matcher.getEnd();
} else {
beg = regs.beg[0];
end = regs.end[0];
}
if (ret < 0) return getRuntime().getNil();
setMatched();
lastPos = pos;
if (succptr) pos += end;
return getstr ? extractBegLen(getRuntime(), lastPos, end) : RubyFixnum.newFixnum(getRuntime(), end);
}
@JRubyMethod(name = "scan", required = 1)
public IRubyObject scan(IRubyObject regex) {
return scan(regex, true, true, true);
}
@JRubyMethod(name = "match?", required = 1)
public IRubyObject match_p(IRubyObject regex) {
return scan(regex, false, false, true);
}
@JRubyMethod(name = "skip", required = 1)
public IRubyObject skip(IRubyObject regex) {
return scan(regex, true, false, true);
}
@JRubyMethod(name = "check", required = 1)
public IRubyObject check(IRubyObject regex) {
return scan(regex, false, true, true);
}
@JRubyMethod(name = "scan_full", required = 3)
public IRubyObject scan_full(IRubyObject regex, IRubyObject s, IRubyObject f) {
return scan(regex, s.isTrue(), f.isTrue(), true);
}
@JRubyMethod(name = "scan_until", required = 1)
public IRubyObject scan_until(IRubyObject regex) {
return scan(regex, true, true, false);
}
@JRubyMethod(name = "exist?", required = 1)
public IRubyObject exist_p(IRubyObject regex) {
return scan(regex, false, false, false);
}
@JRubyMethod(name = "skip_until", required = 1)
public IRubyObject skip_until(IRubyObject regex) {
return scan(regex, true, false, false);
}
@JRubyMethod(name = "check_until", required = 1)
public IRubyObject check_until(IRubyObject regex) {
return scan(regex, false, true, false);
}
@JRubyMethod(name = "search_full", required = 3)
public IRubyObject search_full(IRubyObject regex, IRubyObject s, IRubyObject f) {
return scan(regex, s.isTrue(), f.isTrue(), false);
}
private void adjustRegisters() {
beg = 0;
end = pos - lastPos;
regs = null;
}
@JRubyMethod(name = "getch")
public IRubyObject getch(ThreadContext context) {
check();
clearMatched();
Ruby runtime = context.getRuntime();
ByteList value = str.getByteList();
if (pos >= value.realSize) return runtime.getNil();
Encoding enc = runtime.getKCode().getEncoding();
int len;
if (enc.isSingleByte()) {
len = 1;
} else {
len = enc.length(value.bytes[value.begin + pos]);
}
if (pos + len > value.realSize) len = value.realSize - pos;
lastPos = pos;
pos += len;
setMatched();
adjustRegisters();
return extractRange(runtime, lastPos + beg, lastPos + end);
}
@JRubyMethod(name = "get_byte")
public IRubyObject get_byte(ThreadContext context) {
check();
clearMatched();
if (pos >= str.getByteList().realSize) return getRuntime().getNil();
lastPos = pos;
pos++;
setMatched();
adjustRegisters();
return extractRange(context.getRuntime(), lastPos + beg, lastPos + end);
}
@JRubyMethod(name = "getbyte")
public IRubyObject getbyte(ThreadContext context) {
context.getRuntime().getWarnings().warning(ID.DEPRECATED_METHOD,
"StringScanner#getbyte is obsolete; use #get_byte instead",
"StringScanner#getbyte", "#get_byte");
return get_byte(context);
}
@JRubyMethod(name = "peek", required = 1)
public IRubyObject peek(ThreadContext context, IRubyObject length) {
check();
int len = RubyNumeric.num2int(length);
if (len < 0) {
throw context.getRuntime().newArgumentError("negative string size (or size too big)");
}
ByteList value = str.getByteList();
if (pos >= value.realSize) return RubyString.newEmptyString(getRuntime()).infectBy(str);
if (pos + len > value.realSize) len = value.realSize - pos;
return extractBegLen(context.getRuntime(), pos, len);
}
@JRubyMethod(name = "peep", required = 1)
public IRubyObject peep(ThreadContext context, IRubyObject length) {
getRuntime().getWarnings().warning(
ID.DEPRECATED_METHOD, "StringScanner#peep is obsolete; use #peek instead",
"StringScanner#peep", "#peek");
return peek(context, length);
}
@JRubyMethod(name = "unscan")
public IRubyObject unscan() {
check();
Ruby runtime = getRuntime();
if (!isMatched()) {
RubyClass errorClass = runtime.fastGetClass("StringScanner").fastGetClass("Error");
throw new RaiseException(RubyException.newException(
runtime, errorClass, "unscan failed: previous match had failed"));
}
pos = lastPos;
clearMatched();
return this;
}
@JRubyMethod(name = "beginning_of_line?", alias = "bol?")
public IRubyObject bol_p() {
check();
ByteList value = str.getByteList();
if (pos > value.realSize) return getRuntime().getNil();
if (pos == 0) return getRuntime().getTrue();
return value.bytes[(value.begin + pos) - 1] == (byte)'\n' ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "eos?")
public RubyBoolean eos_p(ThreadContext context) {
check();
return pos >= str.getByteList().realSize ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
@JRubyMethod(name = "empty?")
public RubyBoolean empty_p(ThreadContext context) {
getRuntime().getWarnings().warning(ID.DEPRECATED_METHOD, "StringScanner#empty? is obsolete; use #eos? instead", "StringScanner#empty?", "#eos?");
return eos_p(context);
}
@JRubyMethod(name = "rest?")
public RubyBoolean rest_p(ThreadContext context) {
check();
return pos >= str.getByteList().realSize ? context.getRuntime().getFalse() : context.getRuntime().getTrue();
}
@JRubyMethod(name = "matched?")
public RubyBoolean matched_p(ThreadContext context) {
check();
return isMatched() ? context.getRuntime().getTrue() : context.getRuntime().getFalse();
}
@JRubyMethod(name = "matched")
public IRubyObject matched(ThreadContext context) {
check();
if (!isMatched()) return getRuntime().getNil();
return extractRange(context.getRuntime(), lastPos + beg, lastPos + end);
}
@JRubyMethod(name = "matched_size")
public IRubyObject matched_size() {
check();
if (!isMatched()) return getRuntime().getNil();
return RubyFixnum.newFixnum(getRuntime(), end - beg);
}
@JRubyMethod(name = "matchedsize")
public IRubyObject matchedsize() {
getRuntime().getWarnings().warning(ID.DEPRECATED_METHOD, "StringScanner#matchedsize is obsolete; use #matched_size instead",
"StringScanner#matchedize", "#matched_size");
return matched_size();
}
@JRubyMethod(name = "[]", required = 1)
public IRubyObject op_aref(ThreadContext context, IRubyObject idx) {
check();
if (!isMatched()) return context.getRuntime().getNil();
int i = RubyNumeric.num2int(idx);
int numRegs = regs == null ? 1 : regs.numRegs;
if (i < 0) i += numRegs;
if (i < 0 || i >= numRegs) return context.getRuntime().getNil();
if (regs == null) {
assert i == 0;
if (beg == -1) return getRuntime().getNil();
return extractRange(context.getRuntime(), lastPos + beg, lastPos + end);
} else {
if (regs.beg[i] == -1) return getRuntime().getNil();
return extractRange(context.getRuntime(), lastPos + regs.beg[i], lastPos + regs.end[i]);
}
}
@JRubyMethod(name = "pre_match")
public IRubyObject pre_match(ThreadContext context) {
check();
if (!isMatched()) return context.getRuntime().getNil();
return extractRange(context.getRuntime(), 0, lastPos + beg);
}
@JRubyMethod(name = "post_match")
public IRubyObject post_match(ThreadContext context) {
check();
if (!isMatched()) return context.getRuntime().getNil();
return extractRange(context.getRuntime(), lastPos + end, str.getByteList().realSize);
}
@JRubyMethod(name = "rest")
public IRubyObject rest(ThreadContext context) {
check();
ByteList value = str.getByteList();
if (pos >= value.realSize) return RubyString.newEmptyString(context.getRuntime()).infectBy(str);
return extractRange(context.getRuntime(), pos, value.realSize);
}
@JRubyMethod(name = "rest_size")
public RubyFixnum rest_size() {
check();
ByteList value = str.getByteList();
if (pos >= value.realSize) return RubyFixnum.zero(getRuntime());
return RubyFixnum.newFixnum(getRuntime(), value.realSize - pos);
}
@JRubyMethod(name = "restsize")
public RubyFixnum restsize() {
getRuntime().getWarnings().warning(ID.DEPRECATED_METHOD, "StringScanner#restsize is obsolete; use #rest_size instead", "StringScanner#restsize", "#rest_size");
return rest_size();
}
@JRubyMethod(name = "inspect")
@Override
public IRubyObject inspect() {
if (str == null) return inspect("(uninitialized)");
if (pos >= str.getByteList().realSize) return inspect("fin");
if (pos == 0) return inspect(pos + "/" + str.getByteList().realSize + " @ " + inspect2());
return inspect(pos + "/" + str.getByteList().realSize + " " + inspect1() + " @ " + inspect2());
}
private IRubyObject inspect(String msg) {
IRubyObject result = getRuntime().newString("#<" + getMetaClass() + " " + msg + ">");
if (str != null) result.infectBy(str);
return result;
}
private static final int INSPECT_LENGTH = 5;
private IRubyObject inspect1() {
if (pos == 0) return RubyString.newEmptyString(getRuntime());
if (pos > INSPECT_LENGTH) {
return RubyString.newString(getRuntime(), "...".getBytes()).append(str.substr(pos - INSPECT_LENGTH, INSPECT_LENGTH)).inspect();
} else {
return str.substr(0, pos).inspect();
}
}
private IRubyObject inspect2() {
if (pos >= str.getByteList().realSize) return RubyString.newEmptyString(getRuntime());
int len = str.getByteList().realSize - pos;
if (len > INSPECT_LENGTH) {
return ((RubyString)str.substr(pos, INSPECT_LENGTH)).cat("...".getBytes()).inspect();
} else {
return str.substr(pos, len).inspect();
}
}
@JRubyMethod(name = "must_C_version", meta = true)
public static IRubyObject mustCversion(IRubyObject recv) {
return recv;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Charles O Nutter <headius@headius.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.List;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.Frame;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.IdUtil;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.methods.CallConfiguration;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.runtime.ClassIndex;
/**
* @author jpetersen
*/
@JRubyClass(name="Struct")
public class RubyStruct extends RubyObject {
private IRubyObject[] values;
/**
* Constructor for RubyStruct.
* @param runtime
* @param rubyClass
*/
public RubyStruct(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass);
int size = RubyNumeric.fix2int(getInternalVariable((RubyClass)rubyClass, "__size__"));
values = new IRubyObject[size];
for (int i = 0; i < size; i++) {
values[i] = getRuntime().getNil();
}
}
public static RubyClass createStructClass(Ruby runtime) {
// TODO: NOT_ALLOCATABLE_ALLOCATOR may be ok here, but it's unclear how Structs
// work with marshalling. Confirm behavior and ensure we're doing this correctly. JRUBY-415
RubyClass structClass = runtime.defineClass("Struct", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setStructClass(structClass);
structClass.index = ClassIndex.STRUCT;
structClass.includeModule(runtime.getEnumerable());
structClass.defineAnnotatedMethods(RubyStruct.class);
return structClass;
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.STRUCT;
}
private static IRubyObject getInternalVariable(RubyClass type, String internedName) {
RubyClass structClass = type.getRuntime().getStructClass();
IRubyObject variable;
while (type != null && type != structClass) {
if ((variable = type.fastGetInternalVariable(internedName)) != null) {
return variable;
}
type = type.getSuperClass();
}
return type.getRuntime().getNil();
}
private RubyClass classOf() {
return getMetaClass() instanceof MetaClass ? getMetaClass().getSuperClass() : getMetaClass();
}
private void modify() {
testFrozen("Struct is frozen");
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't modify struct");
}
}
@JRubyMethod
public RubyFixnum hash(ThreadContext context) {
Ruby runtime = getRuntime();
int h = getMetaClass().getRealClass().hashCode();
for (int i = 0; i < values.length; i++) {
h = (h << 1) | (h < 0 ? 1 : 0);
h ^= RubyNumeric.num2long(values[i].callMethod(context, MethodIndex.HASH, "hash"));
}
return runtime.newFixnum(h);
}
private IRubyObject setByName(String name, IRubyObject value) {
RubyArray member = (RubyArray) getInternalVariable(classOf(), "__member__");
assert !member.isNil() : "uninitialized struct";
modify();
for (int i = 0,k=member.getLength(); i < k; i++) {
if (member.eltInternal(i).asJavaString().equals(name)) {
return values[i] = value;
}
}
throw notStructMemberError(name);
}
private IRubyObject getByName(String name) {
RubyArray member = (RubyArray) getInternalVariable(classOf(), "__member__");
assert !member.isNil() : "uninitialized struct";
for (int i = 0,k=member.getLength(); i < k; i++) {
if (member.eltInternal(i).asJavaString().equals(name)) {
return values[i];
}
}
throw notStructMemberError(name);
}
// Struct methods
/** Create new Struct class.
*
* MRI: rb_struct_s_def / make_struct
*
*/
@JRubyMethod(name = "new", required = 1, rest = true, frame = true, meta = true)
public static RubyClass newInstance(IRubyObject recv, IRubyObject[] args, Block block) {
String name = null;
boolean nilName = false;
Ruby runtime = recv.getRuntime();
if (args.length > 0) {
IRubyObject firstArgAsString = args[0].checkStringType();
if (!firstArgAsString.isNil()) {
name = ((RubyString)firstArgAsString).getByteList().toString();
} else if (args[0].isNil()) {
nilName = true;
}
}
RubyArray member = runtime.newArray();
for (int i = (name == null && !nilName) ? 0 : 1; i < args.length; i++) {
member.append(runtime.newSymbol(args[i].asJavaString()));
}
RubyClass newStruct;
RubyClass superClass = (RubyClass)recv;
if (name == null || nilName) {
newStruct = RubyClass.newClass(runtime, superClass);
newStruct.setAllocator(STRUCT_INSTANCE_ALLOCATOR);
newStruct.makeMetaClass(superClass.getMetaClass());
newStruct.inherit(superClass);
} else {
if (!IdUtil.isConstant(name)) {
throw runtime.newNameError("identifier " + name + " needs to be constant", name);
}
IRubyObject type = superClass.getConstantAt(name);
if (type != null) {
ThreadContext context = runtime.getCurrentContext();
Frame frame = context.getCurrentFrame();
runtime.getWarnings().warn(ID.STRUCT_CONSTANT_REDEFINED, frame.getFile(), frame.getLine(), "redefining constant Struct::" + name, name);
superClass.remove_const(context, runtime.newString(name));
}
newStruct = superClass.defineClassUnder(name, superClass, STRUCT_INSTANCE_ALLOCATOR);
}
newStruct.index = ClassIndex.STRUCT;
newStruct.fastSetInternalVariable("__size__", member.length());
newStruct.fastSetInternalVariable("__member__", member);
newStruct.getSingletonClass().defineAnnotatedMethods(StructMethods.class);
// define access methods.
for (int i = (name == null && !nilName) ? 0 : 1; i < args.length; i++) {
final String memberName = args[i].asJavaString();
// if we are storing a name as well, index is one too high for values
final int index = (name == null && !nilName) ? i : i - 1;
newStruct.addMethod(memberName, new DynamicMethod(newStruct, Visibility.PUBLIC, CallConfiguration.NO_FRAME_NO_SCOPE) {
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
Arity.checkArgumentCount(self.getRuntime(), args, 0, 0);
return ((RubyStruct)self).get(index);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name) {
return ((RubyStruct)self).get(index);
}
@Override
public DynamicMethod dup() {
return this;
}
});
newStruct.addMethod(memberName + "=", new DynamicMethod(newStruct, Visibility.PUBLIC, CallConfiguration.NO_FRAME_NO_SCOPE) {
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
Arity.checkArgumentCount(self.getRuntime(), args, 1, 1);
return ((RubyStruct)self).set(args[0], index);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg) {
return ((RubyStruct)self).set(arg, index);
}
@Override
public DynamicMethod dup() {
return this;
}
});
}
if (block.isGiven()) {
// Struct bodies should be public by default, so set block visibility to public. JRUBY-1185.
block.getBinding().setVisibility(Visibility.PUBLIC);
block.yield(runtime.getCurrentContext(), null, newStruct, newStruct, false);
}
return newStruct;
}
// For binding purposes on the newly created struct types
public static class StructMethods {
@JRubyMethod(name = {"new", "[]"}, rest = true, frame = true)
public static IRubyObject newStruct(IRubyObject recv, IRubyObject[] args, Block block) {
return RubyStruct.newStruct(recv, args, block);
}
@JRubyMethod
public static IRubyObject members(IRubyObject recv, Block block) {
return RubyStruct.members(recv, block);
}
}
/** Create new Structure.
*
* MRI: struct_alloc
*
*/
public static RubyStruct newStruct(IRubyObject recv, IRubyObject[] args, Block block) {
RubyStruct struct = new RubyStruct(recv.getRuntime(), (RubyClass) recv);
struct.callInit(args, block);
return struct;
}
@JRubyMethod(rest = true, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
modify();
int size = RubyNumeric.fix2int(getInternalVariable(getMetaClass(), "__size__"));
if (args.length > size) {
throw getRuntime().newArgumentError("struct size differs (" + args.length +" for " + size + ")");
}
for (int i = 0; i < args.length; i++) {
values[i] = args[i];
}
return getRuntime().getNil();
}
public static RubyArray members(IRubyObject recv, Block block) {
RubyArray member = (RubyArray) getInternalVariable((RubyClass) recv, "__member__");
assert !member.isNil() : "uninitialized struct";
RubyArray result = recv.getRuntime().newArray(member.getLength());
for (int i = 0,k=member.getLength(); i < k; i++) {
result.append(recv.getRuntime().newString(member.eltInternal(i).asJavaString()));
}
return result;
}
@JRubyMethod
public RubyArray members() {
return members(classOf(), Block.NULL_BLOCK);
}
@JRubyMethod
public RubyArray select(ThreadContext context, Block block) {
RubyArray array = RubyArray.newArray(context.getRuntime());
for (int i = 0; i < values.length; i++) {
if (block.yield(context, values[i]).isTrue()) {
array.append(values[i]);
}
}
return array;
}
public IRubyObject set(IRubyObject value, int index) {
RubyArray member = (RubyArray) getInternalVariable(classOf(), "__member__");
assert !member.isNil() : "uninitialized struct";
modify();
return values[index] = value;
}
private RaiseException notStructMemberError(String name) {
return getRuntime().newNameError(name + " is not struct member", name);
}
public IRubyObject get(int index) {
RubyArray member = (RubyArray) getInternalVariable(classOf(), "__member__");
assert !member.isNil() : "uninitialized struct";
return values[index];
}
@Override
public void copySpecialInstanceVariables(IRubyObject clone) {
RubyStruct struct = (RubyStruct)clone;
struct.values = new IRubyObject[values.length];
System.arraycopy(values, 0, struct.values, 0, values.length);
}
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
if (this == other) return getRuntime().getTrue();
if (!(other instanceof RubyStruct)) return getRuntime().getFalse();
if (getMetaClass().getRealClass() != other.getMetaClass().getRealClass()) return getRuntime().getFalse();
Ruby runtime = getRuntime();
RubyStruct otherStruct = (RubyStruct)other;
for (int i = 0; i < values.length; i++) {
if (!equalInternal(context, values[i], otherStruct.values[i])) return runtime.getFalse();
}
return runtime.getTrue();
}
@JRubyMethod(name = "eql?", required = 1)
public IRubyObject eql_p(ThreadContext context, IRubyObject other) {
if (this == other) return getRuntime().getTrue();
if (!(other instanceof RubyStruct)) return getRuntime().getFalse();
if (getMetaClass() != other.getMetaClass()) return getRuntime().getFalse();
Ruby runtime = getRuntime();
RubyStruct otherStruct = (RubyStruct)other;
for (int i = 0; i < values.length; i++) {
if (!eqlInternal(context, values[i], otherStruct.values[i])) return runtime.getFalse();
}
return runtime.getTrue();
}
/** inspect_struct
*
*/
private IRubyObject inspectStruct(final ThreadContext context) {
RubyArray member = (RubyArray) getInternalVariable(classOf(), "__member__");
assert !member.isNil() : "uninitialized struct";
ByteList buffer = new ByteList("#<struct ".getBytes());
buffer.append(getMetaClass().getRealClass().getRealClass().getName().getBytes());
buffer.append(' ');
for (int i = 0,k=member.getLength(); i < k; i++) {
if (i > 0) buffer.append(',').append(' ');
// FIXME: MRI has special case for constants here
buffer.append(RubyString.objAsString(context, member.eltInternal(i)).getByteList());
buffer.append('=');
buffer.append(inspect(context, values[i]).getByteList());
}
buffer.append('>');
return getRuntime().newString(buffer); // OBJ_INFECT
}
@JRubyMethod(name = {"inspect", "to_s"})
public IRubyObject inspect(ThreadContext context) {
if (getRuntime().isInspecting(this)) return getRuntime().newString("#<struct " + getMetaClass().getRealClass().getName() + ":...>");
try {
getRuntime().registerInspecting(this);
return inspectStruct(context);
} finally {
getRuntime().unregisterInspecting(this);
}
}
@JRubyMethod(name = {"to_a", "values"})
public RubyArray to_a() {
return getRuntime().newArray(values);
}
@JRubyMethod(name = {"size", "length"} )
public RubyFixnum size() {
return getRuntime().newFixnum(values.length);
}
@JRubyMethod(name = "each", backtrace = true)
public IRubyObject each(ThreadContext context, Block block) {
for (int i = 0; i < values.length; i++) {
block.yield(context, values[i]);
}
return this;
}
@JRubyMethod(frame = true)
public IRubyObject each_pair(ThreadContext context, Block block) {
RubyArray member = (RubyArray) getInternalVariable(classOf(), "__member__");
assert !member.isNil() : "uninitialized struct";
for (int i = 0; i < values.length; i++) {
block.yield(context, getRuntime().newArrayNoCopy(new IRubyObject[]{member.eltInternal(i), values[i]}));
}
return this;
}
@JRubyMethod(name = "[]", required = 1)
public IRubyObject aref(IRubyObject key) {
if (key instanceof RubyString || key instanceof RubySymbol) {
return getByName(key.asJavaString());
}
int idx = RubyNumeric.fix2int(key);
idx = idx < 0 ? values.length + idx : idx;
if (idx < 0) {
throw getRuntime().newIndexError("offset " + idx + " too large for struct (size:" + values.length + ")");
} else if (idx >= values.length) {
throw getRuntime().newIndexError("offset " + idx + " too large for struct (size:" + values.length + ")");
}
return values[idx];
}
@JRubyMethod(name = "[]=", required = 2)
public IRubyObject aset(IRubyObject key, IRubyObject value) {
if (key instanceof RubyString || key instanceof RubySymbol) {
return setByName(key.asJavaString(), value);
}
int idx = RubyNumeric.fix2int(key);
idx = idx < 0 ? values.length + idx : idx;
if (idx < 0) {
throw getRuntime().newIndexError("offset " + idx + " too large for struct (size:" + values.length + ")");
} else if (idx >= values.length) {
throw getRuntime().newIndexError("offset " + idx + " too large for struct (size:" + values.length + ")");
}
modify();
return values[idx] = value;
}
// FIXME: This is copied code from RubyArray. Both RE, Struct, and Array should share one impl
// This is also hacky since I construct ruby objects to access ruby arrays through aref instead
// of something lower.
@JRubyMethod(rest = true)
public IRubyObject values_at(IRubyObject[] args) {
long olen = values.length;
RubyArray result = getRuntime().newArray(args.length);
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof RubyFixnum) {
result.append(aref(args[i]));
continue;
}
long beglen[];
if (!(args[i] instanceof RubyRange)) {
} else if ((beglen = ((RubyRange) args[i]).begLen(olen, 0)) == null) {
continue;
} else {
int beg = (int) beglen[0];
int len = (int) beglen[1];
int end = len;
for (int j = 0; j < end; j++) {
result.append(aref(getRuntime().newFixnum(j + beg)));
}
continue;
}
result.append(aref(getRuntime().newFixnum(RubyNumeric.num2long(args[i]))));
}
return result;
}
public static void marshalTo(RubyStruct struct, MarshalStream output) throws java.io.IOException {
output.registerLinkTarget(struct);
output.dumpDefaultObjectHeader('S', struct.getMetaClass());
List members = ((RubyArray) getInternalVariable(struct.classOf(), "__member__")).getList();
output.writeInt(members.size());
for (int i = 0; i < members.size(); i++) {
RubySymbol name = (RubySymbol) members.get(i);
output.dumpObject(name);
output.dumpObject(struct.values[i]);
}
}
public static RubyStruct unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
Ruby runtime = input.getRuntime();
RubySymbol className = (RubySymbol) input.unmarshalObject();
RubyClass rbClass = pathToClass(runtime, className.asJavaString());
if (rbClass == null) {
throw runtime.newNameError("uninitialized constant " + className, className.asJavaString());
}
RubyArray mem = members(rbClass, Block.NULL_BLOCK);
int len = input.unmarshalInt();
IRubyObject[] values = new IRubyObject[len];
for(int i = 0; i < len; i++) {
values[i] = runtime.getNil();
}
RubyStruct result = newStruct(rbClass, values, Block.NULL_BLOCK);
input.registerLinkTarget(result);
for(int i = 0; i < len; i++) {
IRubyObject slot = input.unmarshalObject();
if(!mem.eltInternal(i).toString().equals(slot.toString())) {
throw runtime.newTypeError("struct " + rbClass.getName() + " not compatible (:" + slot + " for :" + mem.eltInternal(i) + ")");
}
result.aset(runtime.newFixnum(i), input.unmarshalObject());
}
return result;
}
private static RubyClass pathToClass(Ruby runtime, String path) {
// FIXME: Throw the right ArgumentError's if the class is missing
// or if it's a module.
return (RubyClass) runtime.getClassFromPath(path);
}
private static ObjectAllocator STRUCT_INSTANCE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyStruct instance = new RubyStruct(runtime, klass);
instance.setMetaClass(klass);
return instance;
}
};
@Override
@JRubyMethod(required = 1)
public IRubyObject initialize_copy(IRubyObject arg) {
if (this == arg) return this;
RubyStruct original = (RubyStruct) arg;
values = new IRubyObject[original.values.length];
System.arraycopy(original.values, 0, values, 0, original.values.length);
return this;
}
}
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Joey Gibson <joey@joeygibson.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Derek Berner <derek.berner@state.nm.us>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 William N Dortch <bill.dortch@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.concurrent.locks.ReentrantLock;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockCallback;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
/**
* Represents a Ruby symbol (e.g. :bar)
*/
@JRubyClass(name="Symbol")
public class RubySymbol extends RubyObject {
private final String symbol;
private final int id;
private final ByteList symbolBytes;
/**
*
* @param runtime
* @param internedSymbol the String value of the new Symbol. This <em>must</em>
* have been previously interned
*/
private RubySymbol(Ruby runtime, String internedSymbol) {
super(runtime, runtime.getSymbol(), false);
// symbol string *must* be interned
assert internedSymbol == internedSymbol.intern() : internedSymbol + " is not interned";
this.symbol = internedSymbol;
this.symbolBytes = ByteList.create(symbol);
this.id = runtime.allocSymbolId();
}
public static RubyClass createSymbolClass(Ruby runtime) {
RubyClass symbolClass = runtime.defineClass("Symbol", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setSymbol(symbolClass);
RubyClass symbolMetaClass = symbolClass.getMetaClass();
symbolClass.index = ClassIndex.SYMBOL;
symbolClass.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubySymbol;
}
};
symbolClass.defineAnnotatedMethods(RubySymbol.class);
symbolMetaClass.undefineMethod("new");
return symbolClass;
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.SYMBOL;
}
/** rb_to_id
*
* @return a String representation of the symbol
*/
@Override
public String asJavaString() {
return symbol;
}
/** short circuit for Symbol key comparison
*
*/
@Override
public final boolean eql(IRubyObject other) {
return other == this;
}
@Override
public boolean isImmediate() {
return true;
}
@Override
public RubyClass getSingletonClass() {
throw getRuntime().newTypeError("can't define singleton");
}
public static RubySymbol getSymbolLong(Ruby runtime, long id) {
return runtime.getSymbolTable().lookup(id);
}
/* Symbol class methods.
*
*/
public static RubySymbol newSymbol(Ruby runtime, String name) {
return runtime.getSymbolTable().getSymbol(name);
}
@JRubyMethod(name = "to_i")
public RubyFixnum to_i() {
return getRuntime().newFixnum(id);
}
@JRubyMethod(name = "to_int")
public RubyFixnum to_int() {
if (getRuntime().getVerbose().isTrue()) {
getRuntime().getWarnings().warn(ID.SYMBOL_AS_INTEGER, "treating Symbol as an integer");
}
return to_i();
}
@JRubyMethod(name = "inspect")
@Override
public IRubyObject inspect() {
Ruby runtime = getRuntime();
return runtime.newString(":" +
(isSymbolName(symbol) ? symbol : RubyString.newStringShared(runtime, symbolBytes).dump().toString()));
}
@JRubyMethod(name = "to_s")
@Override
public IRubyObject to_s() {
return RubyString.newStringShared(getRuntime(), symbolBytes);
}
@JRubyMethod(name = "id2name")
public IRubyObject id2name() {
return to_s();
}
@JRubyMethod(name = "===", required = 1)
@Override
public IRubyObject op_eqq(ThreadContext context, IRubyObject other) {
return super.op_equal(context, other);
}
@Override
public RubyFixnum hash() {
return getRuntime().newFixnum(hashCode());
}
@Override
public int hashCode() {
return id;
}
public int getId() {
return id;
}
@Override
public boolean equals(Object other) {
return other == this;
}
@JRubyMethod(name = "to_sym")
public IRubyObject to_sym() {
return this;
}
@Override
public IRubyObject freeze(ThreadContext context) {
return this;
}
@Override
public IRubyObject taint(ThreadContext context) {
return this;
}
private static class ToProcCallback implements BlockCallback {
private RubySymbol symbol;
public ToProcCallback(RubySymbol symbol) {
this.symbol = symbol;
}
public IRubyObject call(ThreadContext ctx, IRubyObject[] args, Block blk) {
IRubyObject[] currentArgs = args;
switch(currentArgs.length) {
case 0: throw symbol.getRuntime().newArgumentError("no receiver given");
case 1: {
if((currentArgs[0] instanceof RubyArray) && ((RubyArray)currentArgs[0]).getLength() != 0) {
// This is needed to unpack stuff
currentArgs = ((RubyArray)currentArgs[0]).toJavaArrayMaybeUnsafe();
IRubyObject[] args2 = new IRubyObject[currentArgs.length-1];
System.arraycopy(currentArgs, 1, args2, 0, args2.length);
return RuntimeHelpers.invoke(ctx, currentArgs[0], symbol.symbol, args2);
} else {
return RuntimeHelpers.invoke(ctx, currentArgs[0], symbol.symbol);
}
}
default: {
IRubyObject[] args2 = new IRubyObject[currentArgs.length-1];
System.arraycopy(currentArgs, 1, args2, 0, args2.length);
return RuntimeHelpers.invoke(ctx, currentArgs[0], symbol.symbol, args2);
}
}
}
}
/*
@JRubyMethod
public IRubyObject to_proc() {
return RubyProc.newProc(getRuntime(),
CallBlock.newCallClosure(this, getRuntime().getSymbol(), Arity.noArguments(), new ToProcCallback(this), getRuntime().getCurrentContext()),
Block.Type.PROC);
}
*/
private static boolean isIdentStart(char c) {
return ((c >= 'a' && c <= 'z')|| (c >= 'A' && c <= 'Z')
|| c == '_');
}
private static boolean isIdentChar(char c) {
return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')
|| c == '_');
}
private static boolean isIdentifier(String s) {
if (s == null || s.length() <= 0) {
return false;
}
if (!isIdentStart(s.charAt(0))) {
return false;
}
for (int i = 1; i < s.length(); i++) {
if (!isIdentChar(s.charAt(i))) {
return false;
}
}
return true;
}
/**
* is_special_global_name from parse.c.
* @param s
* @return
*/
private static boolean isSpecialGlobalName(String s) {
if (s == null || s.length() <= 0) {
return false;
}
int length = s.length();
switch (s.charAt(0)) {
case '~': case '*': case '$': case '?': case '!': case '@': case '/': case '\\':
case ';': case ',': case '.': case '=': case ':': case '<': case '>': case '\"':
case '&': case '`': case '\'': case '+': case '0':
return length == 1;
case '-':
return (length == 1 || (length == 2 && isIdentChar(s.charAt(1))));
default:
// we already confirmed above that length > 0
for (int i = 0; i < length; i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
}
return true;
}
private static boolean isSymbolName(String s) {
if (s == null || s.length() < 1) {
return false;
}
int length = s.length();
char c = s.charAt(0);
switch (c) {
case '$':
if (length > 1 && isSpecialGlobalName(s.substring(1))) {
return true;
}
return isIdentifier(s.substring(1));
case '@':
int offset = 1;
if (length >= 2 && s.charAt(1) == '@') {
offset++;
}
return isIdentifier(s.substring(offset));
case '<':
return (length == 1 || (length == 2 && (s.equals("<<") || s.equals("<="))) ||
(length == 3 && s.equals("<=>")));
case '>':
return (length == 1) || (length == 2 && (s.equals(">>") || s.equals(">=")));
case '=':
return ((length == 2 && (s.equals("==") || s.equals("=~"))) ||
(length == 3 && s.equals("===")));
case '*':
return (length == 1 || (length == 2 && s.equals("**")));
case '+':
return (length == 1 || (length == 2 && s.equals("+@")));
case '-':
return (length == 1 || (length == 2 && s.equals("-@")));
case '|': case '^': case '&': case '/': case '%': case '~': case '`':
return length == 1;
case '[':
return s.equals("[]") || s.equals("[]=");
}
if (!isIdentStart(c)) {
return false;
}
boolean localID = (c >= 'a' && c <= 'z');
int last = 1;
for (; last < length; last++) {
char d = s.charAt(last);
if (!isIdentChar(d)) {
break;
}
}
if (last == length) {
return true;
} else if (localID && last == length - 1) {
char d = s.charAt(last);
return d == '!' || d == '?' || d == '=';
}
return false;
}
@JRubyMethod(name = "all_symbols", meta = true)
public static IRubyObject all_symbols(IRubyObject recv) {
return recv.getRuntime().getSymbolTable().all_symbols();
}
public static RubySymbol unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
RubySymbol result = newSymbol(input.getRuntime(), RubyString.byteListToString(input.unmarshalString()));
input.registerLinkTarget(result);
return result;
}
public static class SymbolTable {
static final int DEFAULT_INITIAL_CAPACITY = 2048; // *must* be power of 2!
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
private final ReentrantLock tableLock = new ReentrantLock();
private volatile SymbolEntry[] symbolTable;
private int size;
private int threshold;
private final float loadFactor;
private final Ruby runtime;
public SymbolTable(Ruby runtime) {
this.runtime = runtime;
this.loadFactor = DEFAULT_LOAD_FACTOR;
this.threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
this.symbolTable = new SymbolEntry[DEFAULT_INITIAL_CAPACITY];
}
// note all fields are final -- rehash creates new entries when necessary.
// as documented in java.util.concurrent.ConcurrentHashMap.java, that will
// statistically affect only a small percentage (< 20%) of entries for a given rehash.
static class SymbolEntry {
final int hash;
final String name;
final RubySymbol symbol;
final SymbolEntry next;
SymbolEntry(int hash, String name, RubySymbol symbol, SymbolEntry next) {
this.hash = hash;
this.name = name;
this.symbol = symbol;
this.next = next;
}
}
public RubySymbol getSymbol(String name) {
int hash = name.hashCode();
SymbolEntry[] table;
for (SymbolEntry e = (table = symbolTable)[hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
return e.symbol;
}
}
ReentrantLock lock;
(lock = tableLock).lock();
try {
int potentialNewSize;
if ((potentialNewSize = size + 1) > threshold) {
table = rehash();
} else {
table = symbolTable;
}
int index;
// try lookup again under lock
for (SymbolEntry e = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
return e.symbol;
}
}
String internedName;
RubySymbol symbol = new RubySymbol(runtime, internedName = name.intern());
table[index] = new SymbolEntry(hash, internedName, symbol, table[index]);
size = potentialNewSize;
// write-volatile
symbolTable = table;
return symbol;
} finally {
lock.unlock();
}
}
public RubySymbol fastGetSymbol(String internedName) {
assert internedName == internedName.intern() : internedName + " is not interned";
SymbolEntry[] table;
for (SymbolEntry e = (table = symbolTable)[internedName.hashCode() & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
return e.symbol;
}
}
ReentrantLock lock;
(lock = tableLock).lock();
try {
int potentialNewSize;
if ((potentialNewSize = size + 1) > threshold) {
table = rehash();
} else {
table = symbolTable;
}
int index;
int hash;
// try lookup again under lock
for (SymbolEntry e = table[index = (hash = internedName.hashCode()) & (table.length - 1)]; e != null; e = e.next) {
if (internedName == e.name) {
return e.symbol;
}
}
RubySymbol symbol = new RubySymbol(runtime, internedName);
table[index] = new SymbolEntry(hash, internedName, symbol, table[index]);
size = potentialNewSize;
// write-volatile
symbolTable = table;
return symbol;
} finally {
lock.unlock();
}
}
// backwards-compatibility, but threadsafe now
public RubySymbol lookup(String name) {
int hash = name.hashCode();
SymbolEntry[] table;
for (SymbolEntry e = (table = symbolTable)[hash & (table.length - 1)]; e != null; e = e.next) {
if (hash == e.hash && name.equals(e.name)) {
return e.symbol;
}
}
return null;
}
public RubySymbol lookup(long id) {
SymbolEntry[] table = symbolTable;
for (int i = table.length; --i >= 0; ) {
for (SymbolEntry e = table[i]; e != null; e = e.next) {
if (id == e.symbol.id) {
return e.symbol;
}
}
}
return null;
}
public RubyArray all_symbols() {
SymbolEntry[] table = this.symbolTable;
RubyArray array = runtime.newArray(this.size);
for (int i = table.length; --i >= 0; ) {
for (SymbolEntry e = table[i]; e != null; e = e.next) {
array.append(e.symbol);
}
}
return array;
}
// not so backwards-compatible here, but no one should have been
// calling this anyway.
@Deprecated
public void store(RubySymbol symbol) {
throw new UnsupportedOperationException();
}
private SymbolEntry[] rehash() {
SymbolEntry[] oldTable = symbolTable;
int oldCapacity;
if ((oldCapacity = oldTable.length) >= MAXIMUM_CAPACITY) {
return oldTable;
}
int newCapacity = oldCapacity << 1;
SymbolEntry[] newTable = new SymbolEntry[newCapacity];
threshold = (int)(newCapacity * loadFactor);
int sizeMask = newCapacity - 1;
SymbolEntry e;
for (int i = oldCapacity; --i >= 0; ) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
e = oldTable[i];
if (e != null) {
SymbolEntry next = e.next;
int idx = e.hash & sizeMask;
// Single node on list
if (next == null)
newTable[idx] = e;
else {
// Reuse trailing consecutive sequence at same slot
SymbolEntry lastRun = e;
int lastIdx = idx;
for (SymbolEntry last = next;
last != null;
last = last.next) {
int k = last.hash & sizeMask;
if (k != lastIdx) {
lastIdx = k;
lastRun = last;
}
}
newTable[lastIdx] = lastRun;
// Clone all remaining nodes
for (SymbolEntry p = e; p != lastRun; p = p.next) {
int k = p.hash & sizeMask;
SymbolEntry n = newTable[k];
newTable[k] = new SymbolEntry(p.hash, p.name, p.symbol, n);
}
}
}
}
symbolTable = newTable;
return newTable;
}
}
}
package org.jruby;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ObjectMarshal;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
@JRubyClass(name="SystemCallError", parent="StandardError")
public class RubySystemCallError extends RubyException {
private IRubyObject errno = getRuntime().getNil();
private final static Map<String, String> defaultMessages = new HashMap<String, String>();
static {
defaultMessages.put("Errno::EPERM", "Operation not permitted");
defaultMessages.put("Errno::ENOENT", "No such file or directory");
defaultMessages.put("Errno::ESRCH", "No such process");
defaultMessages.put("Errno::EINTR", "Interrupted system call");
defaultMessages.put("Errno::EIO", "Input/output error");
defaultMessages.put("Errno::ENXIO", "Device not configured");
defaultMessages.put("Errno::E2BIG", "Argument list too long");
defaultMessages.put("Errno::ENOEXEC", "Exec format error");
defaultMessages.put("Errno::EBADF", "Bad file descriptor");
defaultMessages.put("Errno::ECHILD", "No child processes");
defaultMessages.put("Errno::EDEADLK", "Resource deadlock avoided");
defaultMessages.put("Errno::ENOMEM", "Cannot allocate memory");
defaultMessages.put("Errno::EACCES", "Permission denied");
defaultMessages.put("Errno::EFAULT", "Bad address");
defaultMessages.put("Errno::ENOTBLK", "Block device required");
defaultMessages.put("Errno::EBUSY", "Resource busy");
defaultMessages.put("Errno::EEXIST", "File exists");
defaultMessages.put("Errno::EXDEV", "Cross-device link");
defaultMessages.put("Errno::ENODEV", "Operation not supported by device");
defaultMessages.put("Errno::ENOTDIR", "Not a directory");
defaultMessages.put("Errno::EISDIR", "Is a directory");
defaultMessages.put("Errno::EINVAL", "Invalid argument");
defaultMessages.put("Errno::ENFILE", "Too many open files in system");
defaultMessages.put("Errno::EMFILE", "Too many open files");
defaultMessages.put("Errno::ENOTTY", "Inappropriate ioctl for device");
defaultMessages.put("Errno::ETXTBSY", "Text file busy");
defaultMessages.put("Errno::EFBIG", "File too large");
defaultMessages.put("Errno::ENOSPC", "No space left on device");
defaultMessages.put("Errno::ESPIPE", "Illegal seek");
defaultMessages.put("Errno::EROFS", "Read-only file system");
defaultMessages.put("Errno::EMLINK", "Too many links");
defaultMessages.put("Errno::EPIPE", "Broken pipe");
defaultMessages.put("Errno::EDOM", "Numerical argument out of domain");
defaultMessages.put("Errno::ERANGE", "Result too large");
defaultMessages.put("Errno::EAGAIN", "Resource temporarily unavailable");
defaultMessages.put("Errno::EWOULDBLOCK", "Resource temporarily unavailable");
defaultMessages.put("Errno::EINPROGRESS", "Operation now in progress");
defaultMessages.put("Errno::EALREADY", "Operation already in progress");
defaultMessages.put("Errno::ENOTSOCK", "Socket operation on non-socket");
defaultMessages.put("Errno::EDESTADDRREQ", "Destination address required");
defaultMessages.put("Errno::EMSGSIZE", "Message too long");
defaultMessages.put("Errno::EPROTOTYPE", "Protocol wrong type for socket");
defaultMessages.put("Errno::ENOPROTOOPT", "Protocol not available");
defaultMessages.put("Errno::EPROTONOSUPPORT", "Protocol not supported");
defaultMessages.put("Errno::ESOCKTNOSUPPORT", "Socket type not supported");
defaultMessages.put("Errno::EPFNOSUPPORT", "Protocol family not supported");
defaultMessages.put("Errno::EAFNOSUPPORT", "Address family not supported by protocol family");
defaultMessages.put("Errno::EADDRINUSE", "Address already in use");
defaultMessages.put("Errno::EADDRNOTAVAIL", "Can't assign requested address");
defaultMessages.put("Errno::ENETDOWN", "Network is down");
defaultMessages.put("Errno::ENETUNREACH", "Network is unreachable");
defaultMessages.put("Errno::ENETRESET", "Network dropped connection on reset");
defaultMessages.put("Errno::ECONNABORTED", "Software caused connection abort");
defaultMessages.put("Errno::ECONNRESET", "Connection reset by peer");
defaultMessages.put("Errno::ENOBUFS", "No buffer space available");
defaultMessages.put("Errno::EISCONN", "Socket is already connected");
defaultMessages.put("Errno::ENOTCONN", "Socket is not connected");
defaultMessages.put("Errno::ESHUTDOWN", "Can't send after socket shutdown");
defaultMessages.put("Errno::ETOOMANYREFS", "Too many references: can't splice");
defaultMessages.put("Errno::ETIMEDOUT", "Operation timed out");
defaultMessages.put("Errno::ECONNREFUSED", "Connection refused");
defaultMessages.put("Errno::ELOOP", "Too many levels of symbolic links");
defaultMessages.put("Errno::ENAMETOOLONG", "File name too long");
defaultMessages.put("Errno::EHOSTDOWN", "Host is down");
defaultMessages.put("Errno::EHOSTUNREACH", "No route to host");
defaultMessages.put("Errno::ENOTEMPTY", "Directory not empty");
defaultMessages.put("Errno::EUSERS", "Too many users");
defaultMessages.put("Errno::EDQUOT", "Disc quota exceeded");
defaultMessages.put("Errno::ESTALE", "Stale NFS file handle");
defaultMessages.put("Errno::EREMOTE", "Too many levels of remote in path");
defaultMessages.put("Errno::ENOLCK", "No locks available");
defaultMessages.put("Errno::ENOSYS", "Function not implemented");
defaultMessages.put("Errno::EOVERFLOW", "Value too large to be stored in data type");
defaultMessages.put("Errno::EIDRM", "Identifier removed");
defaultMessages.put("Errno::ENOMSG", "No message of desired type");
defaultMessages.put("Errno::EILSEQ", "Illegal byte sequence");
defaultMessages.put("Errno::EBADMSG", "Bad message");
defaultMessages.put("Errno::EMULTIHOP", "EMULTIHOP (Reserved)");
defaultMessages.put("Errno::ENODATA", "No message available on STREAM");
defaultMessages.put("Errno::ENOLINK", "ENOLINK (Reserved)");
defaultMessages.put("Errno::ENOSR", "No STREAM resources");
defaultMessages.put("Errno::ENOSTR", "Not a STREAM");
defaultMessages.put("Errno::EPROTO", "Protocol error");
defaultMessages.put("Errno::ETIME", "STREAM ioctl timeout");
defaultMessages.put("Errno::EOPNOTSUPP", "Operation not supported");
defaultMessages.put("Errno::EOPNOTSUPP_DARWIN", "Operation not supported");
}
protected RubySystemCallError(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass, null);
}
public RubySystemCallError(Ruby runtime, RubyClass rubyClass, String message, int errno) {
super(runtime, rubyClass, message);
this.errno = runtime.newFixnum(errno);
}
private static ObjectAllocator SYSTEM_CALL_ERROR_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyException instance = new RubySystemCallError(runtime, klass);
instance.setMetaClass(klass);
return instance;
}
};
private static final ObjectMarshal SYSTEM_CALL_ERROR_MARSHAL = new ObjectMarshal() {
public void marshalTo(Ruby runtime, Object obj, RubyClass type,
MarshalStream marshalStream) throws IOException {
RubySystemCallError exc = (RubySystemCallError) obj;
marshalStream.registerLinkTarget(exc);
List<Variable<IRubyObject>> attrs = exc.getVariableList();
attrs.add(new VariableEntry<IRubyObject>(
"mesg", exc.message == null ? runtime.getNil() : exc.message));
attrs.add(new VariableEntry<IRubyObject>("errno", exc.errno));
attrs.add(new VariableEntry<IRubyObject>("bt", exc.getBacktrace()));
marshalStream.dumpVariables(attrs);
}
public Object unmarshalFrom(Ruby runtime, RubyClass type,
UnmarshalStream unmarshalStream) throws IOException {
RubySystemCallError exc = (RubySystemCallError) type.allocate();
unmarshalStream.registerLinkTarget(exc);
unmarshalStream.defaultVariablesUnmarshal(exc);
exc.message = exc.removeInternalVariable("mesg");
exc.errno = exc.removeInternalVariable("errno");
exc.set_backtrace(exc.removeInternalVariable("bt"));
return exc;
}
};
public static RubyClass createSystemCallErrorClass(Ruby runtime, RubyClass standardError) {
RubyClass exceptionClass = runtime.defineClass("SystemCallError", standardError, SYSTEM_CALL_ERROR_ALLOCATOR);
exceptionClass.setMarshal(SYSTEM_CALL_ERROR_MARSHAL);
runtime.callbackFactory(RubyClass.class);
exceptionClass.defineAnnotatedMethods(RubySystemCallError.class);
return exceptionClass;
}
@JRubyMethod(optional = 2, required=0, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block block) {
RubyClass sCallErorrClass = getRuntime().getSystemCallError();
RubyClass klass = getMetaClass().getRealClass();
IRubyObject msg = getRuntime().getNil();
IRubyObject err = getRuntime().getNil();
boolean isErrnoClass = !klass.equals(sCallErorrClass);
if (!isErrnoClass) {
// one optional, one required args
Arity.checkArgumentCount(getRuntime(), args, 1, 2);
msg = args[0];
if (args.length == 2) {
err = args[1];
}
if (args.length == 1 && (msg instanceof RubyFixnum)) {
err = msg;
msg = getRuntime().getNil();
}
} else {
// one optional and no required args
Arity.checkArgumentCount(getRuntime(), args, 0, 1);
if (args.length == 1) {
msg = args[0];
}
// try to get errno out of the class
err = klass.fastGetConstant("Errno");
}
if (!err.isNil()) {
errno = err.convertToInteger();
}
String val = defaultMessages.get(klass.getName());
if (val == null) {
val = "Unknown error";
}
// MRI behavior: we don't print errno for actual Errno errors
if (!errno.isNil() && !isErrnoClass) {
val += " " + errno.toString();
}
if (!msg.isNil()) {
val += " - " + msg.convertToString();
}
message = getRuntime().newString(val);
return this;
}
@JRubyMethod
public IRubyObject errno() {
return errno;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyClass(name="SystemExit", parent="Exception")
public class RubySystemExit extends RubyException {
IRubyObject status;
private static ObjectAllocator SYSTEMEXIT_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubySystemExit(runtime, klass);
}
};
public static RubyClass createSystemExitClass(Ruby runtime, RubyClass exceptionClass) {
RubyClass systemExitClass = runtime.defineClass("SystemExit", exceptionClass, SYSTEMEXIT_ALLOCATOR);
systemExitClass.defineAnnotatedMethods(RubySystemExit.class);
return systemExitClass;
}
public static RubySystemExit newInstance(Ruby runtime, int status) {
RubyClass exc = runtime.getSystemExit();
IRubyObject[] exArgs = new IRubyObject[] {
runtime.newFixnum(status),
runtime.newString("exit") };
return (RubySystemExit) exc.newInstance(runtime.getCurrentContext(), exArgs, Block.NULL_BLOCK);
}
protected RubySystemExit(Ruby runtime, RubyClass exceptionClass) {
super(runtime, exceptionClass);
status = runtime.getNil();
}
@JRubyMethod(name = "initialize", optional = 2, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[]args, Block block) {
status = RubyFixnum.zero(getRuntime());
if (args.length > 0 && args[0] instanceof RubyFixnum) {
status = args[0];
IRubyObject[]tmpArgs = new IRubyObject[args.length - 1];
System.arraycopy(args, 1, tmpArgs, 0, tmpArgs.length);
args = tmpArgs;
}
super.initialize(args, block);
return this;
}
@JRubyMethod(name = "status")
public IRubyObject status() {
return status;
}
@JRubyMethod(name = "success?")
public IRubyObject success_p() {
if (status.isNil()) return getRuntime().getTrue();
if (status.equals(RubyFixnum.zero(getRuntime()))) return getRuntime().getTrue();
return getRuntime().getFalse();
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Jason Voegele <jason@jvoegele.com>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.nio.channels.Channel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.exceptions.RaiseException;
import org.jruby.exceptions.ThreadKill;
import org.jruby.internal.runtime.FutureThread;
import org.jruby.internal.runtime.NativeThread;
import org.jruby.internal.runtime.RubyRunnable;
import org.jruby.internal.runtime.ThreadLike;
import org.jruby.internal.runtime.ThreadService;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.ReentrantLock;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.ObjectMarshal;
import org.jruby.runtime.Visibility;
/**
* Implementation of Ruby's <code>Thread</code> class. Each Ruby thread is
* mapped to an underlying Java Virtual Machine thread.
* <p>
* Thread encapsulates the behavior of a thread of execution, including the main
* thread of the Ruby script. In the descriptions that follow, the parameter
* <code>aSymbol</code> refers to a symbol, which is either a quoted string or a
* <code>Symbol</code> (such as <code>:name</code>).
*
* Note: For CVS history, see ThreadClass.java.
*/
@JRubyClass(name="Thread")
public class RubyThread extends RubyObject {
private ThreadLike threadImpl;
private RubyFixnum priority;
private transient Map<IRubyObject, IRubyObject> threadLocalVariables;
private boolean abortOnException;
private IRubyObject finalResult;
private RaiseException exitingException;
private IRubyObject receivedException;
private RubyThreadGroup threadGroup;
private final ThreadService threadService;
private volatile boolean isStopped = false;
private volatile boolean isDead = false;
public Object stopLock = new Object();
private volatile boolean killed = false;
public Object killLock = new Object();
public final ReentrantLock lock = new ReentrantLock();
private static final boolean DEBUG = false;
protected RubyThread(Ruby runtime, RubyClass type) {
super(runtime, type);
this.threadService = runtime.getThreadService();
finalResult = runtime.getNil();
}
/**
* Dispose of the current thread by removing it from its parent ThreadGroup.
*/
public void dispose() {
threadGroup.remove(this);
}
public static RubyClass createThreadClass(Ruby runtime) {
// FIXME: In order for Thread to play well with the standard 'new' behavior,
// it must provide an allocator that can create empty object instances which
// initialize then fills with appropriate data.
RubyClass threadClass = runtime.defineClass("Thread", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setThread(threadClass);
threadClass.defineAnnotatedMethods(RubyThread.class);
RubyThread rubyThread = new RubyThread(runtime, threadClass);
// TODO: need to isolate the "current" thread from class creation
rubyThread.threadImpl = new NativeThread(rubyThread, Thread.currentThread());
runtime.getThreadService().setMainThread(Thread.currentThread(), rubyThread);
// set to default thread group
runtime.getDefaultThreadGroup().addDirectly(rubyThread);
threadClass.setMarshal(ObjectMarshal.NOT_MARSHALABLE_MARSHAL);
return threadClass;
}
/**
* <code>Thread.new</code>
* <p>
* Thread.new( <i>[ arg ]*</i> ) {| args | block } -> aThread
* <p>
* Creates a new thread to execute the instructions given in block, and
* begins running it. Any arguments passed to Thread.new are passed into the
* block.
* <pre>
* x = Thread.new { sleep .1; print "x"; print "y"; print "z" }
* a = Thread.new { print "a"; print "b"; sleep .2; print "c" }
* x.join # Let the threads finish before
* a.join # main thread exits...
* </pre>
* <i>produces:</i> abxyzc
*/
@JRubyMethod(name = {"new", "fork"}, rest = true, frame = true, meta = true)
public static IRubyObject newInstance(IRubyObject recv, IRubyObject[] args, Block block) {
return startThread(recv, args, true, block);
}
/**
* Basically the same as Thread.new . However, if class Thread is
* subclassed, then calling start in that subclass will not invoke the
* subclass's initialize method.
*/
@JRubyMethod(name = "start", rest = true, frame = true, meta = true)
public static RubyThread start(IRubyObject recv, IRubyObject[] args, Block block) {
return startThread(recv, args, false, block);
}
public static RubyThread adopt(IRubyObject recv, Thread t) {
return adoptThread(recv, t, Block.NULL_BLOCK);
}
private static RubyThread adoptThread(final IRubyObject recv, Thread t, Block block) {
final Ruby runtime = recv.getRuntime();
final RubyThread rubyThread = new RubyThread(runtime, (RubyClass) recv);
rubyThread.threadImpl = new NativeThread(rubyThread, t);
ThreadContext context = runtime.getThreadService().registerNewThread(rubyThread);
context.preAdoptThread();
// set to default thread group
runtime.getDefaultThreadGroup().addDirectly(rubyThread);
return rubyThread;
}
@JRubyMethod(name = "initialize", rest = true, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject[] args, Block block) {
Ruby runtime = getRuntime();
if (!block.isGiven()) throw runtime.newThreadError("must be called with a block");
RubyRunnable runnable = new RubyRunnable(this, args, block);
if (RubyInstanceConfig.POOLING_ENABLED) {
threadImpl = new FutureThread(this, runnable);
} else {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
threadImpl = new NativeThread(this, thread);
}
// set to default thread group
runtime.getDefaultThreadGroup().addDirectly(this);
threadImpl.start();
// We yield here to hopefully permit the target thread to schedule
// MRI immediately schedules it, so this is close but not exact
Thread.yield();
return this;
}
private static RubyThread startThread(final IRubyObject recv, final IRubyObject[] args, boolean callInit, Block block) {
RubyThread rubyThread = new RubyThread(recv.getRuntime(), (RubyClass) recv);
if (callInit) {
rubyThread.callInit(args, block);
} else {
// for Thread::start, which does not call the subclass's initialize
rubyThread.initialize(args, block);
}
return rubyThread;
}
private void ensureNotCurrent() {
if (this == getRuntime().getCurrentContext().getThread()) {
throw new RuntimeException("internal thread method called from another thread");
}
}
public synchronized void cleanTerminate(IRubyObject result) {
finalResult = result;
isStopped = true;
isDead = true;
}
public void pollThreadEvents() {
pollThreadEvents(getRuntime().getCurrentContext());
}
public void pollThreadEvents(ThreadContext context) {
// check for criticalization *before* locking ourselves
threadService.waitForCritical();
if (killed) throwThreadKill();
if (receivedException != null) receivedAnException(context);
}
private void throwThreadKill() {
throw new ThreadKill();
}
/**
* Returns the status of the global ``abort on exception'' condition. The
* default is false. When set to true, will cause all threads to abort (the
* process will exit(0)) if an exception is raised in any thread. See also
* Thread.abort_on_exception= .
*/
@JRubyMethod(name = "abort_on_exception", meta = true)
public static RubyBoolean abort_on_exception_x(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
return runtime.isGlobalAbortOnExceptionEnabled() ? runtime.getTrue() : runtime.getFalse();
}
@JRubyMethod(name = "abort_on_exception=", required = 1, meta = true)
public static IRubyObject abort_on_exception_set_x(IRubyObject recv, IRubyObject value) {
recv.getRuntime().setGlobalAbortOnExceptionEnabled(value.isTrue());
return value;
}
@JRubyMethod(name = "current", meta = true)
public static RubyThread current(IRubyObject recv) {
return recv.getRuntime().getCurrentContext().getThread();
}
@JRubyMethod(name = "main", meta = true)
public static RubyThread main(IRubyObject recv) {
return recv.getRuntime().getThreadService().getMainThread();
}
@JRubyMethod(name = "pass", meta = true)
public static IRubyObject pass(IRubyObject recv) {
Ruby runtime = recv.getRuntime();
ThreadService ts = runtime.getThreadService();
boolean critical = ts.getCritical();
ts.setCritical(false);
Thread.yield();
ts.setCritical(critical);
return recv.getRuntime().getNil();
}
@JRubyMethod(name = "list", meta = true)
public static RubyArray list(IRubyObject recv) {
RubyThread[] activeThreads = recv.getRuntime().getThreadService().getActiveRubyThreads();
return recv.getRuntime().newArrayNoCopy(activeThreads);
}
private IRubyObject getSymbolKey(IRubyObject originalKey) {
if (originalKey instanceof RubySymbol) {
return originalKey;
} else if (originalKey instanceof RubyString) {
return getRuntime().newSymbol(originalKey.asJavaString());
} else if (originalKey instanceof RubyFixnum) {
getRuntime().getWarnings().warn(ID.FIXNUMS_NOT_SYMBOLS, "Do not use Fixnums as Symbols");
throw getRuntime().newArgumentError(originalKey + " is not a symbol");
} else {
throw getRuntime().newTypeError(originalKey + " is not a symbol");
}
}
private synchronized Map<IRubyObject, IRubyObject> getThreadLocals() {
if (threadLocalVariables == null) {
threadLocalVariables = new HashMap<IRubyObject, IRubyObject>();
}
return threadLocalVariables;
}
@JRubyMethod(name = "[]", required = 1)
public IRubyObject op_aref(IRubyObject key) {
IRubyObject value;
if ((value = getThreadLocals().get(getSymbolKey(key))) != null) {
return value;
}
return getRuntime().getNil();
}
@JRubyMethod(name = "[]=", required = 2)
public IRubyObject op_aset(IRubyObject key, IRubyObject value) {
key = getSymbolKey(key);
getThreadLocals().put(key, value);
return value;
}
@JRubyMethod(name = "abort_on_exception")
public RubyBoolean abort_on_exception() {
return abortOnException ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "abort_on_exception=", required = 1)
public IRubyObject abort_on_exception_set(IRubyObject val) {
abortOnException = val.isTrue();
return val;
}
@JRubyMethod(name = "alive?")
public RubyBoolean alive_p() {
return !isDead && threadImpl.isAlive() ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "join", optional = 1, backtrace = true)
public IRubyObject join(IRubyObject[] args) {
long timeoutMillis = Long.MAX_VALUE;
if (args.length > 0) {
if (args.length > 1) {
throw getRuntime().newArgumentError(args.length,1);
}
// MRI behavior: value given in seconds; converted to Float; less
// than or equal to zero returns immediately; returns nil
timeoutMillis = (long)(1000.0D * args[0].convertToFloat().getValue());
if (timeoutMillis <= 0) {
// TODO: not sure that we should skip calling join() altogether.
// Thread.join() has some implications for Java Memory Model, etc.
if (threadImpl.isAlive()) {
return getRuntime().getNil();
} else {
return this;
}
}
}
if (isCurrent()) {
throw getRuntime().newThreadError("thread tried to join itself");
}
try {
if (threadService.getCritical()) {
// If the target thread is sleeping or stopped, wake it
synchronized (stopLock) {
stopLock.notify();
}
// interrupt the target thread in case it's blocking or waiting
// WARNING: We no longer interrupt the target thread, since this usually means
// interrupting IO and with NIO that means the channel is no longer usable.
// We either need a new way to handle waking a target thread that's waiting
// on IO, or we need to accept that we can't wake such threads and must wait
// for them to complete their operation.
//threadImpl.interrupt();
}
RubyThread currentThread = getRuntime().getCurrentContext().getThread();
final long timeToWait = Math.min(timeoutMillis, 200);
// We need this loop in order to be able to "unblock" the
// join call without actually calling interrupt.
long start = System.currentTimeMillis();
while(true) {
currentThread.pollThreadEvents();
threadImpl.join(timeToWait);
if (!threadImpl.isAlive()) {
break;
}
if (System.currentTimeMillis() - start > timeoutMillis) {
break;
}
}
} catch (InterruptedException ie) {
ie.printStackTrace();
assert false : ie;
} catch (ExecutionException ie) {
ie.printStackTrace();
assert false : ie;
}
if (exitingException != null) {
throw exitingException;
}
if (threadImpl.isAlive()) {
return getRuntime().getNil();
} else {
return this;
}
}
@JRubyMethod(name = "value")
public IRubyObject value() {
join(new IRubyObject[0]);
synchronized (this) {
return finalResult;
}
}
@JRubyMethod(name = "group")
public IRubyObject group() {
if (threadGroup == null) {
return getRuntime().getNil();
}
return threadGroup;
}
void setThreadGroup(RubyThreadGroup rubyThreadGroup) {
threadGroup = rubyThreadGroup;
}
@JRubyMethod(name = "inspect")
@Override
public IRubyObject inspect() {
// FIXME: There's some code duplication here with RubyObject#inspect
StringBuilder part = new StringBuilder();
String cname = getMetaClass().getRealClass().getName();
part.append("#<").append(cname).append(":0x");
part.append(Integer.toHexString(System.identityHashCode(this)));
if (threadImpl.isAlive()) {
if (isStopped) {
part.append(getRuntime().newString(" sleep"));
} else if (killed) {
part.append(getRuntime().newString(" aborting"));
} else {
part.append(getRuntime().newString(" run"));
}
} else {
part.append(" dead");
}
part.append(">");
return getRuntime().newString(part.toString());
}
@JRubyMethod(name = "key?", required = 1)
public RubyBoolean key_p(IRubyObject key) {
key = getSymbolKey(key);
return getRuntime().newBoolean(getThreadLocals().containsKey(key));
}
@JRubyMethod(name = "keys")
public RubyArray keys() {
IRubyObject[] keys = new IRubyObject[getThreadLocals().size()];
return RubyArray.newArrayNoCopy(getRuntime(), getThreadLocals().keySet().toArray(keys));
}
@JRubyMethod(name = "critical=", required = 1, meta = true)
public static IRubyObject critical_set(IRubyObject receiver, IRubyObject value) {
receiver.getRuntime().getThreadService().setCritical(value.isTrue());
return value;
}
@JRubyMethod(name = "critical", meta = true)
public static IRubyObject critical(IRubyObject receiver) {
return receiver.getRuntime().newBoolean(receiver.getRuntime().getThreadService().getCritical());
}
@JRubyMethod(name = "stop", meta = true)
public static IRubyObject stop(IRubyObject receiver) {
RubyThread rubyThread = receiver.getRuntime().getThreadService().getCurrentContext().getThread();
Object stopLock = rubyThread.stopLock;
synchronized (stopLock) {
rubyThread.pollThreadEvents();
try {
rubyThread.isStopped = true;
// attempt to decriticalize all if we're the critical thread
receiver.getRuntime().getThreadService().setCritical(false);
stopLock.wait();
} catch (InterruptedException ie) {
rubyThread.pollThreadEvents();
}
rubyThread.isStopped = false;
}
return receiver.getRuntime().getNil();
}
@JRubyMethod(name = "kill", required = 1, frame = true, meta = true)
public static IRubyObject kill(IRubyObject receiver, IRubyObject rubyThread, Block block) {
if (!(rubyThread instanceof RubyThread)) throw receiver.getRuntime().newTypeError(rubyThread, receiver.getRuntime().getThread());
return ((RubyThread)rubyThread).kill();
}
@JRubyMethod(name = "exit", frame = true, meta = true)
public static IRubyObject s_exit(IRubyObject receiver, Block block) {
RubyThread rubyThread = receiver.getRuntime().getThreadService().getCurrentContext().getThread();
rubyThread.killed = true;
// attempt to decriticalize all if we're the critical thread
receiver.getRuntime().getThreadService().setCritical(false);
throw new ThreadKill();
}
@JRubyMethod(name = "stop?")
public RubyBoolean stop_p() {
// not valid for "dead" state
return getRuntime().newBoolean(isStopped);
}
@JRubyMethod(name = "wakeup")
public RubyThread wakeup() {
synchronized (stopLock) {
stopLock.notifyAll();
}
return this;
}
@JRubyMethod(name = "priority")
public RubyFixnum priority() {
return priority;
}
@JRubyMethod(name = "priority=", required = 1)
public IRubyObject priority_set(IRubyObject priority) {
// FIXME: This should probably do some translation from Ruby priority levels to Java priority levels (until we have green threads)
int iPriority = RubyNumeric.fix2int(priority);
if (iPriority < Thread.MIN_PRIORITY) {
iPriority = Thread.MIN_PRIORITY;
} else if (iPriority > Thread.MAX_PRIORITY) {
iPriority = Thread.MAX_PRIORITY;
}
this.priority = RubyFixnum.newFixnum(getRuntime(), iPriority);
if (threadImpl.isAlive()) {
threadImpl.setPriority(iPriority);
}
return this.priority;
}
@JRubyMethod(name = "raise", optional = 2, frame = true)
public IRubyObject raise(IRubyObject[] args, Block block) {
ensureNotCurrent();
Ruby runtime = getRuntime();
if (DEBUG) System.out.println("thread " + Thread.currentThread() + " before raising");
RubyThread currentThread = getRuntime().getCurrentContext().getThread();
try {
while (!(currentThread.lock.tryLock() && this.lock.tryLock())) {
if (currentThread.lock.isHeldByCurrentThread()) currentThread.lock.unlock();
}
currentThread.pollThreadEvents();
if (DEBUG) System.out.println("thread " + Thread.currentThread() + " raising");
receivedException = prepareRaiseException(runtime, args, block);
// If the target thread is sleeping or stopped, wake it
synchronized (stopLock) {
stopLock.notify();
}
// interrupt the target thread in case it's blocking or waiting
// WARNING: We no longer interrupt the target thread, since this usually means
// interrupting IO and with NIO that means the channel is no longer usable.
// We either need a new way to handle waking a target thread that's waiting
// on IO, or we need to accept that we can't wake such threads and must wait
// for them to complete their operation.
//threadImpl.interrupt();
// new interrupt, to hopefully wake it out of any blocking IO
this.interrupt();
} finally {
if (currentThread.lock.isHeldByCurrentThread()) currentThread.lock.unlock();
if (this.lock.isHeldByCurrentThread()) this.lock.unlock();
}
return this;
}
private IRubyObject prepareRaiseException(Ruby runtime, IRubyObject[] args, Block block) {
if(args.length == 0) {
IRubyObject lastException = runtime.getGlobalVariables().get("$!");
if(lastException.isNil()) {
return new RaiseException(runtime, runtime.getRuntimeError(), "", false).getException();
}
return lastException;
}
IRubyObject exception;
ThreadContext context = getRuntime().getCurrentContext();
if(args.length == 1) {
if(args[0] instanceof RubyString) {
return runtime.getRuntimeError().newInstance(context, args, block);
}
if(!args[0].respondsTo("exception")) {
return runtime.newTypeError("exception class/object expected").getException();
}
exception = args[0].callMethod(context, "exception");
} else {
if (!args[0].respondsTo("exception")) {
return runtime.newTypeError("exception class/object expected").getException();
}
exception = args[0].callMethod(context, "exception", args[1]);
}
if (!runtime.getException().isInstance(exception)) {
return runtime.newTypeError("exception object expected").getException();
}
if (args.length == 3) {
((RubyException) exception).set_backtrace(args[2]);
}
return exception;
}
@JRubyMethod(name = "run")
public IRubyObject run() {
// if stopped, unstop
synchronized (stopLock) {
if (isStopped) {
isStopped = false;
stopLock.notifyAll();
}
}
return this;
}
public void sleep(long millis) throws InterruptedException {
assert this == getRuntime().getCurrentContext().getThread();
synchronized (stopLock) {
pollThreadEvents();
try {
isStopped = true;
stopLock.wait(millis);
} finally {
isStopped = false;
pollThreadEvents();
}
}
}
@JRubyMethod(name = "status")
public IRubyObject status() {
if (threadImpl.isAlive()) {
if (isStopped || currentSelector != null && currentSelector.isOpen()) {
return getRuntime().newString("sleep");
} else if (killed) {
return getRuntime().newString("aborting");
}
return getRuntime().newString("run");
} else if (exitingException != null) {
return getRuntime().getNil();
} else {
return getRuntime().getFalse();
}
}
@JRubyMethod(name = {"kill", "exit", "terminate"})
public IRubyObject kill() {
// need to reexamine this
RubyThread currentThread = getRuntime().getCurrentContext().getThread();
// If the killee thread is the same as the killer thread, just die
if (currentThread == this) throwThreadKill();
try {
if (DEBUG) System.out.println("thread " + Thread.currentThread() + " trying to kill");
while (!(currentThread.lock.tryLock() && this.lock.tryLock())) {
if (currentThread.lock.isHeldByCurrentThread()) currentThread.lock.unlock();
}
currentThread.pollThreadEvents();
if (DEBUG) System.out.println("thread " + Thread.currentThread() + " succeeded with kill");
killed = true;
// If the target thread is sleeping or stopped, wake it
synchronized (stopLock) {
stopLock.notify();
}
// interrupt the target thread in case it's blocking or waiting
// WARNING: We no longer interrupt the target thread, since this usually means
// interrupting IO and with NIO that means the channel is no longer usable.
// We either need a new way to handle waking a target thread that's waiting
// on IO, or we need to accept that we can't wake such threads and must wait
// for them to complete their operation.
//threadImpl.interrupt();
// new interrupt, to hopefully wake it out of any blocking IO
this.interrupt();
} finally {
if (currentThread.lock.isHeldByCurrentThread()) currentThread.lock.unlock();
if (this.lock.isHeldByCurrentThread()) this.lock.unlock();
}
try {
threadImpl.join();
} catch (InterruptedException ie) {
// we were interrupted, check thread events again
currentThread.pollThreadEvents();
} catch (ExecutionException ie) {
// we were interrupted, check thread events again
currentThread.pollThreadEvents();
}
return this;
}
@JRubyMethod(name = {"kill!", "exit!", "terminate!"})
public IRubyObject kill_bang() {
throw getRuntime().newNotImplementedError("Thread#kill!, exit!, and terminate! are not safe and not supported");
}
@JRubyMethod(name = "safe_level")
public IRubyObject safe_level() {
throw getRuntime().newNotImplementedError("Thread-specific SAFE levels are not supported");
}
private boolean isCurrent() {
return threadImpl.isCurrent();
}
public void exceptionRaised(RaiseException exception) {
assert isCurrent();
RubyException rubyException = exception.getException();
Ruby runtime = rubyException.getRuntime();
if (runtime.getSystemExit().isInstance(rubyException)) {
threadService.getMainThread().raise(new IRubyObject[] {rubyException}, Block.NULL_BLOCK);
} else if (abortOnException(runtime)) {
runtime.printError(rubyException);
RubyException systemExit = RubySystemExit.newInstance(runtime, 1);
systemExit.message = rubyException.message;
systemExit.set_backtrace(rubyException.backtrace());
threadService.getMainThread().raise(new IRubyObject[] {systemExit}, Block.NULL_BLOCK);
return;
} else if (runtime.getDebug().isTrue()) {
runtime.printError(exception.getException());
}
exitingException = exception;
}
private boolean abortOnException(Ruby runtime) {
return (runtime.isGlobalAbortOnExceptionEnabled() || abortOnException);
}
public static RubyThread mainThread(IRubyObject receiver) {
return receiver.getRuntime().getThreadService().getMainThread();
}
private Selector currentSelector;
@Deprecated
public boolean selectForAccept(RubyIO io) {
return select(io, SelectionKey.OP_ACCEPT);
}
public boolean select(RubyIO io, int ops) {
Channel channel = io.getChannel();
if (channel instanceof SelectableChannel) {
SelectableChannel selectable = (SelectableChannel)channel;
synchronized (selectable.blockingLock()) {
boolean oldBlocking = selectable.isBlocking();
try {
selectable.configureBlocking(false);
io.addBlockingThread(this);
currentSelector = selectable.provider().openSelector();
SelectionKey key = selectable.register(currentSelector, ops);
int result = currentSelector.select();
// check for thread events, in case we've been woken up to die
pollThreadEvents();
if (result == 1) {
Set<SelectionKey> keySet = currentSelector.selectedKeys();
if (keySet.iterator().next() == key) {
return true;
}
}
return false;
} catch (IOException ioe) {
throw io.getRuntime().newRuntimeError("Error with selector: " + ioe);
} finally {
if (currentSelector != null) {
try {
currentSelector.close();
} catch (IOException ioe) {
throw io.getRuntime().newRuntimeError("Could not close selector");
}
}
currentSelector = null;
io.removeBlockingThread(this);
try {
selectable.configureBlocking(oldBlocking);
} catch (IOException ioe) {
// ignore; I don't like doing it, but it seems like we
// really just need to make all channels non-blocking by
// default and use select when implementing blocking ops,
// so if this remains set non-blocking, perhaps it's not
// such a big deal...
}
}
}
} else {
// can't select, just have to do a blocking call
return true;
}
}
public void interrupt() {
if (currentSelector != null) {
currentSelector.wakeup();
}
}
public void beforeBlockingCall() {
isStopped = true;
}
public void afterBlockingCall() {
isStopped = false;
}
private void receivedAnException(ThreadContext context) {
// clear this so we don't keep re-throwing
IRubyObject raiseException = receivedException;
receivedException = null;
RubyModule kernelModule = getRuntime().getKernel();
if (DEBUG) {
System.out.println("thread " + Thread.currentThread() + " before propagating exception: " + killed);
}
kernelModule.callMethod(context, "raise", raiseException);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.HashMap;
import java.util.Map;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
/**
* Implementation of Ruby's <code>ThreadGroup</code> class. This is currently
* just a stub.
* <p>
*
* @author Charles O Nutter (headius@headius.com)
*/
@JRubyClass(name="ThreadGroup")
public class RubyThreadGroup extends RubyObject {
private Map<Integer, IRubyObject> rubyThreadList = new HashMap<Integer, IRubyObject>();
private boolean enclosed = false;
// ENEBO: Can these be fast?
public static RubyClass createThreadGroupClass(Ruby runtime) {
RubyClass threadGroupClass = runtime.defineClass("ThreadGroup", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setThreadGroup(threadGroupClass);
threadGroupClass.defineAnnotatedMethods(RubyThreadGroup.class);
// create the default thread group
RubyThreadGroup defaultThreadGroup = new RubyThreadGroup(runtime, threadGroupClass);
runtime.setDefaultThreadGroup(defaultThreadGroup);
threadGroupClass.defineConstant("Default", defaultThreadGroup);
return threadGroupClass;
}
@JRubyMethod(name = "new", frame = true, meta = true)
public static IRubyObject newInstance(IRubyObject recv, Block block) {
return new RubyThreadGroup(recv.getRuntime(), (RubyClass)recv);
}
@JRubyMethod(name = "add", required = 1, frame = true)
public synchronized IRubyObject add(IRubyObject rubyThread, Block block) {
if (!(rubyThread instanceof RubyThread)) throw getRuntime().newTypeError(rubyThread, getRuntime().getThread());
// synchronize on the RubyThread for threadgroup updates
if (isFrozen()) {
throw getRuntime().newTypeError("can't add to frozen ThreadGroup");
}
RubyThread thread = (RubyThread)rubyThread;
// we only add live threads
if (thread.alive_p().isTrue()) {
addDirectly(thread);
}
return this;
}
void addDirectly(RubyThread rubyThread) {
synchronized (rubyThread) {
IRubyObject oldGroup = rubyThread.group();
if (oldGroup != getRuntime().getNil()) {
RubyThreadGroup threadGroup = (RubyThreadGroup) oldGroup;
threadGroup.rubyThreadList.remove(System.identityHashCode(rubyThread));
}
rubyThread.setThreadGroup(this);
rubyThreadList.put(System.identityHashCode(rubyThread), rubyThread);
}
}
public synchronized void remove(RubyThread rubyThread) {
rubyThread.setThreadGroup(null);
rubyThreadList.remove(System.identityHashCode(rubyThread));
}
@JRubyMethod(name = "enclose", frame = true)
public IRubyObject enclose(Block block) {
enclosed = true;
return this;
}
@JRubyMethod(name = "enclosed?", frame = true)
public IRubyObject enclosed_p(Block block) {
return new RubyBoolean(getRuntime(), enclosed);
}
@JRubyMethod(name = "list", frame = true)
public synchronized IRubyObject list(Block block) {
return getRuntime().newArrayNoCopy((IRubyObject[]) rubyThreadList.values().toArray(new IRubyObject[rubyThreadList.size()]));
}
private RubyThreadGroup(Ruby runtime, RubyClass type) {
super(runtime, type);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Joey Gibson <joey@joeygibson.com>
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2006 Ola Bini <ola.bini@ki.se>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.lang.ref.SoftReference;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.RubyDateFormat;
/** The Time class.
*
* @author chadfowler, jpetersen
*/
@JRubyClass(name="Time", include="Comparable")
public class RubyTime extends RubyObject {
public static final String UTC = "UTC";
private DateTime dt;
private long usec;
private final static DateTimeFormatter ONE_DAY_CTIME_FORMATTER = DateTimeFormat.forPattern("EEE MMM d HH:mm:ss yyyy").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TWO_DAY_CTIME_FORMATTER = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss yyyy").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TO_S_FORMATTER = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy").withLocale(Locale.ENGLISH);
private final static DateTimeFormatter TO_S_UTC_FORMATTER = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss 'UTC' yyyy").withLocale(Locale.ENGLISH);
// There are two different popular TZ formats: legacy (AST+3:00:00, GMT-3), and
// newer one (US/Pacific, America/Los_Angeles). This pattern is to detect
// the legacy TZ format in order to convert it to the newer format
// understood by Java API.
private static final Pattern TZ_PATTERN
= Pattern.compile("(\\D+?)([\\+-]?)(\\d+)(:\\d+)?(:\\d+)?");
private static final ByteList TZ_STRING = ByteList.create("TZ");
public static DateTimeZone getLocalTimeZone(Ruby runtime) {
RubyString tzVar = runtime.newString(TZ_STRING);
RubyHash h = ((RubyHash)runtime.getObject().fastGetConstant("ENV"));
IRubyObject tz = h.op_aref(runtime.getCurrentContext(), tzVar);
if (tz == null || ! (tz instanceof RubyString)) {
return DateTimeZone.getDefault();
} else {
String zone = tz.toString();
DateTimeZone cachedZone = runtime.getLocalTimezoneCache().get(zone);
if (cachedZone != null) return cachedZone;
String originalZone = zone;
// Value of "TZ" property is of a bit different format,
// which confuses the Java's TimeZone.getTimeZone(id) method,
// and so, we need to convert it.
Matcher tzMatcher = TZ_PATTERN.matcher(zone);
if (tzMatcher.matches()) {
String sign = tzMatcher.group(2);
String hours = tzMatcher.group(3);
String minutes = tzMatcher.group(4);
// GMT+00:00 --> Etc/GMT, see "MRI behavior"
// comment below.
if (("00".equals(hours) || "0".equals(hours))
&& (minutes == null || ":00".equals(minutes) || ":0".equals(minutes))) {
zone = "Etc/GMT";
} else {
// Invert the sign, since TZ format and Java format
// use opposite signs, sigh... Also, Java API requires
// the sign to be always present, be it "+" or "-".
sign = ("-".equals(sign)? "+" : "-");
// Always use "GMT" since that's required by Java API.
zone = "GMT" + sign + hours;
if (minutes != null) {
zone += minutes;
}
}
}
// MRI behavior: With TZ equal to "GMT" or "UTC", Time.now
// is *NOT* considered as a proper GMT/UTC time:
// ENV['TZ']="GMT"
// Time.now.gmt? ==> false
// ENV['TZ']="UTC"
// Time.now.utc? ==> false
// Hence, we need to adjust for that.
if ("GMT".equalsIgnoreCase(zone) || "UTC".equalsIgnoreCase(zone)) {
zone = "Etc/" + zone;
}
DateTimeZone dtz = DateTimeZone.forTimeZone(TimeZone.getTimeZone(zone));
runtime.getLocalTimezoneCache().put(originalZone, dtz);
return dtz;
}
}
public RubyTime(Ruby runtime, RubyClass rubyClass) {
super(runtime, rubyClass);
}
public RubyTime(Ruby runtime, RubyClass rubyClass, DateTime dt) {
super(runtime, rubyClass);
this.dt = dt;
}
// We assume that these two time instances
// occurred at the same time.
private static final long BASE_TIME_MILLIS = System.currentTimeMillis();
private static final long BASE_TIME_NANOS = System.nanoTime();
private static ObjectAllocator TIME_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
long usecsPassed = (System.nanoTime() - BASE_TIME_NANOS) / 1000L;
long millisTime = BASE_TIME_MILLIS + usecsPassed / 1000L;
long usecs = usecsPassed % 1000L;
DateTimeZone dtz = getLocalTimeZone(runtime);
DateTime dt = new DateTime(millisTime, dtz);
RubyTime rt = new RubyTime(runtime, klass, dt);
rt.setUSec(usecs);
return rt;
}
};
public static RubyClass createTimeClass(Ruby runtime) {
RubyClass timeClass = runtime.defineClass("Time", runtime.getObject(), TIME_ALLOCATOR);
timeClass.index = ClassIndex.TIME;
runtime.setTime(timeClass);
timeClass.includeModule(runtime.getComparable());
timeClass.defineAnnotatedMethods(RubyTime.class);
return timeClass;
}
public void setUSec(long usec) {
this.usec = usec;
}
public long getUSec() {
return usec;
}
public void updateCal(DateTime dt) {
this.dt = dt;
}
protected long getTimeInMillis() {
return dt.getMillis(); // For JDK 1.4 we can use "cal.getTimeInMillis()"
}
public static RubyTime newTime(Ruby runtime, long milliseconds) {
return newTime(runtime, new DateTime(milliseconds));
}
public static RubyTime newTime(Ruby runtime, DateTime dt) {
return new RubyTime(runtime, runtime.getTime(), dt);
}
public static RubyTime newTime(Ruby runtime, DateTime dt, long usec) {
RubyTime t = new RubyTime(runtime, runtime.getTime(), dt);
t.setUSec(usec);
return t;
}
@Override
public Class<?> getJavaClass() {
return Date.class;
}
@JRubyMethod(name = "initialize_copy", required = 1)
@Override
public IRubyObject initialize_copy(IRubyObject original) {
if (!(original instanceof RubyTime)) {
throw getRuntime().newTypeError("Expecting an instance of class Time");
}
RubyTime originalTime = (RubyTime) original;
// We can just use dt, since it is immutable
dt = originalTime.dt;
usec = originalTime.usec;
return this;
}
@JRubyMethod(name = "succ")
public RubyTime succ() {
return newTime(getRuntime(),dt.plusSeconds(1));
}
@JRubyMethod(name = {"gmtime", "utc"})
public RubyTime gmtime() {
dt = dt.withZone(DateTimeZone.UTC);
return this;
}
@JRubyMethod(name = "localtime")
public RubyTime localtime() {
dt = dt.withZone(getLocalTimeZone(getRuntime()));
return this;
}
@JRubyMethod(name = {"gmt?", "utc?", "gmtime?"})
public RubyBoolean gmt() {
return getRuntime().newBoolean(dt.getZone().getID().equals("UTC"));
}
@JRubyMethod(name = {"getgm", "getutc"})
public RubyTime getgm() {
return newTime(getRuntime(), dt.withZone(DateTimeZone.UTC), getUSec());
}
@JRubyMethod(name = "getlocal")
public RubyTime getlocal() {
return newTime(getRuntime(), dt.withZone(getLocalTimeZone(getRuntime())), getUSec());
}
@JRubyMethod(name = "strftime", required = 1)
public RubyString strftime(IRubyObject format) {
final RubyDateFormat rubyDateFormat = new RubyDateFormat("-", Locale.US);
rubyDateFormat.applyPattern(format.toString());
rubyDateFormat.setDateTime(dt);
String result = rubyDateFormat.format(null);
return getRuntime().newString(result);
}
@JRubyMethod(name = ">=", required = 1)
public IRubyObject op_ge(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) >= 0);
}
return RubyComparable.op_ge(context, this, other);
}
@JRubyMethod(name = ">", required = 1)
public IRubyObject op_gt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) > 0);
}
return RubyComparable.op_gt(context, this, other);
}
@JRubyMethod(name = "<=", required = 1)
public IRubyObject op_le(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) <= 0);
}
return RubyComparable.op_le(context, this, other);
}
@JRubyMethod(name = "<", required = 1)
public IRubyObject op_lt(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return getRuntime().newBoolean(cmp((RubyTime) other) < 0);
}
return RubyComparable.op_lt(context, this, other);
}
private int cmp(RubyTime other) {
long millis = getTimeInMillis();
long millis_other = other.getTimeInMillis();
long usec_other = other.usec;
if (millis > millis_other || (millis == millis_other && usec > usec_other)) {
return 1;
} else if (millis < millis_other || (millis == millis_other && usec < usec_other)) {
return -1;
}
return 0;
}
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus(IRubyObject other) {
long time = getTimeInMillis();
if (other instanceof RubyTime) {
throw getRuntime().newTypeError("time + time ?");
}
long adjustment = (long) (RubyNumeric.num2dbl(other) * 1000000);
int micro = (int) (adjustment % 1000);
adjustment = adjustment / 1000;
time += adjustment;
RubyTime newTime = new RubyTime(getRuntime(), getMetaClass());
newTime.dt = new DateTime(time).withZone(dt.getZone());
newTime.setUSec(micro);
return newTime;
}
private IRubyObject opMinus(RubyTime other) {
long time = getTimeInMillis() * 1000 + getUSec();
time -= other.getTimeInMillis() * 1000 + other.getUSec();
return RubyFloat.newFloat(getRuntime(), time / 1000000.0); // float number of seconds
}
@JRubyMethod(name = "-", required = 1)
public IRubyObject op_minus(IRubyObject other) {
if (other instanceof RubyTime) return opMinus((RubyTime) other);
long time = getTimeInMillis();
long adjustment = (long) (RubyNumeric.num2dbl(other) * 1000000);
int micro = (int) (adjustment % 1000);
adjustment = adjustment / 1000;
time -= adjustment;
RubyTime newTime = new RubyTime(getRuntime(), getMetaClass());
newTime.dt = new DateTime(time).withZone(dt.getZone());
newTime.setUSec(micro);
return newTime;
}
@JRubyMethod(name = "===", required = 1)
@Override
public IRubyObject op_eqq(ThreadContext context, IRubyObject other) {
return (RubyNumeric.fix2int(callMethod(context, MethodIndex.OP_SPACESHIP, "<=>", other)) == 0) ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
if (other instanceof RubyTime) {
return context.getRuntime().newFixnum(cmp((RubyTime) other));
}
return context.getRuntime().getNil();
}
@JRubyMethod(name = "eql?", required = 1)
@Override
public IRubyObject eql_p(IRubyObject other) {
if (other instanceof RubyTime) {
RubyTime otherTime = (RubyTime)other;
return (usec == otherTime.usec && getTimeInMillis() == otherTime.getTimeInMillis()) ? getRuntime().getTrue() : getRuntime().getFalse();
}
return getRuntime().getFalse();
}
@JRubyMethod(name = {"asctime", "ctime"})
public RubyString asctime() {
DateTimeFormatter simpleDateFormat;
if (dt.getDayOfMonth() < 10) {
simpleDateFormat = ONE_DAY_CTIME_FORMATTER;
} else {
simpleDateFormat = TWO_DAY_CTIME_FORMATTER;
}
String result = simpleDateFormat.print(dt);
return getRuntime().newString(result);
}
@JRubyMethod(name = {"to_s", "inspect"})
@Override
public IRubyObject to_s() {
DateTimeFormatter simpleDateFormat;
if (dt.getZone() == DateTimeZone.UTC) {
simpleDateFormat = TO_S_UTC_FORMATTER;
} else {
simpleDateFormat = TO_S_FORMATTER;
}
String result = simpleDateFormat.print(dt);
return getRuntime().newString(result);
}
@JRubyMethod(name = "to_a")
@Override
public RubyArray to_a() {
return getRuntime().newArrayNoCopy(new IRubyObject[] { sec(), min(), hour(), mday(), month(),
year(), wday(), yday(), isdst(), zone() });
}
@JRubyMethod(name = "to_f")
public RubyFloat to_f() {
long time = getTimeInMillis();
time = time * 1000 + usec;
return RubyFloat.newFloat(getRuntime(), time / 1000000.0);
}
@JRubyMethod(name = {"to_i", "tv_sec"})
public RubyInteger to_i() {
return getRuntime().newFixnum(getTimeInMillis() / 1000);
}
@JRubyMethod(name = {"usec", "tv_usec"})
public RubyInteger usec() {
return getRuntime().newFixnum(dt.getMillisOfSecond() * 1000 + getUSec());
}
public void setMicroseconds(long mic) {
long millis = getTimeInMillis() % 1000;
long withoutMillis = getTimeInMillis() - millis;
withoutMillis += (mic / 1000);
dt = dt.withMillis(withoutMillis);
usec = mic % 1000;
}
public long microseconds() {
return getTimeInMillis() % 1000 * 1000 + usec;
}
@JRubyMethod(name = "sec")
public RubyInteger sec() {
return getRuntime().newFixnum(dt.getSecondOfMinute());
}
@JRubyMethod(name = "min")
public RubyInteger min() {
return getRuntime().newFixnum(dt.getMinuteOfHour());
}
@JRubyMethod(name = "hour")
public RubyInteger hour() {
return getRuntime().newFixnum(dt.getHourOfDay());
}
@JRubyMethod(name = {"mday", "day"})
public RubyInteger mday() {
return getRuntime().newFixnum(dt.getDayOfMonth());
}
@JRubyMethod(name = {"month", "mon"})
public RubyInteger month() {
return getRuntime().newFixnum(dt.getMonthOfYear());
}
@JRubyMethod(name = "year")
public RubyInteger year() {
return getRuntime().newFixnum(dt.getYear());
}
@JRubyMethod(name = "wday")
public RubyInteger wday() {
return getRuntime().newFixnum((dt.getDayOfWeek()%7));
}
@JRubyMethod(name = "yday")
public RubyInteger yday() {
return getRuntime().newFixnum(dt.getDayOfYear());
}
@JRubyMethod(name = {"gmt_offset", "gmtoff", "utc_offset"})
public RubyInteger gmt_offset() {
int offset = dt.getZone().getOffsetFromLocal(dt.getMillis());
return getRuntime().newFixnum((int)(offset/1000));
}
@JRubyMethod(name = {"isdst", "dst?"})
public RubyBoolean isdst() {
return getRuntime().newBoolean(!dt.getZone().isStandardOffset(dt.getMillis()));
}
@JRubyMethod(name = "zone")
public RubyString zone() {
String zone = dt.getZone().getShortName(dt.getMillis());
if(zone.equals("+00:00")) {
zone = "GMT";
}
return getRuntime().newString(zone);
}
public void setDateTime(DateTime dt) {
this.dt = dt;
}
public DateTime getDateTime() {
return this.dt;
}
public Date getJavaDate() {
return this.dt.toDate();
}
@JRubyMethod(name = "hash")
@Override
public RubyFixnum hash() {
// modified to match how hash is calculated in 1.8.2
return getRuntime().newFixnum((int)(((dt.getMillis() / 1000) ^ microseconds()) << 1) >> 1);
}
@JRubyMethod(name = "_dump", optional = 1, frame = true)
public RubyString dump(IRubyObject[] args, Block unusedBlock) {
RubyString str = (RubyString) mdump(new IRubyObject[] { this });
str.syncVariables(this.getVariableList());
return str;
}
public RubyObject mdump(final IRubyObject[] args) {
RubyTime obj = (RubyTime)args[0];
DateTime dateTime = obj.dt.withZone(DateTimeZone.UTC);
byte dumpValue[] = new byte[8];
int pe =
0x1 << 31 |
(dateTime.getYear()-1900) << 14 |
(dateTime.getMonthOfYear()-1) << 10 |
dateTime.getDayOfMonth() << 5 |
dateTime.getHourOfDay();
int se =
dateTime.getMinuteOfHour() << 26 |
dateTime.getSecondOfMinute() << 20 |
(dateTime.getMillisOfSecond() * 1000 + (int)usec); // dump usec, not msec
for(int i = 0; i < 4; i++) {
dumpValue[i] = (byte)(pe & 0xFF);
pe >>>= 8;
}
for(int i = 4; i < 8 ;i++) {
dumpValue[i] = (byte)(se & 0xFF);
se >>>= 8;
}
return RubyString.newString(obj.getRuntime(), new ByteList(dumpValue,false));
}
@JRubyMethod(name = "initialize", frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(Block block) {
return this;
}
/* Time class methods */
public static IRubyObject s_new(IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = recv.getRuntime();
RubyTime time = new RubyTime(runtime, (RubyClass) recv, new DateTime(getLocalTimeZone(runtime)));
time.callInit(args,block);
return time;
}
/**
* @deprecated Use {@link #newInstance(ThreadContext, IRubyObject)}
*/
@Deprecated
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return newInstance(context, recv);
}
@JRubyMethod(name = "now", backtrace = true, meta = true)
public static IRubyObject newInstance(ThreadContext context, IRubyObject recv) {
IRubyObject obj = ((RubyClass) recv).allocate();
obj.getMetaClass().getBaseCallSites()[RubyClass.CS_IDX_INITIALIZE].call(context, obj);
return obj;
}
@JRubyMethod(name = "at", meta = true)
public static IRubyObject at(ThreadContext context, IRubyObject recv, IRubyObject arg) {
Ruby runtime = context.getRuntime();
final RubyTime time;
if (arg instanceof RubyTime) {
RubyTime other = (RubyTime) arg;
time = new RubyTime(runtime, (RubyClass) recv, other.dt);
time.setUSec(other.getUSec());
} else {
time = new RubyTime(runtime, (RubyClass) recv,
new DateTime(0L, getLocalTimeZone(runtime)));
long seconds = RubyNumeric.num2long(arg);
long millisecs = 0;
long microsecs = 0;
// In the case of two arguments, MRI will discard the portion of
// the first argument after a decimal point (i.e., "floor").
// However in the case of a single argument, any portion after
// the decimal point is honored.
if (arg instanceof RubyFloat) {
double dbl = ((RubyFloat) arg).getDoubleValue();
long micro = (long) ((dbl - seconds) * 1000000);
millisecs = micro / 1000;
microsecs = micro % 1000;
}
time.setUSec(microsecs);
time.dt = time.dt.withMillis(seconds * 1000 + millisecs);
}
time.getMetaClass().getBaseCallSites()[RubyClass.CS_IDX_INITIALIZE].call(context, time);
return time;
}
@JRubyMethod(name = "at", meta = true)
public static IRubyObject at(ThreadContext context, IRubyObject recv, IRubyObject arg1, IRubyObject arg2) {
Ruby runtime = context.getRuntime();
RubyTime time = new RubyTime(runtime, (RubyClass) recv,
new DateTime(0L, getLocalTimeZone(runtime)));
long seconds = RubyNumeric.num2long(arg1);
long millisecs = 0;
long microsecs = 0;
long tmp = RubyNumeric.num2long(arg2);
millisecs = tmp / 1000;
microsecs = tmp % 1000;
time.setUSec(microsecs);
time.dt = time.dt.withMillis(seconds * 1000 + millisecs);
time.getMetaClass().getBaseCallSites()[RubyClass.CS_IDX_INITIALIZE].call(context, time);
return time;
}
@JRubyMethod(name = {"local", "mktime"}, required = 1, optional = 9, meta = true)
public static RubyTime new_local(IRubyObject recv, IRubyObject[] args) {
return createTime(recv, args, false);
}
@JRubyMethod(name = {"utc", "gm"}, required = 1, optional = 9, meta = true)
public static RubyTime new_utc(IRubyObject recv, IRubyObject[] args) {
return createTime(recv, args, true);
}
@JRubyMethod(name = "_load", required = 1, frame = true, meta = true)
public static RubyTime load(IRubyObject recv, IRubyObject from, Block block) {
return s_mload(recv, (RubyTime)(((RubyClass)recv).allocate()), from);
}
protected static RubyTime s_mload(IRubyObject recv, RubyTime time, IRubyObject from) {
Ruby runtime = recv.getRuntime();
DateTime dt = new DateTime(DateTimeZone.UTC);
byte[] fromAsBytes = null;
fromAsBytes = from.convertToString().getBytes();
if(fromAsBytes.length != 8) {
throw runtime.newTypeError("marshaled time format differ");
}
int p=0;
int s=0;
for (int i = 0; i < 4; i++) {
p |= ((int)fromAsBytes[i] & 0xFF) << (8 * i);
}
for (int i = 4; i < 8; i++) {
s |= ((int)fromAsBytes[i] & 0xFF) << (8 * (i - 4));
}
if ((p & (1<<31)) == 0) {
dt = dt.withMillis(p * 1000L + s);
} else {
p &= ~(1<<31);
dt = dt.withYear(((p >>> 14) & 0xFFFF) + 1900);
dt = dt.withMonthOfYear(((p >>> 10) & 0xF) + 1);
dt = dt.withDayOfMonth(((p >>> 5) & 0x1F));
dt = dt.withHourOfDay((p & 0x1F));
dt = dt.withMinuteOfHour(((s >>> 26) & 0x3F));
dt = dt.withSecondOfMinute(((s >>> 20) & 0x3F));
// marsaling dumps usec, not msec
dt = dt.withMillisOfSecond((s & 0xFFFFF) / 1000);
dt = dt.withZone(getLocalTimeZone(runtime));
time.setUSec((s & 0xFFFFF) % 1000);
}
time.setDateTime(dt);
return time;
}
private static final String[] MONTHS = {"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"};
private static final Map<String, Integer> MONTHS_MAP = new HashMap<String, Integer>();
static {
for (int i = 0; i < MONTHS.length; i++) {
MONTHS_MAP.put(MONTHS[i], i + 1);
}
}
private static final int[] time_min = {1, 0, 0, 0, Integer.MIN_VALUE};
private static final int[] time_max = {31, 23, 59, 60, Integer.MAX_VALUE};
private static final int ARG_SIZE = 7;
private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt) {
Ruby runtime = recv.getRuntime();
int len = ARG_SIZE;
if (args.length == 10) {
args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil() };
} else {
// MRI accepts additional wday argument which appears to be ignored.
len = args.length;
if (len < ARG_SIZE) {
IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
System.arraycopy(args, 0, newArgs, 0, args.length);
for (int i = len; i < ARG_SIZE; i++) {
newArgs[i] = runtime.getNil();
}
args = newArgs;
len = ARG_SIZE;
}
}
if (args[0] instanceof RubyString) {
args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
}
int year = (int) RubyNumeric.num2long(args[0]);
int month = 1;
if (len > 1) {
if (!args[1].isNil()) {
IRubyObject tmp = args[1].checkStringType();
if (!tmp.isNil()) {
String monthString = tmp.toString().toLowerCase();
Integer monthInt = MONTHS_MAP.get(monthString);
if (monthInt != null) {
month = monthInt;
} else {
try {
month = Integer.parseInt(monthString);
} catch (NumberFormatException nfExcptn) {
throw runtime.newArgumentError("Argument out of range.");
}
}
} else {
month = (int) RubyNumeric.num2long(args[1]);
}
}
if (1 > month || month > 12) {
throw runtime.newArgumentError("Argument out of range: for month: " + month);
}
}
int[] int_args = { 1, 0, 0, 0, 0, 0 };
for (int i = 0; int_args.length >= i + 2; i++) {
if (!args[i + 2].isNil()) {
if (!(args[i + 2] instanceof RubyNumeric)) {
args[i + 2] = args[i + 2].callMethod(
runtime.getCurrentContext(), "to_i");
}
long value = RubyNumeric.num2long(args[i + 2]);
if (time_min[i] > value || value > time_max[i]) {
throw runtime.newArgumentError("argument out of range.");
}
int_args[i] = (int) value;
}
}
if (0 <= year && year < 39) {
year += 2000;
} else if (69 <= year && year < 139) {
year += 1900;
}
DateTimeZone dtz;
if (gmt) {
dtz = DateTimeZone.UTC;
} else {
dtz = getLocalTimeZone(runtime);
}
DateTime dt;
// set up with min values and then add to allow rolling over
try {
dt = new DateTime(year, 1, 1, 0, 0 , 0, 0, dtz);
dt = dt.plusMonths(month - 1)
.plusDays(int_args[0] - 1)
.plusHours(int_args[1])
.plusMinutes(int_args[2])
.plusSeconds(int_args[3]);
} catch (org.joda.time.IllegalFieldValueException e) {
throw runtime.newArgumentError("time out of range");
}
RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
// Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
if (args.length != 8 && !args[6].isNil()) {
int usec = int_args[4] % 1000;
int msec = int_args[4] / 1000;
if (int_args[4] < 0) {
msec -= 1;
usec += 1000;
}
time.dt = dt.withMillis(dt.getMillis() + msec);
time.setUSec(usec);
}
time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
return time;
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2004 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* Note: This was renamed from UnboundMethod.java
*
* @author jpetersen
*/
@JRubyClass(name="UnboundMethod", parent="Method")
public class RubyUnboundMethod extends RubyMethod {
protected RubyUnboundMethod(Ruby runtime) {
super(runtime, runtime.getUnboundMethod());
}
public static RubyUnboundMethod newUnboundMethod(
RubyModule implementationModule,
String methodName,
RubyModule originModule,
String originName,
DynamicMethod method) {
RubyUnboundMethod newMethod = new RubyUnboundMethod(implementationModule.getRuntime());
newMethod.implementationModule = implementationModule;
newMethod.methodName = methodName;
newMethod.originModule = originModule;
newMethod.originName = originName;
newMethod.method = method;
return newMethod;
}
public static RubyClass defineUnboundMethodClass(Ruby runtime) {
// TODO: NOT_ALLOCATABLE_ALLOCATOR is probably ok here. Confirm. JRUBY-415
RubyClass newClass =
runtime.defineClass("UnboundMethod", runtime.getMethod(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setUnboundMethod(newClass);
newClass.defineAnnotatedMethods(RubyUnboundMethod.class);
return newClass;
}
/**
* @see org.jruby.RubyMethod#call(IRubyObject[])
*/
@JRubyMethod(name = {"call", "[]"}, rest = true, frame = true)
@Override
public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) {
throw context.getRuntime().newTypeError("you cannot call unbound method; bind first");
}
/**
* @see org.jruby.RubyMethod#unbind()
*/
@JRubyMethod(name = "unbind", frame = true)
@Override
public RubyUnboundMethod unbind(Block block) {
return this;
}
@JRubyMethod(name = "bind", required = 1, frame = true)
public RubyMethod bind(ThreadContext context, IRubyObject aReceiver, Block block) {
RubyClass receiverClass = aReceiver.getMetaClass();
if (!originModule.isInstance(aReceiver)) {
if (originModule instanceof MetaClass) {
throw context.getRuntime().newTypeError("singleton method called for a different object");
} else if (receiverClass instanceof MetaClass && receiverClass.getMethods().containsKey(originName)) {
throw context.getRuntime().newTypeError("method `" + originName + "' overridden");
} else if (
!(originModule.isModule() ? originModule.isInstance(aReceiver) : aReceiver.getType() == originModule)) {
// FIX replace type() == ... with isInstanceOf(...)
throw context.getRuntime().newTypeError("bind argument must be an instance of " + originModule.getName());
}
}
return RubyMethod.newMethod(implementationModule, methodName, receiverClass, originName, method, aReceiver);
}
@JRubyMethod(name = "clone")
@Override
public RubyMethod rbClone() {
return newUnboundMethod(implementationModule, methodName, originModule, originName, method);
}
@JRubyMethod(name = "to_proc", frame = true)
@Override
public IRubyObject to_proc(ThreadContext context, Block unusedBlock) {
return super.to_proc(context, unusedBlock);
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 Ola Bini <ola.bini@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyModule;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.Visibility;
import org.jruby.yaml.JRubyRepresenter;
import org.jruby.yaml.JRubyConstructor;
import org.jruby.yaml.JRubySerializer;
import org.jruby.util.IOInputStream;
import org.jruby.util.IOOutputStream;
import org.jvyamlb.Representer;
import org.jvyamlb.Constructor;
import org.jvyamlb.ParserImpl;
import org.jvyamlb.PositioningParserImpl;
import org.jvyamlb.Scanner;
import org.jvyamlb.ScannerImpl;
import org.jvyamlb.Composer;
import org.jvyamlb.ComposerImpl;
import org.jvyamlb.PositioningScannerImpl;
import org.jvyamlb.PositioningComposerImpl;
import org.jvyamlb.Serializer;
import org.jvyamlb.ResolverImpl;
import org.jvyamlb.EmitterImpl;
import org.jvyamlb.exceptions.YAMLException;
import org.jvyamlb.YAMLConfig;
import org.jvyamlb.YAML;
import org.jvyamlb.PositioningScanner;
import org.jvyamlb.Positionable;
import org.jvyamlb.Position;
/**
* @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
*/
@JRubyModule(name="YAML")
public class RubyYAML {
public static RubyModule createYAMLModule(Ruby runtime) {
RubyModule result = runtime.defineModule("YAML");
runtime.getKernel().callMethod(runtime.getCurrentContext(),"require", runtime.newString("stringio"));
result.defineAnnotatedMethods(RubyYAML.class);
RubyClass obj = runtime.getObject();
RubyClass clazz = runtime.getClassClass();
RubyClass hash = runtime.getHash();
RubyClass array = runtime.getArray();
RubyClass struct = runtime.getStructClass();
RubyClass exception = runtime.getException();
RubyClass string = runtime.getString();
RubyClass symbol = runtime.getSymbol();
RubyClass range = runtime.getRange();
RubyClass regexp = runtime.getRegexp();
RubyClass time = runtime.getTime();
RubyClass date = runtime.fastGetClass("Date");
RubyClass fixnum = runtime.getFixnum();
RubyClass bignum = runtime.getBignum();
RubyClass flt = runtime.getFloat();
RubyClass trueClass = runtime.getTrueClass();
RubyClass falseClass = runtime.getFalseClass();
RubyClass nilClass = runtime.getNilClass();
clazz.defineAnnotatedMethods(YAMLClassMethods.class);
obj.defineAnnotatedMethods(YAMLObjectMethods.class);
hash.defineAnnotatedMethods(YAMLHashMethods.class);
array.defineAnnotatedMethods(YAMLArrayMethods.class);
struct.defineAnnotatedMethods(YAMLStructMethods.class);
exception.defineAnnotatedMethods(YAMLExceptionMethods.class);
string.defineAnnotatedMethods(YAMLStringMethods.class);
symbol.defineAnnotatedMethods(YAMLSymbolMethods.class);
range.defineAnnotatedMethods(YAMLRangeMethods.class);
regexp.defineAnnotatedMethods(YAMLRegexpMethods.class);
time.defineAnnotatedMethods(YAMLTimeMethods.class);
date.defineAnnotatedMethods(YAMLDateMethods.class);
bignum.defineAnnotatedMethods(YAMLNumericMethods.class);
fixnum.defineAnnotatedMethods(YAMLNumericMethods.class);
flt.defineAnnotatedMethods(YAMLNumericMethods.class);
trueClass.defineAnnotatedMethods(YAMLTrueMethods.class);
falseClass.defineAnnotatedMethods(YAMLFalseMethods.class);
nilClass.defineAnnotatedMethods(YAMLNilMethods.class);
runtime.setObjectToYamlMethod(runtime.getObject().searchMethod("to_yaml"));
return result;
}
@JRubyMethod(name = "dump", required = 1, optional = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject dump(IRubyObject self, IRubyObject[] args) {
IRubyObject obj = args[0];
Ruby runtime = self.getRuntime();
IRubyObject val = runtime.newArray(obj);
if(args.length>1) {
return RuntimeHelpers.invoke(runtime.getCurrentContext(), self,"dump_all", val, args[1]);
} else {
return self.callMethod(runtime.getCurrentContext(),"dump_all", val);
}
}
@JRubyMethod(name = "dump_all", required = 1, optional = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject dump_all(IRubyObject self, IRubyObject[] args) {
ThreadContext context = self.getRuntime().getCurrentContext();
RubyArray objs = (RubyArray)args[0];
IRubyObject io = null;
IRubyObject io2 = null;
if(args.length == 2 && args[1] != null && !args[1].isNil()) {
io = args[1];
}
YAMLConfig cfg = YAML.config().version("1.0");
IOOutputStream iox = null;
if(null == io) {
io2 = self.getRuntime().fastGetClass("StringIO").callMethod(context, "new");
iox = new IOOutputStream(io2);
} else {
iox = new IOOutputStream(io);
}
Serializer ser = new JRubySerializer(new EmitterImpl(iox,cfg),new ResolverImpl(),cfg);
try {
ser.open();
Representer r = new JRubyRepresenter(ser, cfg);
for(Iterator iter = objs.getList().iterator();iter.hasNext();) {
r.represent(iter.next());
}
ser.close();
} catch(IOException e) {
throw self.getRuntime().newIOErrorFromException(e);
}
if(null == io) {
io2.callMethod(context, "rewind");
return io2.callMethod(context, "read");
} else {
return io;
}
}
@JRubyMethod(name = "_parse_internal", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject parse_internal(IRubyObject self, IRubyObject arg) {
boolean debug = self.getRuntime().getDebug().isTrue();
IRubyObject io = check_yaml_port(arg);
Scanner scn = null;
try {
if(io instanceof RubyString) {
scn = debug ? new PositioningScannerImpl(((RubyString)io).getByteList()) : new ScannerImpl(((RubyString)io).getByteList());
} else {
scn = debug ? new PositioningScannerImpl(new IOInputStream(io)) : new ScannerImpl(new IOInputStream(io));
}
Composer ctor =
debug ?
new PositioningComposerImpl(new PositioningParserImpl((PositioningScanner)scn,YAML.config().version("1.0")),new ResolverImpl()) :
new ComposerImpl(new ParserImpl(scn,YAML.config().version("1.0")),new ResolverImpl())
;
if(ctor.checkNode()) {
return JavaEmbedUtils.javaToRuby(self.getRuntime(),ctor.getNode());
}
return self.getRuntime().getNil();
} catch(YAMLException e) {
if(self.getRuntime().getDebug().isTrue()) {
Position.Range range = ((Positionable)e).getRange();
throw self.getRuntime().newArgumentError("syntax error on " + range.start + ":" + range.end + ": " + e.getMessage());
} else {
throw self.getRuntime().newArgumentError("syntax error:" + e.getMessage());
}
}
}
@JRubyMethod(name = "load", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject load(IRubyObject self, IRubyObject arg) {
boolean debug = self.getRuntime().getDebug().isTrue();
IRubyObject io = check_yaml_port(arg);
Scanner scn = null;
try {
if(io instanceof RubyString) {
scn = debug ? new PositioningScannerImpl(((RubyString)io).getByteList()) : new ScannerImpl(((RubyString)io).getByteList());
} else {
scn = debug ? new PositioningScannerImpl(new IOInputStream(io)) : new ScannerImpl(new IOInputStream(io));
}
Constructor ctor =
debug ?
new JRubyConstructor(self, new PositioningComposerImpl(new PositioningParserImpl((PositioningScanner)scn,YAML.config().version("1.0")),new ResolverImpl())) :
new JRubyConstructor(self, new ComposerImpl(new ParserImpl(scn,YAML.config().version("1.0")),new ResolverImpl()))
;
if(ctor.checkData()) {
return JavaEmbedUtils.javaToRuby(self.getRuntime(),ctor.getData());
}
return self.getRuntime().getNil();
} catch(YAMLException e) {
if(self.getRuntime().getDebug().isTrue()) {
Position.Range range = ((Positionable)e).getRange();
throw self.getRuntime().newArgumentError("syntax error on " + range.start + ":" + range.end + ": " + e.getMessage());
} else {
throw self.getRuntime().newArgumentError("syntax error:" + e.getMessage());
}
}
}
@JRubyMethod(name = "load_file", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject load_file(IRubyObject self, IRubyObject arg) {
Ruby runtime = self.getRuntime();
ThreadContext context = runtime.getCurrentContext();
IRubyObject io = RuntimeHelpers.invoke(context, runtime.getFile(),"open", arg, runtime.newString("r"));
IRubyObject val = self.callMethod(context,"load", io);
io.callMethod(context, "close");
return val;
}
@JRubyMethod(name = "each_document", required = 1, frame = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject each_document(IRubyObject self, IRubyObject arg, Block block) {
boolean debug = self.getRuntime().getDebug().isTrue();
ThreadContext context = self.getRuntime().getCurrentContext();
IRubyObject io = arg;
Scanner scn = null;
try {
if(io instanceof RubyString) {
scn = debug ? new PositioningScannerImpl(((RubyString)io).getByteList()) : new ScannerImpl(((RubyString)io).getByteList());
} else {
scn = debug ? new PositioningScannerImpl(new IOInputStream(io)) : new ScannerImpl(new IOInputStream(io));
}
Constructor ctor =
debug ?
new JRubyConstructor(self, new PositioningComposerImpl(new PositioningParserImpl((PositioningScanner)scn,YAML.config().version("1.0")),new ResolverImpl())) :
new JRubyConstructor(self, new ComposerImpl(new ParserImpl(scn,YAML.config().version("1.0")),new ResolverImpl()))
;
while(ctor.checkData()) {
block.yield(context, JavaEmbedUtils.javaToRuby(self.getRuntime(),ctor.getData()));
}
return self.getRuntime().getNil();
} catch(YAMLException e) {
if(self.getRuntime().getDebug().isTrue()) {
Position.Range range = ((Positionable)e).getRange();
throw self.getRuntime().newArgumentError("syntax error on " + range.start + ":" + range.end + ": " + e.getMessage());
} else {
throw self.getRuntime().newArgumentError("syntax error:" + e.getMessage());
}
}
}
@JRubyMethod(name = "load_documents", required = 1, frame = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject load_documents(IRubyObject self, IRubyObject arg, Block block) {
boolean debug = self.getRuntime().getDebug().isTrue();
ThreadContext context = self.getRuntime().getCurrentContext();
IRubyObject io = check_yaml_port(arg);
Scanner scn = null;
try {
if(io instanceof RubyString) {
scn = debug ? new PositioningScannerImpl(((RubyString)io).getByteList()) : new ScannerImpl(((RubyString)io).getByteList());
} else {
scn = debug ? new PositioningScannerImpl(new IOInputStream(io)) : new ScannerImpl(new IOInputStream(io));
}
Constructor ctor =
debug ?
new JRubyConstructor(self, new PositioningComposerImpl(new PositioningParserImpl((PositioningScanner)scn,YAML.config().version("1.0")),new ResolverImpl())) :
new JRubyConstructor(self, new ComposerImpl(new ParserImpl(scn,YAML.config().version("1.0")),new ResolverImpl()))
;
while(ctor.checkData()) {
block.yield(context, JavaEmbedUtils.javaToRuby(self.getRuntime(),ctor.getData()));
}
return self.getRuntime().getNil();
} catch(YAMLException e) {
if(self.getRuntime().getDebug().isTrue()) {
Position.Range range = ((Positionable)e).getRange();
throw self.getRuntime().newArgumentError("syntax error on " + range.start + ":" + range.end + ": " + e.getMessage());
} else {
throw self.getRuntime().newArgumentError("syntax error:" + e.getMessage());
}
}
}
@JRubyMethod(name = "load_stream", required = 1, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject load_stream(IRubyObject self, IRubyObject arg) {
boolean debug = self.getRuntime().getDebug().isTrue();
ThreadContext context = self.getRuntime().getCurrentContext();
IRubyObject d = self.getRuntime().getNil();
IRubyObject io = arg;
Scanner scn = null;
try {
if(io instanceof RubyString) {
scn = debug ? new PositioningScannerImpl(((RubyString)io).getByteList()) : new ScannerImpl(((RubyString)io).getByteList());
} else {
scn = debug ? new PositioningScannerImpl(new IOInputStream(io)) : new ScannerImpl(new IOInputStream(io));
}
Constructor ctor =
debug ?
new JRubyConstructor(self, new PositioningComposerImpl(new PositioningParserImpl((PositioningScanner)scn,YAML.config().version("1.0")),new ResolverImpl())) :
new JRubyConstructor(self, new ComposerImpl(new ParserImpl(scn,YAML.config().version("1.0")),new ResolverImpl()))
;
while(ctor.checkData()) {
if(d.isNil()) {
d = self.getRuntime().fastGetModule("YAML").fastGetClass("Stream").callMethod(context,"new", d);
}
d.callMethod(context,"add", JavaEmbedUtils.javaToRuby(self.getRuntime(),ctor.getData()));
}
return d;
} catch(YAMLException e) {
if(self.getRuntime().getDebug().isTrue()) {
Position.Range range = ((Positionable)e).getRange();
throw self.getRuntime().newArgumentError("syntax error on " + range.start + ":" + range.end + ": " + e.getMessage());
} else {
throw self.getRuntime().newArgumentError("syntax error:" + e.getMessage());
}
}
}
@JRubyMethod(name = "dump_stream", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject dump_stream(IRubyObject self, IRubyObject[] args) {
ThreadContext context = self.getRuntime().getCurrentContext();
IRubyObject stream = self.getRuntime().fastGetModule("YAML").fastGetClass("Stream").callMethod(context, "new");
for(int i=0,j=args.length;i<j;i++) {
stream.callMethod(context,"add", args[i]);
}
return stream.callMethod(context, "emit");
}
@JRubyMethod(name = "quick_emit_node", required = 1, rest = true, frame = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject quick_emit_node(IRubyObject self, IRubyObject[] args, Block block) {
return block.yield(self.getRuntime().getCurrentContext(), args[0]);
}
// @JRubyMethod(name = "quick_emit_node", rest = true, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject quick_emit(IRubyObject self, IRubyObject[] args) {
return self.getRuntime().getNil();
}
// prepares IO port type for load (ported from ext/syck/rubyext.c)
private static IRubyObject check_yaml_port(IRubyObject port) {
if (port instanceof RubyString) {
// OK
}
else if (port.respondsTo("read")) {
if (port.respondsTo("binmode")) {
ThreadContext context = port.getRuntime().getCurrentContext();
port.callMethod(context, "binmode");
}
}
else {
throw port.getRuntime().newTypeError("instance of IO needed");
}
return port;
}
@JRubyClass(name="Hash")
public static class YAMLHashMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject hash_to_yaml_node(IRubyObject self, IRubyObject arg) {
Ruby runtime = self.getRuntime();
ThreadContext context = runtime.getCurrentContext();
return RuntimeHelpers.invoke(context, arg, "map", self.callMethod(context, "taguri"), self, self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="Object")
public static class YAMLObjectMethods {
@JRubyMethod(name = "to_yaml_properties")
public static IRubyObject obj_to_yaml_properties(IRubyObject self) {
ThreadContext context = self.getRuntime().getCurrentContext();
return self.callMethod(context, "instance_variables").callMethod(context, "sort");
}
@JRubyMethod(name = "to_yaml_style")
public static IRubyObject obj_to_yaml_style(IRubyObject self) {
return self.getRuntime().getNil();
}
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject obj_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
Map mep = (Map)(new RubyHash(self.getRuntime()));
RubyArray props = (RubyArray)self.callMethod(context, "to_yaml_properties");
for(Iterator iter = props.getList().iterator(); iter.hasNext();) {
String m = iter.next().toString();
mep.put(self.getRuntime().newString(m.substring(1)), self.callMethod(context,"instance_variable_get", self.getRuntime().newString(m)));
}
return RuntimeHelpers.invoke(context, arg, "map", self.callMethod(context, "taguri"), (IRubyObject)mep, self.callMethod(context, "to_yaml_style"));
}
@JRubyMethod(name = "to_yaml", rest = true)
public static IRubyObject obj_to_yaml(IRubyObject self, IRubyObject[] args) {
ThreadContext context = self.getRuntime().getCurrentContext();
return self.getRuntime().fastGetModule("YAML").callMethod(context,"dump", self);
}
@JRubyMethod(name = "taguri")
public static IRubyObject obj_taguri(IRubyObject self) {
return self.getRuntime().newString("!ruby/object:" + self.getType().getName());
}
}
@JRubyClass(name="Class")
public static class YAMLClassMethods {
@JRubyMethod(name = "to_yaml", rest = true)
public static IRubyObject class_to_yaml(IRubyObject self, IRubyObject[] args) {
throw self.getRuntime().newTypeError("can't dump anonymous class " + self.getType().getName());
}
}
@JRubyClass(name="Array")
public static class YAMLArrayMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject array_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
return RuntimeHelpers.invoke(context, arg, "seq", self.callMethod(context, "taguri"), self, self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="Struct")
public static class YAMLStructMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject struct_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
Map mep = (Map)(new RubyHash(self.getRuntime()));
for(Iterator iter = ((RubyArray)self.callMethod(context, "members")).getList().iterator();iter.hasNext();) {
IRubyObject key = self.getRuntime().newString(iter.next().toString());
mep.put(key,self.callMethod(context,MethodIndex.AREF, "[]", key));
}
for(Iterator iter = ((RubyArray)self.callMethod(context, "to_yaml_properties")).getList().iterator(); iter.hasNext();) {
String m = iter.next().toString();
mep.put(self.getRuntime().newString(m.substring(1)), self.callMethod(context,"instance_variable_get", self.getRuntime().newString(m)));
}
return RuntimeHelpers.invoke(context, arg, "map", self.callMethod(context, "taguri"), (IRubyObject)mep, self.callMethod(context, "to_yaml_style"));
}
@JRubyMethod(name = "taguri")
public static IRubyObject struct_taguri(IRubyObject self) {
return self.getRuntime().newString("!ruby/struct:" + self.getType().getName());
}
}
@JRubyClass(name="Exception")
public static class YAMLExceptionMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject exception_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
Map mep = (Map)(new RubyHash(self.getRuntime()));
mep.put(self.getRuntime().newString("message"),self.callMethod(context, "message"));
for(Iterator iter = ((RubyArray)self.callMethod(context, "to_yaml_properties")).getList().iterator(); iter.hasNext();) {
String m = iter.next().toString();
mep.put(self.getRuntime().newString(m.substring(1)), self.callMethod(context,"instance_variable_get", self.getRuntime().newString(m)));
}
return RuntimeHelpers.invoke(context, arg,"map", self.callMethod(context, "taguri"), (IRubyObject)mep, self.callMethod(context, "to_yaml_style"));
}
@JRubyMethod(name = "taguri")
public static IRubyObject exception_taguri(IRubyObject self) {
return self.getRuntime().newString("!ruby/exception:" + self.getType().getName());
}
}
private static final Pattern AFTER_NEWLINE = Pattern.compile("\n.+", Pattern.DOTALL);
@JRubyClass(name="String")
public static class YAMLStringMethods {
@JRubyMethod(name = "is_complex_yaml?")
public static IRubyObject string_is_complex(IRubyObject self) {
ThreadContext context = self.getRuntime().getCurrentContext();
return (self.callMethod(context, "to_yaml_style").isTrue() ||
((List)self.callMethod(context, "to_yaml_properties")).isEmpty() ||
AFTER_NEWLINE.matcher(self.toString()).find()) ? self.getRuntime().getTrue() : self.getRuntime().getFalse();
}
@JRubyMethod(name = "is_binary_data?")
public static IRubyObject string_is_binary(IRubyObject self) {
ThreadContext context = self.getRuntime().getCurrentContext();
if(self.callMethod(context, MethodIndex.EMPTY_P, "empty?").isTrue()) {
return self.getRuntime().getNil();
}
return self.toString().indexOf('\0') != -1 ? self.getRuntime().getTrue() : self.getRuntime().getFalse();
}
private static JRubyRepresenter into(IRubyObject arg) {
IRubyObject jobj = arg.getInstanceVariables().fastGetInstanceVariable("@java_object");
if(jobj != null) {
return (JRubyRepresenter)(((org.jruby.javasupport.JavaObject)jobj).getValue());
}
return null;
}
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject string_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
Ruby rt = self.getRuntime();
if(self.callMethod(context, "is_binary_data?").isTrue()) {
return RuntimeHelpers.invoke(context, arg, "scalar", rt.newString("tag:yaml.org,2002:binary"), rt.newArray(self).callMethod(context, "pack", rt.newString("m")), rt.newString("|"));
}
if(((List)self.callMethod(context, "to_yaml_properties")).isEmpty()) {
JRubyRepresenter rep = into(arg);
if(rep != null) {
try {
return JavaUtil.convertJavaToRuby(rt,rep.scalar(self.callMethod(context, "taguri").toString(),self.convertToString().getByteList(),self.toString().startsWith(":") ? "\"" : self.callMethod(context, "to_yaml_style").toString()));
} catch(IOException e) {
throw rt.newIOErrorFromException(e);
}
} else {
return RuntimeHelpers.invoke(context, arg, "scalar", self.callMethod(context, "taguri"), self, self.toString().startsWith(":") ? rt.newString("\"") : self.callMethod(context, "to_yaml_style"));
}
}
Map mep = (Map)(new RubyHash(self.getRuntime()));
mep.put(self.getRuntime().newString("str"),rt.newString(self.toString()));
for(Iterator iter = ((RubyArray)self.callMethod(context, "to_yaml_properties")).getList().iterator(); iter.hasNext();) {
String m = iter.next().toString();
mep.put(self.getRuntime().newString(m), self.callMethod(context,"instance_variable_get", self.getRuntime().newString(m)));
}
return RuntimeHelpers.invoke(context, arg, "map", self.callMethod(context, "taguri"), (IRubyObject)mep, self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="Symbol")
public static class YAMLSymbolMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject symbol_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
return RuntimeHelpers.invoke(context, arg, "scalar", self.callMethod(context, "taguri"), self.callMethod(context, "inspect"), self.callMethod(context, "to_yaml_style"));
}
@JRubyMethod(name = "taguri")
public static IRubyObject symbol_taguri(IRubyObject self) {
return self.getRuntime().newString("tag:yaml.org,2002:str");
}
}
@JRubyClass(name="Numeric")
public static class YAMLNumericMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject numeric_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
String val = self.toString();
if("Infinity".equals(val)) {
val = ".Inf";
} else if("-Infinity".equals(val)) {
val = "-.Inf";
} else if("NaN".equals(val)) {
val = ".NaN";
}
return RuntimeHelpers.invoke(context, arg,"scalar", self.callMethod(context, "taguri"), self.getRuntime().newString(val), self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="Range")
public static class YAMLRangeMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject range_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
Map mep = (Map)(new RubyHash(self.getRuntime()));
mep.put(self.getRuntime().newString("begin"),self.callMethod(context, "begin"));
mep.put(self.getRuntime().newString("end"),self.callMethod(context, "end"));
mep.put(self.getRuntime().newString("excl"),self.callMethod(context, "exclude_end?"));
for(Iterator iter = ((RubyArray)self.callMethod(context, "to_yaml_properties")).getList().iterator(); iter.hasNext();) {
String m = iter.next().toString();
mep.put(self.getRuntime().newString(m.substring(1)), self.callMethod(context,"instance_variable_get", self.getRuntime().newString(m)));
}
return RuntimeHelpers.invoke(context, arg, "map", self.callMethod(context, "taguri"), (IRubyObject)mep, self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="Regexp")
public static class YAMLRegexpMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject regexp_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
return RuntimeHelpers.invoke(context, arg, "scalar", self.callMethod(context, "taguri"), self.callMethod(context, "inspect"), self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="Time")
public static class YAMLTimeMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject time_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
IRubyObject tz = self.getRuntime().newString("Z");
IRubyObject difference_sign = self.getRuntime().newString("-");
self = self.dup();
if(!self.callMethod(context, "utc?").isTrue()) {
IRubyObject utc_same_instant = self.callMethod(context, "utc");
IRubyObject utc_same_writing = RuntimeHelpers.invoke(context, self.getRuntime().getTime(), "utc", new IRubyObject[]{
self.callMethod(context, "year"),self.callMethod(context, "month"),self.callMethod(context, "day"),self.callMethod(context, "hour"),
self.callMethod(context, "min"),self.callMethod(context, "sec"),self.callMethod(context, "usec")});
IRubyObject difference_to_utc = utc_same_writing.callMethod(context,MethodIndex.OP_MINUS, "-", utc_same_instant);
IRubyObject absolute_difference;
if(difference_to_utc.callMethod(context,MethodIndex.OP_LT, "<", RubyFixnum.zero(self.getRuntime())).isTrue()) {
difference_sign = self.getRuntime().newString("-");
absolute_difference = RubyFixnum.zero(self.getRuntime()).callMethod(context,MethodIndex.OP_MINUS, "-", difference_to_utc);
} else {
difference_sign = self.getRuntime().newString("+");
absolute_difference = difference_to_utc;
}
IRubyObject difference_minutes = absolute_difference.callMethod(context,"/", self.getRuntime().newFixnum(60)).callMethod(context, "round");
tz = self.getRuntime().newString("%s%02d:%02d").callMethod(context,"%", self.getRuntime().newArrayNoCopy(new IRubyObject[]{difference_sign,difference_minutes.callMethod(context,"/", self.getRuntime().newFixnum(60)),difference_minutes.callMethod(context,"%", self.getRuntime().newFixnum(60))}));
}
IRubyObject standard = self.callMethod(context,"strftime", self.getRuntime().newString("%Y-%m-%d %H:%M:%S"));
if(self.callMethod(context, "usec").callMethod(context, "nonzero?").isTrue()) {
standard = standard.callMethod(context, MethodIndex.OP_PLUS, "+", self.getRuntime().newString(".%06d").callMethod(context,"%", self.getRuntime().newArray(self.callMethod(context, "usec"))));
}
standard = standard.callMethod(context,MethodIndex.OP_PLUS, "+", self.getRuntime().newString(" %s").callMethod(context,"%", self.getRuntime().newArray(tz)));
return RuntimeHelpers.invoke(context, arg, "scalar", self.callMethod(context, "taguri"), standard, self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="Date")
public static class YAMLDateMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject date_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
return RuntimeHelpers.invoke(context, arg, "scalar", self.callMethod(context, "taguri"), self.callMethod(context, MethodIndex.TO_S, "to_s"), self.callMethod(context, "to_yaml_style"));
}
}
@JRubyClass(name="TrueClass")
public static class YAMLTrueMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject true_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
return RuntimeHelpers.invoke(context, arg, "scalar", self.callMethod(context, "taguri"), self.callMethod(context, MethodIndex.TO_S, "to_s"), self.callMethod(context, "to_yaml_style"));
}
@JRubyMethod(name = "taguri")
public static IRubyObject true_taguri(IRubyObject self) {
return self.getRuntime().newString("tag:yaml.org,2002:bool");
}
}
@JRubyClass(name="FalseClass")
public static class YAMLFalseMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject false_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
return RuntimeHelpers.invoke(context, arg, "scalar", self.callMethod(context, "taguri"), self.callMethod(context, MethodIndex.TO_S, "to_s"), self.callMethod(context, "to_yaml_style"));
}
@JRubyMethod(name = "taguri")
public static IRubyObject false_taguri(IRubyObject self) {
return self.getRuntime().newString("tag:yaml.org,2002:bool");
}
}
@JRubyClass(name="NilClass")
public static class YAMLNilMethods {
@JRubyMethod(name = "to_yaml_node", required = 1)
public static IRubyObject nil_to_yaml_node(IRubyObject self, IRubyObject arg) {
ThreadContext context = self.getRuntime().getCurrentContext();
return RuntimeHelpers.invoke(context, arg,"scalar", self.callMethod(context, "taguri"), self.getRuntime().newString(""), self.callMethod(context, "to_yaml_style"));
}
}
}// RubyYAML
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.InputStream;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.jruby.anno.FrameField;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyModule;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.IOInputStream;
import org.jruby.util.IOOutputStream;
import org.jruby.util.CRC32Ext;
import org.jruby.util.Adler32Ext;
import org.jruby.util.ZlibInflate;
import org.jruby.util.ZlibDeflate;
import org.jruby.util.ByteList;
@JRubyModule(name="Zlib")
public class RubyZlib {
/** Create the Zlib module and add it to the Ruby runtime.
*
*/
public static RubyModule createZlibModule(Ruby runtime) {
RubyModule result = runtime.defineModule("Zlib");
RubyClass gzfile = result.defineClassUnder("GzipFile", runtime.getObject(), RubyGzipFile.GZIPFILE_ALLOCATOR);
gzfile.defineAnnotatedMethods(RubyGzipFile.class);
RubyClass gzreader = result.defineClassUnder("GzipReader", gzfile, RubyGzipReader.GZIPREADER_ALLOCATOR);
gzreader.includeModule(runtime.getEnumerable());
gzreader.defineAnnotatedMethods(RubyGzipReader.class);
RubyClass standardError = runtime.getStandardError();
RubyClass zlibError = result.defineClassUnder("Error", standardError, standardError.getAllocator());
gzreader.defineClassUnder("Error", zlibError, zlibError.getAllocator());
RubyClass gzwriter = result.defineClassUnder("GzipWriter", gzfile, RubyGzipWriter.GZIPWRITER_ALLOCATOR);
gzwriter.defineAnnotatedMethods(RubyGzipWriter.class);
result.defineConstant("ZLIB_VERSION",runtime.newString("1.2.1"));
result.defineConstant("VERSION",runtime.newString("0.6.0"));
result.defineConstant("BINARY",runtime.newFixnum(0));
result.defineConstant("ASCII",runtime.newFixnum(1));
result.defineConstant("UNKNOWN",runtime.newFixnum(2));
result.defineConstant("DEF_MEM_LEVEL",runtime.newFixnum(8));
result.defineConstant("MAX_MEM_LEVEL",runtime.newFixnum(9));
result.defineConstant("OS_UNIX",runtime.newFixnum(3));
result.defineConstant("OS_UNKNOWN",runtime.newFixnum(255));
result.defineConstant("OS_CODE",runtime.newFixnum(11));
result.defineConstant("OS_ZSYSTEM",runtime.newFixnum(8));
result.defineConstant("OS_VMCMS",runtime.newFixnum(4));
result.defineConstant("OS_VMS",runtime.newFixnum(2));
result.defineConstant("OS_RISCOS",runtime.newFixnum(13));
result.defineConstant("OS_MACOS",runtime.newFixnum(7));
result.defineConstant("OS_OS2",runtime.newFixnum(6));
result.defineConstant("OS_AMIGA",runtime.newFixnum(1));
result.defineConstant("OS_QDOS",runtime.newFixnum(12));
result.defineConstant("OS_WIN32",runtime.newFixnum(11));
result.defineConstant("OS_ATARI",runtime.newFixnum(5));
result.defineConstant("OS_MSDOS",runtime.newFixnum(0));
result.defineConstant("OS_CPM",runtime.newFixnum(9));
result.defineConstant("OS_TOPS20",runtime.newFixnum(10));
result.defineConstant("DEFAULT_STRATEGY",runtime.newFixnum(0));
result.defineConstant("FILTERED",runtime.newFixnum(1));
result.defineConstant("HUFFMAN_ONLY",runtime.newFixnum(2));
result.defineConstant("NO_FLUSH",runtime.newFixnum(0));
result.defineConstant("SYNC_FLUSH",runtime.newFixnum(2));
result.defineConstant("FULL_FLUSH",runtime.newFixnum(3));
result.defineConstant("FINISH",runtime.newFixnum(4));
result.defineConstant("NO_COMPRESSION",runtime.newFixnum(0));
result.defineConstant("BEST_SPEED",runtime.newFixnum(1));
result.defineConstant("DEFAULT_COMPRESSION",runtime.newFixnum(-1));
result.defineConstant("BEST_COMPRESSION",runtime.newFixnum(9));
result.defineConstant("MAX_WBITS",runtime.newFixnum(15));
result.defineAnnotatedMethods(RubyZlib.class);
result.defineClassUnder("StreamEnd",zlibError, zlibError.getAllocator());
result.defineClassUnder("StreamError",zlibError, zlibError.getAllocator());
result.defineClassUnder("BufError",zlibError, zlibError.getAllocator());
result.defineClassUnder("NeedDict",zlibError, zlibError.getAllocator());
result.defineClassUnder("MemError",zlibError, zlibError.getAllocator());
result.defineClassUnder("VersionError",zlibError, zlibError.getAllocator());
result.defineClassUnder("DataError",zlibError, zlibError.getAllocator());
RubyClass gzError = gzfile.defineClassUnder("Error",zlibError, zlibError.getAllocator());
gzfile.defineClassUnder("CRCError",gzError, gzError.getAllocator());
gzfile.defineClassUnder("NoFooter",gzError, gzError.getAllocator());
gzfile.defineClassUnder("LengthError",gzError, gzError.getAllocator());
// ZStream actually *isn't* allocatable
RubyClass zstream = result.defineClassUnder("ZStream", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
zstream.defineAnnotatedMethods(ZStream.class);
zstream.undefineMethod("new");
RubyClass infl = result.defineClassUnder("Inflate", zstream, Inflate.INFLATE_ALLOCATOR);
infl.defineAnnotatedMethods(Inflate.class);
RubyClass defl = result.defineClassUnder("Deflate", zstream, Deflate.DEFLATE_ALLOCATOR);
defl.defineAnnotatedMethods(Deflate.class);
runtime.getKernel().callMethod(runtime.getCurrentContext(),"require",runtime.newString("stringio"));
return result;
}
@JRubyClass(name="Zlib::Error", parent="StandardError")
public static class Error {}
@JRubyClass(name="Zlib::StreamEnd", parent="Zlib::Error")
public static class StreamEnd extends Error {}
@JRubyClass(name="Zlib::StreamError", parent="Zlib::Error")
public static class StreamError extends Error {}
@JRubyClass(name="Zlib::BufError", parent="Zlib::Error")
public static class BufError extends Error {}
@JRubyClass(name="Zlib::NeedDict", parent="Zlib::Error")
public static class NeedDict extends Error {}
@JRubyClass(name="Zlib::MemError", parent="Zlib::Error")
public static class MemError extends Error {}
@JRubyClass(name="Zlib::VersionError", parent="Zlib::Error")
public static class VersionError extends Error {}
@JRubyClass(name="Zlib::DataError", parent="Zlib::Error")
public static class DataError extends Error {}
@JRubyMethod(name = "zlib_version", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject zlib_version(IRubyObject recv) {
return ((RubyModule)recv).fastGetConstant("ZLIB_VERSION");
}
@JRubyMethod(name = "version", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject version(IRubyObject recv) {
return ((RubyModule)recv).fastGetConstant("VERSION");
}
@JRubyMethod(name = "crc32", optional = 2, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject crc32(IRubyObject recv, IRubyObject[] args) throws Exception {
args = Arity.scanArgs(recv.getRuntime(),args,0,2);
long crc = 0;
ByteList bytes = null;
if (!args[0].isNil()) bytes = args[0].convertToString().getByteList();
if (!args[1].isNil()) crc = RubyNumeric.num2long(args[1]);
CRC32Ext ext = new CRC32Ext((int)crc);
if (bytes != null) {
ext.update(bytes.unsafeBytes(), bytes.begin(), bytes.length());
}
return recv.getRuntime().newFixnum(ext.getValue());
}
@JRubyMethod(name = "adler32", optional = 2, module = true, visibility = Visibility.PRIVATE)
public static IRubyObject adler32(IRubyObject recv, IRubyObject[] args) throws Exception {
args = Arity.scanArgs(recv.getRuntime(),args,0,2);
int adler = 1;
ByteList bytes = null;
if (!args[0].isNil()) bytes = args[0].convertToString().getByteList();
if (!args[1].isNil()) adler = RubyNumeric.fix2int(args[1]);
Adler32Ext ext = new Adler32Ext(adler);
if (bytes != null) {
ext.update(bytes.unsafeBytes(), bytes.begin(), bytes.length()); // it's safe since adler.update doesn't modify the array
}
return recv.getRuntime().newFixnum(ext.getValue());
}
private final static long[] crctab = new long[]{
0L, 1996959894L, 3993919788L, 2567524794L, 124634137L, 1886057615L, 3915621685L, 2657392035L, 249268274L, 2044508324L, 3772115230L, 2547177864L, 162941995L,
2125561021L, 3887607047L, 2428444049L, 498536548L, 1789927666L, 4089016648L, 2227061214L, 450548861L, 1843258603L, 4107580753L, 2211677639L, 325883990L,
1684777152L, 4251122042L, 2321926636L, 335633487L, 1661365465L, 4195302755L, 2366115317L, 997073096L, 1281953886L, 3579855332L, 2724688242L, 1006888145L,
1258607687L, 3524101629L, 2768942443L, 901097722L, 1119000684L, 3686517206L, 2898065728L, 853044451L, 1172266101L, 3705015759L, 2882616665L, 651767980L,
1373503546L, 3369554304L, 3218104598L, 565507253L, 1454621731L, 3485111705L, 3099436303L, 671266974L, 1594198024L, 3322730930L, 2970347812L, 795835527L,
1483230225L, 3244367275L, 3060149565L, 1994146192L, 31158534L, 2563907772L, 4023717930L, 1907459465L, 112637215L, 2680153253L, 3904427059L, 2013776290L,
251722036L, 2517215374L, 3775830040L, 2137656763L, 141376813L, 2439277719L, 3865271297L, 1802195444L, 476864866L, 2238001368L, 4066508878L, 1812370925L,
453092731L, 2181625025L, 4111451223L, 1706088902L, 314042704L, 2344532202L, 4240017532L, 1658658271L, 366619977L, 2362670323L, 4224994405L, 1303535960L,
984961486L, 2747007092L, 3569037538L, 1256170817L, 1037604311L, 2765210733L, 3554079995L, 1131014506L, 879679996L, 2909243462L, 3663771856L, 1141124467L,
855842277L, 2852801631L, 3708648649L, 1342533948L, 654459306L, 3188396048L, 3373015174L, 1466479909L, 544179635L, 3110523913L, 3462522015L, 1591671054L,
702138776L, 2966460450L, 3352799412L, 1504918807L, 783551873L, 3082640443L, 3233442989L, 3988292384L, 2596254646L, 62317068L, 1957810842L, 3939845945L,
2647816111L, 81470997L, 1943803523L, 3814918930L, 2489596804L, 225274430L, 2053790376L, 3826175755L, 2466906013L, 167816743L, 2097651377L, 4027552580L,
2265490386L, 503444072L, 1762050814L, 4150417245L, 2154129355L, 426522225L, 1852507879L, 4275313526L, 2312317920L, 282753626L, 1742555852L, 4189708143L,
2394877945L, 397917763L, 1622183637L, 3604390888L, 2714866558L, 953729732L, 1340076626L, 3518719985L, 2797360999L, 1068828381L, 1219638859L, 3624741850L,
2936675148L, 906185462L, 1090812512L, 3747672003L, 2825379669L, 829329135L, 1181335161L, 3412177804L, 3160834842L, 628085408L, 1382605366L, 3423369109L,
3138078467L, 570562233L, 1426400815L, 3317316542L, 2998733608L, 733239954L, 1555261956L, 3268935591L, 3050360625L, 752459403L, 1541320221L, 2607071920L,
3965973030L, 1969922972L, 40735498L, 2617837225L, 3943577151L, 1913087877L, 83908371L, 2512341634L, 3803740692L, 2075208622L, 213261112L, 2463272603L,
3855990285L, 2094854071L, 198958881L, 2262029012L, 4057260610L, 1759359992L, 534414190L, 2176718541L, 4139329115L, 1873836001L, 414664567L, 2282248934L,
4279200368L, 1711684554L, 285281116L, 2405801727L, 4167216745L, 1634467795L, 376229701L, 2685067896L, 3608007406L, 1308918612L, 956543938L, 2808555105L,
3495958263L, 1231636301L, 1047427035L, 2932959818L, 3654703836L, 1088359270L, 936918000L, 2847714899L, 3736837829L, 1202900863L, 817233897L, 3183342108L,
3401237130L, 1404277552L, 615818150L, 3134207493L, 3453421203L, 1423857449L, 601450431L, 3009837614L, 3294710456L, 1567103746L, 711928724L, 3020668471L,
3272380065L, 1510334235L, 755167117};
@JRubyMethod(name = "crc_table", module = true, visibility = Visibility.PRIVATE)
public static IRubyObject crc_table(IRubyObject recv) {
List<IRubyObject> ll = new ArrayList<IRubyObject>(crctab.length);
for(int i=0;i<crctab.length;i++) {
ll.add(recv.getRuntime().newFixnum(crctab[i]));
}
return recv.getRuntime().newArray(ll);
}
@JRubyClass(name="Zlib::ZStream")
public static abstract class ZStream extends RubyObject {
protected boolean closed = false;
protected boolean ended = false;
protected boolean finished = false;
protected abstract int internalTotalOut();
protected abstract boolean internalStreamEndP();
protected abstract void internalEnd();
protected abstract void internalReset();
protected abstract int internalAdler();
protected abstract IRubyObject internalFinish() throws Exception;
protected abstract int internalTotalIn();
protected abstract void internalClose();
public ZStream(Ruby runtime, RubyClass type) {
super(runtime, type);
}
@JRubyMethod(name = "initialize", frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(Block unusedBlock) {
return this;
}
@JRubyMethod(name = "flust_next_out")
public IRubyObject flush_next_out() {
return getRuntime().getNil();
}
@JRubyMethod(name = "total_out")
public IRubyObject total_out() {
return getRuntime().newFixnum(internalTotalOut());
}
@JRubyMethod(name = "stream_end?")
public IRubyObject stream_end_p() {
return internalStreamEndP() ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "data_type")
public IRubyObject data_type() {
return getRuntime().fastGetModule("Zlib").fastGetConstant("UNKNOWN");
}
@JRubyMethod(name = "closed?")
public IRubyObject closed_p() {
return closed ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "ended?")
public IRubyObject ended_p() {
return ended ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "end")
public IRubyObject end() {
if(!ended) {
internalEnd();
ended = true;
}
return getRuntime().getNil();
}
@JRubyMethod(name = "reset")
public IRubyObject reset() {
internalReset();
return getRuntime().getNil();
}
@JRubyMethod(name = "avail_out")
public IRubyObject avail_out() {
return RubyFixnum.zero(getRuntime());
}
@JRubyMethod(name = "avail_out=", required = 1)
public IRubyObject set_avail_out(IRubyObject p1) {
return p1;
}
@JRubyMethod(name = "adler")
public IRubyObject adler() {
return getRuntime().newFixnum(internalAdler());
}
@JRubyMethod(name = "finish")
public IRubyObject finish() throws Exception {
if(!finished) {
finished = true;
return internalFinish();
}
return RubyString.newEmptyString(getRuntime());
}
@JRubyMethod(name = "avail_in")
public IRubyObject avail_in() {
return RubyFixnum.zero(getRuntime());
}
@JRubyMethod(name = "flush_next_in")
public IRubyObject flush_next_in() {
return getRuntime().getNil();
}
@JRubyMethod(name = "total_in")
public IRubyObject total_in() {
return getRuntime().newFixnum(internalTotalIn());
}
@JRubyMethod(name = "finished?")
public IRubyObject finished_p() {
return finished ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "close")
public IRubyObject close() {
if(!closed) {
internalClose();
closed = true;
}
return getRuntime().getNil();
}
}
@JRubyClass(name="Zlib::Inflate", parent="Zlib::ZStream")
public static class Inflate extends ZStream {
protected static final ObjectAllocator INFLATE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new Inflate(runtime, klass);
}
};
@JRubyMethod(name = "inflate", required = 1, meta = true)
public static IRubyObject s_inflate(IRubyObject recv, IRubyObject string) throws Exception {
return ZlibInflate.s_inflate(recv,string.convertToString().getByteList());
}
public Inflate(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private ZlibInflate infl;
@JRubyMethod(name = "initialize", rest = true, visibility = Visibility.PRIVATE)
public IRubyObject _initialize(IRubyObject[] args) throws Exception {
infl = new ZlibInflate(this);
return this;
}
@JRubyMethod(name = "<<", required = 1)
public IRubyObject append(IRubyObject arg) {
infl.append(arg);
return this;
}
@JRubyMethod(name = "sync_point?")
public IRubyObject sync_point_p() {
return infl.sync_point();
}
@JRubyMethod(name = "set_dictionary", required = 1)
public IRubyObject set_dictionary(IRubyObject arg) throws Exception {
return infl.set_dictionary(arg);
}
@JRubyMethod(name = "inflate", required = 1)
public IRubyObject inflate(IRubyObject string) throws Exception {
return infl.inflate(string.convertToString().getByteList());
}
@JRubyMethod(name = "sync", required = 1)
public IRubyObject sync(IRubyObject string) {
return infl.sync(string);
}
protected int internalTotalOut() {
return infl.getInflater().getTotalOut();
}
protected boolean internalStreamEndP() {
return infl.getInflater().finished();
}
protected void internalEnd() {
infl.getInflater().end();
}
protected void internalReset() {
infl.getInflater().reset();
}
protected int internalAdler() {
return infl.getInflater().getAdler();
}
protected IRubyObject internalFinish() throws Exception {
infl.finish();
return getRuntime().getNil();
}
public IRubyObject finished_p() {
return infl.getInflater().finished() ? getRuntime().getTrue() : getRuntime().getFalse();
}
protected int internalTotalIn() {
return infl.getInflater().getTotalIn();
}
protected void internalClose() {
infl.close();
}
}
@JRubyClass(name="Zlib::Deflate", parent="Zlib::ZStream")
public static class Deflate extends ZStream {
protected static final ObjectAllocator DEFLATE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new Deflate(runtime, klass);
}
};
@JRubyMethod(name = "deflate", required = 1, optional = 1, meta = true)
public static IRubyObject s_deflate(IRubyObject recv, IRubyObject[] args) throws Exception {
args = Arity.scanArgs(recv.getRuntime(),args,1,1);
int level = -1;
if(!args[1].isNil()) {
level = RubyNumeric.fix2int(args[1]);
}
return ZlibDeflate.s_deflate(recv,args[0].convertToString().getByteList(),level);
}
public Deflate(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private ZlibDeflate defl;
@JRubyMethod(name = "initialize", optional = 4, visibility = Visibility.PRIVATE)
public IRubyObject _initialize(IRubyObject[] args) throws Exception {
args = Arity.scanArgs(getRuntime(),args,0,4);
int level = -1;
int window_bits = 15;
int memlevel = 8;
int strategy = 0;
if(!args[0].isNil()) {
level = RubyNumeric.fix2int(args[0]);
}
if(!args[1].isNil()) {
window_bits = RubyNumeric.fix2int(args[1]);
}
if(!args[2].isNil()) {
memlevel = RubyNumeric.fix2int(args[2]);
}
if(!args[3].isNil()) {
strategy = RubyNumeric.fix2int(args[3]);
}
defl = new ZlibDeflate(this,level,window_bits,memlevel,strategy);
return this;
}
@JRubyMethod(name = "<<", required = 1)
public IRubyObject append(IRubyObject arg) throws Exception {
defl.append(arg);
return this;
}
@JRubyMethod(name = "params", required = 2)
public IRubyObject params(IRubyObject level, IRubyObject strategy) {
defl.params(RubyNumeric.fix2int(level),RubyNumeric.fix2int(strategy));
return getRuntime().getNil();
}
@JRubyMethod(name = "set_dictionary", required = 1)
public IRubyObject set_dictionary(IRubyObject arg) throws Exception {
return defl.set_dictionary(arg);
}
@JRubyMethod(name = "flush", optional = 1)
public IRubyObject flush(IRubyObject[] args) throws Exception {
int flush = 2; // SYNC_FLUSH
if(args.length == 1) {
if(!args[0].isNil()) {
flush = RubyNumeric.fix2int(args[0]);
}
}
return defl.flush(flush);
}
@JRubyMethod(name = "deflate", required = 1, optional = 1)
public IRubyObject deflate(IRubyObject[] args) throws Exception {
args = Arity.scanArgs(getRuntime(),args,1,1);
int flush = 0; // NO_FLUSH
if(!args[1].isNil()) {
flush = RubyNumeric.fix2int(args[1]);
}
return defl.deflate(args[0].convertToString().getByteList(),flush);
}
protected int internalTotalOut() {
return defl.getDeflater().getTotalOut();
}
protected boolean internalStreamEndP() {
return defl.getDeflater().finished();
}
protected void internalEnd() {
defl.getDeflater().end();
}
protected void internalReset() {
defl.getDeflater().reset();
}
protected int internalAdler() {
return defl.getDeflater().getAdler();
}
protected IRubyObject internalFinish() throws Exception {
return defl.finish();
}
protected int internalTotalIn() {
return defl.getDeflater().getTotalIn();
}
protected void internalClose() {
defl.close();
}
}
@JRubyClass(name="Zlib::GzipFile")
public static class RubyGzipFile extends RubyObject {
@JRubyClass(name="Zlib::GzipFile::Error", parent="Zlib::Error")
public static class Error {}
@JRubyClass(name="Zlib::GzipFile::CRCError", parent="Zlib::GzipFile::Error")
public static class CRCError extends Error {}
@JRubyClass(name="Zlib::GzipFile::NoFooter", parent="Zlib::GzipFile::Error")
public static class NoFooter extends Error {}
@JRubyClass(name="Zlib::GzipFile::LengthError", parent="Zlib::GzipFile::Error")
public static class LengthError extends Error {}
private static IRubyObject wrap(ThreadContext context, RubyGzipFile instance,
IRubyObject io, Block block) throws IOException {
if (block.isGiven()) {
try {
block.yield(context, instance);
return instance.getRuntime().getNil();
} finally {
if (!instance.isClosed()) instance.close();
}
}
return io;
}
@JRubyMethod(name = "wrap", required = 1, frame = true, meta = true)
public static IRubyObject wrap(ThreadContext context, IRubyObject recv, IRubyObject io, Block block) throws IOException {
Ruby runtime = recv.getRuntime();
RubyGzipFile instance;
// TODO: People extending GzipWriter/reader will break. Find better way here.
if (recv == runtime.getModule("Zlib").getClass("GzipWriter")) {
instance = RubyGzipWriter.newGzipWriter(recv, new IRubyObject[] { io }, block);
} else {
instance = RubyGzipReader.newInstance(recv, new IRubyObject[] { io }, block);
}
return wrap(context, instance, io, block);
}
protected static final ObjectAllocator GZIPFILE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyGzipFile(runtime, klass);
}
};
@JRubyMethod(name = "new", frame = true, meta = true)
public static RubyGzipFile newInstance(IRubyObject recv, Block block) {
RubyClass klass = (RubyClass)recv;
RubyGzipFile result = (RubyGzipFile) klass.allocate();
result.callInit(new IRubyObject[0], block);
return result;
}
protected boolean closed = false;
protected boolean finished = false;
private int os_code = 255;
private int level = -1;
private String orig_name;
private String comment;
protected IRubyObject realIo;
private IRubyObject mtime;
public RubyGzipFile(Ruby runtime, RubyClass type) {
super(runtime, type);
mtime = runtime.getNil();
}
@JRubyMethod(name = "os_code")
public IRubyObject os_code() {
return getRuntime().newFixnum(os_code);
}
@JRubyMethod(name = "closed?")
public IRubyObject closed_p() {
return closed ? getRuntime().getTrue() : getRuntime().getFalse();
}
protected boolean isClosed() {
return closed;
}
@JRubyMethod(name = "orig_name")
public IRubyObject orig_name() {
return orig_name == null ? getRuntime().getNil() : getRuntime().newString(orig_name);
}
@JRubyMethod(name = "to_io")
public IRubyObject to_io() {
return realIo;
}
@JRubyMethod(name = "comment")
public IRubyObject comment() {
return comment == null ? getRuntime().getNil() : getRuntime().newString(comment);
}
@JRubyMethod(name = "crc")
public IRubyObject crc() {
return RubyFixnum.zero(getRuntime());
}
@JRubyMethod(name = "mtime")
public IRubyObject mtime() {
return mtime;
}
@JRubyMethod(name = "sync")
public IRubyObject sync() {
return getRuntime().getNil();
}
@JRubyMethod(name = "finish")
public IRubyObject finish() throws IOException {
if (!finished) {
//io.finish();
}
finished = true;
return realIo;
}
@JRubyMethod(name = "close")
public IRubyObject close() throws IOException {
return null;
}
@JRubyMethod(name = "level")
public IRubyObject level() {
return getRuntime().newFixnum(level);
}
@JRubyMethod(name = "sync=", required = 1)
public IRubyObject set_sync(IRubyObject ignored) {
return getRuntime().getNil();
}
}
@JRubyClass(name="Zlib::GzipReader", parent="Zlib::GzipFile", include="Enumerable")
public static class RubyGzipReader extends RubyGzipFile {
@JRubyClass(name="Zlib::GzipReader::Error", parent="Zlib::GzipReader")
public static class Error {}
protected static final ObjectAllocator GZIPREADER_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyGzipReader(runtime, klass);
}
};
@JRubyMethod(name = "new", rest = true, frame = true, meta = true)
public static RubyGzipReader newInstance(IRubyObject recv, IRubyObject[] args, Block block) {
RubyClass klass = (RubyClass)recv;
RubyGzipReader result = (RubyGzipReader)klass.allocate();
result.callInit(args, block);
return result;
}
@JRubyMethod(name = "open", required = 1, frame = true, meta = true)
public static IRubyObject open(final ThreadContext context, IRubyObject recv, IRubyObject filename, Block block) throws IOException {
Ruby runtime = recv.getRuntime();
IRubyObject io = RuntimeHelpers.invoke(context, runtime.getFile(), "open", filename, runtime.newString("rb"));
RubyGzipFile instance = newInstance(recv, new IRubyObject[]{io}, Block.NULL_BLOCK);
return RubyGzipFile.wrap(context, instance, io, block);
}
public RubyGzipReader(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private int line;
private InputStream io;
@JRubyMethod(name = "initialize", required = 1, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(IRubyObject io, Block unusedBlock) {
realIo = io;
try {
this.io = new GZIPInputStream(new IOInputStream(io));
} catch (IOException e) {
Ruby runtime = io.getRuntime();
RubyClass errorClass = runtime.fastGetModule("Zlib").fastGetClass("GzipReader").fastGetClass("Error");
throw new RaiseException(RubyException.newException(runtime, errorClass, e.getMessage()));
}
line = 1;
return this;
}
@JRubyMethod(name = "rewind")
public IRubyObject rewind() {
return getRuntime().getNil();
}
@JRubyMethod(name = "lineno")
public IRubyObject lineno() {
return getRuntime().newFixnum(line);
}
@JRubyMethod(name = "readline", writes = FrameField.LASTLINE)
public IRubyObject readline(ThreadContext context) throws IOException {
IRubyObject dst = gets(context, new IRubyObject[0]);
if (dst.isNil()) {
throw getRuntime().newEOFError();
}
return dst;
}
public IRubyObject internalGets(IRubyObject[] args) throws IOException {
ByteList sep = ((RubyString)getRuntime().getGlobalVariables().get("$/")).getByteList();
if (args.length > 0) {
sep = args[0].convertToString().getByteList();
}
return internalSepGets(sep);
}
private IRubyObject internalSepGets(ByteList sep) throws IOException {
ByteList result = new ByteList();
int ce = io.read();
while (ce != -1 && sep.indexOf(ce) == -1) {
result.append((byte)ce);
ce = io.read();
}
line++;
result.append(sep);
return RubyString.newString(getRuntime(),result);
}
@JRubyMethod(name = "gets", optional = 1, writes = FrameField.LASTLINE)
public IRubyObject gets(ThreadContext context, IRubyObject[] args) throws IOException {
IRubyObject result = internalGets(args);
if (!result.isNil()) {
context.getCurrentFrame().setLastLine(result);
}
return result;
}
private final static int BUFF_SIZE = 4096;
@JRubyMethod(name = "read", optional = 1)
public IRubyObject read(IRubyObject[] args) throws IOException {
if (args.length == 0 || args[0].isNil()) {
ByteList val = new ByteList(10);
byte[] buffer = new byte[BUFF_SIZE];
int read = io.read(buffer);
while (read != -1) {
val.append(buffer,0,read);
read = io.read(buffer);
}
return RubyString.newString(getRuntime(),val);
}
int len = RubyNumeric.fix2int(args[0]);
if (len < 0) {
throw getRuntime().newArgumentError("negative length " + len + " given");
} else if (len > 0) {
byte[] buffer = new byte[len];
int toRead = len;
int offset = 0;
int read = 0;
while (toRead > 0) {
read = io.read(buffer,offset,toRead);
if (read == -1) {
break;
}
toRead -= read;
offset += read;
} // hmm...
return RubyString.newString(getRuntime(),new ByteList(buffer,0,len-toRead,false));
}
return RubyString.newEmptyString(getRuntime());
}
@JRubyMethod(name = "lineno=", required = 1)
public IRubyObject set_lineno(IRubyObject lineArg) {
line = RubyNumeric.fix2int(lineArg);
return lineArg;
}
@JRubyMethod(name = "pos")
public IRubyObject pos() {
return RubyFixnum.zero(getRuntime());
}
@JRubyMethod(name = "readchar")
public IRubyObject readchar() throws IOException {
int value = io.read();
if (value == -1) {
throw getRuntime().newEOFError();
}
return getRuntime().newFixnum(value);
}
@JRubyMethod(name = "getc")
public IRubyObject getc() throws IOException {
int value = io.read();
return value == -1 ? getRuntime().getNil() : getRuntime().newFixnum(value);
}
private boolean isEof() throws IOException {
return ((GZIPInputStream)io).available() != 1;
}
@JRubyMethod(name = "close")
public IRubyObject close() throws IOException {
if (!closed) {
io.close();
}
this.closed = true;
return getRuntime().getNil();
}
@JRubyMethod(name = "eof")
public IRubyObject eof() throws IOException {
return isEof() ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "eof?")
public IRubyObject eof_p() throws IOException {
return eof();
}
@JRubyMethod(name = "unused")
public IRubyObject unused() {
return getRuntime().getNil();
}
@JRubyMethod(name = "tell")
public IRubyObject tell() {
return getRuntime().getNil();
}
@JRubyMethod(name = "each", optional = 1, frame = true)
public IRubyObject each(ThreadContext context, IRubyObject[] args, Block block) throws IOException {
ByteList sep = ((RubyString)getRuntime().getGlobalVariables().get("$/")).getByteList();
if (args.length > 0 && !args[0].isNil()) {
sep = args[0].convertToString().getByteList();
}
while (!isEof()) {
block.yield(context, internalSepGets(sep));
}
return getRuntime().getNil();
}
@JRubyMethod(name = "ungetc", required = 1)
public IRubyObject ungetc(IRubyObject arg) {
return getRuntime().getNil();
}
@JRubyMethod(name = "readlines", optional = 1)
public IRubyObject readlines(IRubyObject[] args) throws IOException {
List<IRubyObject> array = new ArrayList<IRubyObject>();
if (args.length != 0 && args[0].isNil()) {
array.add(read(new IRubyObject[0]));
} else {
ByteList seperator = ((RubyString)getRuntime().getGlobalVariables().get("$/")).getByteList();
if (args.length > 0) {
seperator = args[0].convertToString().getByteList();
}
while (!isEof()) {
array.add(internalSepGets(seperator));
}
}
return getRuntime().newArray(array);
}
@JRubyMethod(name = "each_byte", frame = true)
public IRubyObject each_byte(ThreadContext context, Block block) throws IOException {
int value = io.read();
while (value != -1) {
block.yield(context, getRuntime().newFixnum(value));
value = io.read();
}
return getRuntime().getNil();
}
}
@JRubyClass(name="Zlib::GzipWriter", parent="Zlib::GzipFile")
public static class RubyGzipWriter extends RubyGzipFile {
protected static final ObjectAllocator GZIPWRITER_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyGzipWriter(runtime, klass);
}
};
@JRubyMethod(name = "new", rest = true, frame = true, meta = true)
public static RubyGzipWriter newGzipWriter(IRubyObject recv, IRubyObject[] args, Block block) {
RubyClass klass = (RubyClass)recv;
RubyGzipWriter result = (RubyGzipWriter)klass.allocate();
result.callInit(args, block);
return result;
}
@JRubyMethod(name = "open", required = 1, optional = 2, frame = true, meta = true)
public static IRubyObject open(final ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) throws IOException {
Ruby runtime = recv.getRuntime();
IRubyObject level = runtime.getNil();
IRubyObject strategy = runtime.getNil();
if (args.length > 1) {
level = args[1];
if (args.length > 2) strategy = args[2];
}
IRubyObject io = RuntimeHelpers.invoke(context, runtime.getFile(), "open", args[0], runtime.newString("wb"));
RubyGzipFile instance = newGzipWriter(recv, new IRubyObject[]{io, level, strategy}, Block.NULL_BLOCK);
return RubyGzipFile.wrap(context, instance, io, block);
}
public RubyGzipWriter(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private GZIPOutputStream io;
@JRubyMethod(name = "initialize", required = 1, rest = true, frame = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize2(IRubyObject[] args, Block unusedBlock) throws IOException {
realIo = (RubyObject)args[0];
this.io = new GZIPOutputStream(new IOOutputStream(args[0]));
return this;
}
@JRubyMethod(name = "close")
public IRubyObject close() throws IOException {
if (!closed) {
io.close();
}
this.closed = true;
return getRuntime().getNil();
}
@JRubyMethod(name = "append", required = 1)
public IRubyObject append(IRubyObject p1) throws IOException {
this.write(p1);
return this;
}
@JRubyMethod(name = "printf", required = 1, rest = true)
public IRubyObject printf(ThreadContext context, IRubyObject[] args) throws IOException {
write(RubyKernel.sprintf(context, this, args));
return context.getRuntime().getNil();
}
@JRubyMethod(name = "print", rest = true)
public IRubyObject print(IRubyObject[] args) throws IOException {
if (args.length != 0) {
for (int i = 0, j = args.length; i < j; i++) {
write(args[i]);
}
}
IRubyObject sep = getRuntime().getGlobalVariables().get("$\\");
if (!sep.isNil()) {
write(sep);
}
return getRuntime().getNil();
}
@JRubyMethod(name = "pos")
public IRubyObject pos() {
return getRuntime().getNil();
}
@JRubyMethod(name = "orig_name=", required = 1)
public IRubyObject set_orig_name(IRubyObject ignored) {
return getRuntime().getNil();
}
@JRubyMethod(name = "comment=", required = 1)
public IRubyObject set_comment(IRubyObject ignored) {
return getRuntime().getNil();
}
@JRubyMethod(name = "putc", required = 1)
public IRubyObject putc(IRubyObject p1) throws IOException {
io.write(RubyNumeric.fix2int(p1));
return p1;
}
@JRubyMethod(name = "puts", rest = true)
public IRubyObject puts(ThreadContext context, IRubyObject[] args) throws IOException {
RubyStringIO sio = (RubyStringIO)getRuntime().fastGetClass("StringIO").newInstance(context, new IRubyObject[0], Block.NULL_BLOCK);
sio.puts(context, args);
write(sio.string());
return getRuntime().getNil();
}
public IRubyObject finish() throws IOException {
if (!finished) {
io.finish();
}
finished = true;
return realIo;
}
@JRubyMethod(name = "flush", optional = 1)
public IRubyObject flush(IRubyObject[] args) throws IOException {
if (args.length == 0 || args[0].isNil() || RubyNumeric.fix2int(args[0]) != 0) { // Zlib::NO_FLUSH
io.flush();
}
return getRuntime().getNil();
}
@JRubyMethod(name = "mtime=", required = 1)
public IRubyObject set_mtime(IRubyObject ignored) {
return getRuntime().getNil();
}
@JRubyMethod(name = "tell")
public IRubyObject tell() {
return getRuntime().getNil();
}
@JRubyMethod(name = "write", required = 1)
public IRubyObject write(IRubyObject p1) throws IOException {
ByteList bytes = p1.convertToString().getByteList();
io.write(bytes.unsafeBytes(), bytes.begin(), bytes.length());
return getRuntime().newFixnum(bytes.length());
}
}
}
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callback.Callback;
/**
*
* @author jpetersen
*/
public final class TopSelfFactory {
/**
* Constructor for TopSelfFactory.
*/
private TopSelfFactory() {
super();
}
public static IRubyObject createTopSelf(final Ruby runtime) {
IRubyObject topSelf = new RubyObject(runtime, runtime.getObject());
topSelf.getSingletonClass().defineFastMethod("to_s", new Callback() {
/**
* @see org.jruby.runtime.callback.Callback#execute(IRubyObject, IRubyObject[])
*/
public IRubyObject execute(IRubyObject recv, IRubyObject[] args, Block block) {
return runtime.newString("main");
}
/**
* @see org.jruby.runtime.callback.Callback#getArity()
*/
public Arity getArity() {
return Arity.noArguments();
}
});
// The following three methods must be defined fast, since they expect to modify the current frame
// (i.e. they expect no frame will be allocated for them). JRUBY-1185.
topSelf.getSingletonClass().defineFastPrivateMethod("include", new Callback() {
/**
* @see org.jruby.runtime.callback.Callback#execute(IRubyObject, IRubyObject[])
*/
public IRubyObject execute(IRubyObject recv, IRubyObject[] args, Block block) {
runtime.secure(4);
return runtime.getObject().include(args);
}
/**
* @see org.jruby.runtime.callback.Callback#getArity()
*/
public Arity getArity() {
return Arity.optional();
}
});
topSelf.getSingletonClass().defineFastPrivateMethod("public", new Callback() {
/**
* @see org.jruby.runtime.callback.Callback#execute(IRubyObject, IRubyObject[])
*/
public IRubyObject execute(IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
return runtime.getObject().rbPublic(recv.getRuntime().getCurrentContext(), args);
}
/**
* @see org.jruby.runtime.callback.Callback#getArity()
*/
public Arity getArity() {
return Arity.optional();
}
});
topSelf.getSingletonClass().defineFastPrivateMethod("private", new Callback() {
/**
* @see org.jruby.runtime.callback.Callback#execute(IRubyObject, IRubyObject[])
*/
public IRubyObject execute(IRubyObject recv, IRubyObject[] args, Block unusedBlock) {
return runtime.getObject().rbPrivate(recv.getRuntime().getCurrentContext(), args);
}
/**
* @see org.jruby.runtime.callback.Callback#getArity()
*/
public Arity getArity() {
return Arity.optional();
}
});
return topSelf;
}
}
|