boo-lang /src/Boo.Lang/Runtime/RuntimeServices.cs

Language C# Lines 1802
MD5 Hash 1d13b62431ae7562402e5048336e1cfb Estimated Cost $41,877 (why?)
Repository https://github.com/boo/boo-lang.git View Raw File View Project SPDX
   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
#region license
// Copyright (c) 2004, 2007 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//	 * Redistributions of source code must retain the above copyright notice,
//	 this list of conditions and the following disclaimer.
//	 * Redistributions in binary form must reproduce the above copyright notice,
//	 this list of conditions and the following disclaimer in the documentation
//	 and/or other materials provided with the distribution.
//	 * Neither the name of Rodrigo B. de Oliveira nor the names of its
//	 contributors may be used to endorse or promote products derived from this
//	 software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
using System.IO;
using System.Reflection.Emit;
using System.Text;

namespace Boo.Lang.Runtime
{
	public class RuntimeServices
	{
		private static readonly object[] NoArguments = new object[0];

		private static readonly Type RuntimeServicesType = typeof(RuntimeServices);

		internal const BindingFlags InstanceMemberFlags = BindingFlags.Public |
														 BindingFlags.NonPublic |
														 BindingFlags.Instance;

		internal const BindingFlags DefaultBindingFlags = InstanceMemberFlags |
												BindingFlags.OptionalParamBinding |
												BindingFlags.Static |
												BindingFlags.FlattenHierarchy;

		private const BindingFlags InvokeBindingFlags = DefaultBindingFlags |
												BindingFlags.InvokeMethod;

		private const BindingFlags StaticMemberBindingFlags = BindingFlags.Public |
												BindingFlags.Static |
												BindingFlags.FlattenHierarchy;

		private const BindingFlags InvokeOperatorBindingFlags = StaticMemberBindingFlags |
												BindingFlags.InvokeMethod;

		private const BindingFlags SetPropertyBindingFlags = DefaultBindingFlags |
												BindingFlags.SetProperty |
												BindingFlags.SetField;

		private const BindingFlags GetPropertyBindingFlags = DefaultBindingFlags |
												BindingFlags.GetProperty |
												BindingFlags.GetField;

		private static DispatcherCache _cache = new DispatcherCache();
		private static ExtensionRegistry _extensions = new ExtensionRegistry();

		public delegate void CodeBlock();

		public static void WithExtensions(System.Type extensions, CodeBlock block)
		{
			RegisterExtensions(extensions);
			try
			{
				block();
			}
			finally
			{
				UnRegisterExtensions(extensions);
			}
		}

		public static void RegisterExtensions(System.Type extensions)
		{
			_extensions.Register(extensions);
		}

		public static void UnRegisterExtensions(System.Type extensions)
		{
			_extensions.UnRegister(extensions);
		}

		public static object Invoke(object target, string name, object[] args)
		{	
			return Dispatch(target, name, args, delegate { return CreateMethodDispatcher(target, name, args); });
		}

		private static Dispatcher CreateMethodDispatcher(object target, string name, object[] args)
		{
			IQuackFu duck = target as IQuackFu;
			if (null != duck)
			{
				return delegate(object o, object[] arguments) { return ((IQuackFu) o).QuackInvoke(name, arguments); };
			}

			Type type = target as Type;
			if (null != type)
			{
				// static method
				return DoCreateMethodDispatcher(null, type, name, args);
			}

			Type targetType = target.GetType();
			if (targetType.IsCOMObject)
			{
				// COM methods cant be seen through reflection
				// so maybe the proper way to support parameter conversions
				// is indeed by creating a specific Binder object
				// which knows the boo conversion rules
				return
					delegate(object o, object[] arguments) { return o.GetType().InvokeMember(name, InvokeBindingFlags, null, target, arguments); };
			}
			
			return DoCreateMethodDispatcher(target, targetType, name, args);
		}

		private static Dispatcher DoCreateMethodDispatcher(object target, Type targetType, string name, object[] args)
		{
			return new MethodDispatcherFactory(_extensions, target, targetType, name, args).Create();
		}

		private static object Dispatch(object target, string cacheKeyName, object[] args, DispatcherCache.DispatcherFactory factory)
		{
			Type[] cacheKeyTypes = MethodResolver.GetArgumentTypes(args);
			return Dispatch(target, cacheKeyName, cacheKeyTypes, args, factory);
		}

		private static object Dispatch(object target, string cacheKeyName, Type[] cacheKeyTypes, object[] args, DispatcherCache.DispatcherFactory factory)
		{
			Type targetType = (target as Type) ?? target.GetType();
			DispatcherKey key = new DispatcherKey(targetType, cacheKeyName, cacheKeyTypes);
			Dispatcher dispatcher = _cache.Get(key, factory);
			return dispatcher(target, args);
		}

		public static object GetProperty(object target, string name)
		{
			return Dispatch(target, name, NoArguments, delegate { return CreatePropGetDispatcher(target, name);  });
		}

		private static Dispatcher CreatePropGetDispatcher(object target, string name)
		{
			IQuackFu duck = target as IQuackFu;
			if (null != duck)
			{
				return delegate(object o, object[] args) { return ((IQuackFu)o).QuackGet(name, null); };
			}

			Type type = target as Type;
			if (null != type) return DoCreatePropGetDispatcher(null, type, name);

			Type targetType = target.GetType();
			if (targetType.IsCOMObject)
			{
				return delegate(object o, object[] args)
		       	{
		       		return o.GetType().InvokeMember(name, GetPropertyBindingFlags, null, o, null);
		       	};
			}

			return DoCreatePropGetDispatcher(target, target.GetType(), name);
		}

		private static Dispatcher DoCreatePropGetDispatcher(object target, Type type, string name)
		{
			return new PropertyDispatcherFactory(_extensions, target, type, name).CreateGetter();
		}

		public static object SetProperty(object target, string name, object value)
		{
			return Dispatch(target, name, new object[] { value }, delegate { return CreatePropSetDispatcher(target, name, value); });
		}

		private static Dispatcher CreatePropSetDispatcher(object target, string name, object value)
		{
			IQuackFu duck = target as IQuackFu;
			if (null != duck)
			{
				return delegate(object o, object[] args) { return ((IQuackFu) o).QuackSet(name, null, args[0]); };
			}

			Type type = target as Type;
			if (null != type) return DoCreatePropSetDispatcher(null, type, name, value);

			Type targetType = target.GetType();
			if (targetType.IsCOMObject)
			{
				return delegate(object o, object[] args)
		       	{
		       		return o.GetType().InvokeMember(name,
		       		                                SetPropertyBindingFlags,
		       		                                null,
		       		                                o,
		       		                                args);
		       	};
			}

			return DoCreatePropSetDispatcher(target, targetType, name, value);
		}

		private static Dispatcher DoCreatePropSetDispatcher(object target, Type type, string name, object value)
		{
			return new PropertyDispatcherFactory(_extensions, target, type, name, value).CreateSetter();
		}

		public struct ValueTypeChange
		{
			public object Target;
			public string Member;
			public object Value;

			public ValueTypeChange(object target, string member, object value)
			{
				this.Target = target;
				this.Member = member;
				this.Value = value;
			}
		}

		public static void PropagateValueTypeChanges(ValueTypeChange[] changes)
		{
			foreach (ValueTypeChange change in changes)
			{
				if (!(change.Value is ValueType)) break;
				try
				{
					SetProperty(change.Target, change.Member, change.Value);
				}
				catch (System.MissingFieldException)
				{
					// hit a readonly property
					break;
				}
			}
		}

		[Obsolete("Use Coerce instead.")]
		public static object DuckImplicitCast(object value, Type toType)
		{
			return Coerce(value, toType);
		}

		public static object Coerce(object value, Type toType)
		{
			if (value == null) return null;

			return Dispatch(value, "$Coerce$", new Type[] {toType}, new object[] {toType}, delegate { return CreateCoerceDispatcher(value, toType); });
		}

		private static Dispatcher CreateCoerceDispatcher(object value, Type toType)
		{
			if (toType.IsInstanceOfType(value)) return IdentityDispatcher;
			if (value is ICoercible) return CoercibleDispatcher;

			Type fromType = value.GetType();
			if (IsPromotableNumeric(fromType) && IsPromotableNumeric(toType))
			{
				return new PromotionEmitter(toType).Emit();
			}

			MethodInfo method = FindImplicitConversionOperator(fromType, toType);
			if (null == method) return IdentityDispatcher;

			return EmitImplicitConversionDispatcher(method);
		}

		private static bool IsPromotableNumeric(Type fromType)
		{
			return IsPromotableNumeric(Type.GetTypeCode(fromType));
		}

		private static Dispatcher EmitImplicitConversionDispatcher(MethodInfo method)
		{
			return new ImplicitConversionEmitter(method).Emit();
		}

		private static object CoercibleDispatcher(object o, object[] args)
		{
			return ((ICoercible) o).Coerce((Type)args[0]);
		}

		private static object IdentityDispatcher(object o, object[] args)
		{
			return o;
		}

		public static object GetSlice(object target, string name, object[] args)
		{
			return Dispatch(target, name + "[]", args, delegate { return CreateGetSliceDispatcher(target, name, args); });
		}

		private static Dispatcher CreateGetSliceDispatcher(object target, string name, object[] args)
		{
			IQuackFu duck = target as IQuackFu;
			if (null != duck)
			{
				return delegate(object o, object[] arguments) { return ((IQuackFu) o).QuackGet(name, arguments); };
			}

			if ("" == name
				&& args.Length == 1
				&& target is System.Array) return GetArraySlice;
			
			return new SliceDispatcherFactory(_extensions, target, target.GetType(), name, args).CreateGetter();
		}

		private static object GetArraySlice(object target, object[] args)
		{
			IList list = (IList)target;
			return list[NormalizeIndex(list.Count, (int)args[0])];
		}

		public static object SetSlice(object target, string name, object[] args)
		{
			return Dispatch(target, name + "[]=", args, delegate { return CreateSetSliceDispatcher(target, name, args); });
		}

		static Dispatcher CreateSetSliceDispatcher(object target, string name, object[] args)
		{
			IQuackFu duck = target as IQuackFu;
			if (null != duck)
			{
				return delegate(object o, object[] arguments)
				{
					return ((IQuackFu) o).QuackSet(name, (object[]) GetRange2(arguments, 0, arguments.Length - 1), arguments[arguments.Length - 1]);
				};
			}

			if ("" == name
				&& 2 == args.Length
				&& target is System.Array) return SetArraySlice;

			return new SliceDispatcherFactory(_extensions, target, target.GetType(), name, args).CreateSetter();
		}

		private static object SetArraySlice(object target, object[] args)
		{
			IList list = (IList)target;
			list[NormalizeIndex(list.Count, (int)args[0])] = args[1];
			return args[1];
		}

		internal static String GetDefaultMemberName(Type type)
		{
			DefaultMemberAttribute attribute = (DefaultMemberAttribute)Attribute.GetCustomAttribute(type, typeof(DefaultMemberAttribute));
			return attribute != null ? attribute.MemberName : "";
		}

		public static object InvokeCallable(object target, object[] args)
		{
			if (null == target) throw new ArgumentNullException("target");
			if (null == args) throw new ArgumentNullException("args");

			ICallable c = target as ICallable;
			if (null != c) return c.Call(args);

			Delegate d = target as Delegate;
			if (null != d) return d.DynamicInvoke(args);
			
			Type type = target as Type;
			if (null != type) return Activator.CreateInstance(type, args);
			
			return ((MethodInfo)target).Invoke(null, args);
		}

		private static bool IsNumeric(TypeCode code)
		{
			switch (code)
			{
				case TypeCode.Byte: return true;
				case TypeCode.SByte: return true;
				case TypeCode.Int16: return true;
				case TypeCode.Int32: return true;
				case TypeCode.Int64: return true;
				case TypeCode.UInt16: return true;
				case TypeCode.UInt32: return true;
				case TypeCode.UInt64: return true;
				case TypeCode.Single: return true;
				case TypeCode.Double: return true;
				case TypeCode.Decimal: return true;
			}
			return false;
		}

		public static object InvokeBinaryOperator(string operatorName, object lhs, object rhs)
		{
			Type lhsType = lhs.GetType();
			Type rhsType = rhs.GetType();
			TypeCode lhsTypeCode = Type.GetTypeCode(lhsType);
			TypeCode rhsTypeCode = Type.GetTypeCode(rhsType);

			if (IsNumeric(lhsTypeCode) && IsNumeric(rhsTypeCode))
			{
				// HACK: optimization to get to the correct operators faster
				// is it worthy?
				switch (((int)operatorName[3] << 8) + (int)operatorName[operatorName.Length - 1])
				{
					case ((int)'A' << 8) + (int)'n':			// op_Addition
						return op_Addition(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'S' << 8) + (int)'n':			// op_Subtraction
						return op_Subtraction(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'M' << 8) + (int)'y':			// op_Multiply
						return op_Multiply(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'D' << 8) + (int)'n':			// op_Division
						return op_Division(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'M' << 8) + (int)'s':			// op_Modulus
						return op_Modulus(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'E' << 8) + (int)'n':			// op_Exponentiation
						return op_Exponentiation(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'L' << 8) + (int)'n':			// op_LessThan
						return op_LessThan(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'L' << 8) + (int)'l':			// op_LessThanOrEqual
						return op_LessThanOrEqual(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'G' << 8) + (int)'n':			// op_GreaterThan
						return op_GreaterThan(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'G' << 8) + (int)'l':			// op_GreaterThanOrEqual
						return op_GreaterThanOrEqual(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'B' << 8) + (int)'r':			// op_BitwiseOr
						return op_BitwiseOr(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'B' << 8) + (int)'d':			// op_BitwiseAnd
						return op_BitwiseAnd(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'E' << 8) + (int)'r':			// op_ExclusiveOr
						return op_ExclusiveOr(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'S' << 8) + (int)'t':			// op_ShiftLeft/Right
						return operatorName[8] == 'L' ?
							op_ShiftLeft(lhs, lhsTypeCode, rhs, rhsTypeCode) :
							op_ShiftRight(lhs, lhsTypeCode, rhs, rhsTypeCode);
					case ((int)'M' << 8) + (int)'h':			// op_Match
					case ((int)'N' << 8) + (int)'h':			// op_NotMatch
					case ((int)'M' << 8) + (int)'r':			// op_Member
					case ((int)'N' << 8) + (int)'r':			// op_NotMember
					default:
						throw new ArgumentException(lhs + " " + operatorName + " " + rhs);
				}
			}
			else
			{
				object[] args = new object[] { lhs, rhs };
				IQuackFu duck = lhs as IQuackFu;
				if (null != duck)
				{
					return duck.QuackInvoke(operatorName, args);
				}
				else
				{
					duck = rhs as IQuackFu;
					if (null != duck)
					{
						return duck.QuackInvoke(operatorName, args);
					}
				}

				try
				{
					// TODO: first resolve the right method on either
					// lhs and rhs
					// and then cache the final information
					return Invoke(lhsType, operatorName, args);
				}
				catch (MissingMethodException)
				{
					try
					{
						return Invoke(rhsType, operatorName, args);
					}
					catch (MissingMethodException)
					{
						try
						{
							return InvokeRuntimeServicesOperator(operatorName, args);
						}
						catch (MissingMethodException)
						{
						}
					}

					throw; // always throw the original exception
				}
			}
		}

		public static object InvokeUnaryOperator(string operatorName, object operand)
		{
			Type operandType = operand.GetType();
			TypeCode operandTypeCode = Type.GetTypeCode(operandType);

			if (IsNumeric(operandTypeCode))
			{
				// HACK: optimization to get to the correct operators faster
				// is it worthy?
				switch (((int)operatorName[3] << 8) + (int)operatorName[operatorName.Length - 1])
				{
					case ((int)'U' << 8) + (int)'n':			// op_UnaryNegation
						return op_UnaryNegation(operand, operandTypeCode);
					default:
						throw new ArgumentException(operatorName + " " + operand);
				}
			}
			else
			{
				object[] args = new object[] { operand };
				IQuackFu duck = operand as IQuackFu;
				if (null != duck)
				{
					return duck.QuackInvoke(operatorName, args);
				}

				try
				{
					return Invoke(operandType, operatorName, args);
				}
				catch (MissingMethodException)
				{
					try
					{
						return InvokeRuntimeServicesOperator(operatorName, args);
					}
					catch (MissingMethodException)
					{
					}

					throw; // always throw the original exception
				}
			}
		}

		private static object InvokeRuntimeServicesOperator(string operatorName, object[] args)
		{
			return Invoke(RuntimeServicesType, operatorName, args);
		}

		public static object MoveNext(IEnumerator enumerator)
		{
			if (null == enumerator) Error("CantUnpackNull");
			if (!enumerator.MoveNext()) Error("UnpackListOfWrongSize");
			return enumerator.Current;
		}

		public static int Len(object obj)
		{
			if (null != obj)
			{
				ICollection collection = obj as ICollection;
				if (null != collection) return collection.Count;

				string s = obj as string;
				if (null != s) return s.Length;
			}
			throw new ArgumentException();
		}

		public static string Mid(string s, int begin, int end)
		{
			begin = NormalizeStringIndex(s, begin);
			end = NormalizeStringIndex(s, end);
			return s.Substring(begin, end - begin);
		}

		public static Array GetRange1(Array source, int begin)
		{
			return GetRange2(source, begin, source.Length);
		}

		public static Array GetRange2(Array source, int begin, int end)
		{
			int sourceLen = source.Length;
			begin = NormalizeIndex(sourceLen, begin);
			end = NormalizeIndex(sourceLen, end);
			int targetLen = Math.Max(0, end - begin);
			Array target = Array.CreateInstance(source.GetType().GetElementType(), targetLen);
			Array.Copy(source, begin, target, 0, targetLen);
			return target;
		}

		public static void SetMultiDimensionalRange1(Array source, Array dest, int[] ranges, bool[] collapse)
		{
			if (dest.Rank != ranges.Length / 2)
			{
				throw new Exception("invalid range passed: " + ranges.Length / 2 + ", expected " + dest.Rank * 2);
			}

			for (int i = 0; i < dest.Rank; i++)
			{
				if (ranges[2 * i] > 0 ||
					ranges[2 * i] > dest.GetLength(i) ||
					ranges[2 * i + 1] > dest.GetLength(i) ||
					ranges[2 * i + 1] < ranges[2 * i])
				{
					// FIXME: Better error reporting
					Error("InvalidArray");
				}
			}

			int sourceRank = 0;
			foreach (bool val in collapse)
			{
				if (!val)
				{
					sourceRank++;
				}
			}

			if (source.Rank != sourceRank)
			{
				// FIXME: Better error reporting
				Error("InvalidArray");
			}

			int[] lensDest = new int[dest.Rank];
			int[] lensSrc = new int[sourceRank];
			int rankIndex = 0;
			for (int i = 0; i < dest.Rank; i++)
			{
				lensDest[i] = ranges[2 * i + 1] - ranges[2 * i];
				if (!collapse[i])
				{
					lensSrc[rankIndex] = lensDest[i] - ranges[2 * i];
					if (lensSrc[rankIndex] != source.GetLength(rankIndex))
					{
						// FIXME: Better error reporting
						Error("InvalidArray");
					}
					rankIndex++;
				}
			}

			int[] modInd = new int[dest.Rank];
			for (int i = 0; i < dest.Rank; i++)
			{
				if (i == 0)
				{
					modInd[i] = source.Length / lensDest[lensDest.Length - 1];
				}
				else
				{
					modInd[i] = modInd[i - 1] / lensDest[i - 1];
				}
			}

			int counter;
			int[] indexDest = new int[dest.Rank];
			int[] indexSrc = new int[sourceRank];
			for (int i = 0; i < source.Length; i++)
			{
				counter = 0;
				for (int j = 0; j < dest.Rank; j++)
				{
					int index = (i % modInd[j]) / (modInd[j] / lensDest[j]);
					indexDest[j] = index;
					if (!collapse[j])
					{
						indexSrc[counter] = indexDest[j] + ranges[2 * j];
						counter++;
					}
					dest.SetValue(source.GetValue(indexSrc), indexDest);
				}
			}
		}

		public static Array GetMultiDimensionalRange1(Array source, int[] ranges, bool[] collapse)
		{
			int rankSrc = source.Rank;
			int collapseSize = 0;

			foreach (bool val in collapse)
			{
				if (val)
				{
					collapseSize++;
				}
			}

			int rankDest = rankSrc - collapseSize;
			int[] lensDest = new int[rankDest];
			int[] lensSrc = new int[rankSrc];

			int rankIndex = 0;
			for (int i = 0; i < rankSrc; i++)
			{
				ranges[2 * i] = NormalizeIndex(source.GetLength(i), ranges[2 * i]);
				ranges[2 * i + 1] = NormalizeIndex(source.GetLength(i), ranges[2 * i + 1]);

				lensSrc[i] = ranges[2 * i + 1] - ranges[2 * i];
				if (!collapse[i])
				{
					lensDest[rankIndex] = ranges[2 * i + 1] - ranges[2 * i];
					rankIndex++;
				}
			}

			Array dest = Array.CreateInstance(source.GetType().GetElementType(), lensDest);

			int[] modInd = new int[rankSrc];
			int[] indicesDest = new int[rankDest];
			int[] indicesSrc = new int[rankSrc];

			for (int i = 0; i < rankSrc; i++)
			{
				if (i == 0)
				{
					modInd[i] = dest.Length;
				}
				else
				{
					modInd[i] = modInd[i - 1] / lensSrc[i - 1];
				}
			}

			for (int i = 0; i < dest.Length; i++)
			{
				int destIndex = 0;
				for (int j = 0; j < rankSrc; j++)
				{
					int index = (i % modInd[j]) / (modInd[j] / lensSrc[j]);
					indicesSrc[j] = ranges[2 * j] + index;
					if (!collapse[j])
					{
						indicesDest[destIndex] = indicesSrc[j] - ranges[2 * j];
						destIndex++;
					}
				}
				dest.SetValue(source.GetValue(indicesSrc), indicesDest);
			}

			return dest;
		}

		public static void CheckArrayUnpack(Array array, int expected)
		{
			if (null == array)
			{
				Error("CantUnpackNull");
			}
			if (expected > array.Length)
			{
				Error("UnpackArrayOfWrongSize", expected, array.Length);
			}
		}

		public static int NormalizeIndex(int len, int index)
		{
			if (index < 0)
			{
				index += len;
				if (index < 0) return 0;
			}

			if (index > len) return len;

			return index;
		}

		public static int NormalizeArrayIndex(Array array, int index)
		{
			return NormalizeIndex(array.Length, index);
		}

		public static int NormalizeStringIndex(string s, int index)
		{
			return NormalizeIndex(s.Length, index);
		}

		public static IEnumerable GetEnumerable(object enumerable)
		{
			if (null == enumerable) Error("CantEnumerateNull");

			IEnumerable iterator = enumerable as IEnumerable;
			if (null != iterator) return iterator;

			TextReader reader = enumerable as TextReader;
			if (null != reader) return TextReaderEnumerator.lines(reader);

			Error("ArgumentNotEnumerable");
			return null;
		}

		#region global operators

		public static Array AddArrays(Type resultingElementType, Array lhs, Array rhs)
		{
			int resultingLen = lhs.Length + rhs.Length;
			Array result = Array.CreateInstance(resultingElementType, resultingLen);
			Array.Copy(lhs, 0, result, 0, lhs.Length);
			Array.Copy(rhs, 0, result, lhs.Length, rhs.Length);
			return result;
		}

		public static string op_Addition(string lhs, string rhs)
		{
			return string.Concat(lhs, rhs);
		}

		public static string op_Addition(string lhs, object rhs)
		{
			return string.Concat(lhs, rhs);
		}

		public static string op_Addition(object lhs, string rhs)
		{
			return string.Concat(lhs, rhs);
		}

		public static Array op_Multiply(Array lhs, int count)
		{
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count");
			}

			Type type = lhs.GetType();
			if (1 != type.GetArrayRank())
			{
				throw new ArgumentException("lhs");
			}

			int length = lhs.Length;
			Array result = Array.CreateInstance(type.GetElementType(), length * count);
			int destinationIndex = 0;
			for (int i = 0; i < count; ++i)
			{
				Array.Copy(lhs, 0, result, destinationIndex, length);
				destinationIndex += length;
			}
			return result;
		}

		public static Array op_Multiply(int count, Array rhs)
		{
			return op_Multiply(rhs, count);
		}

		public static string op_Multiply(string lhs, int count)
		{
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count");
			}

			string result = null;
			if (null != lhs)
			{
				StringBuilder builder = new StringBuilder(lhs.Length * count);
				for (int i = 0; i < count; ++i)
				{
					builder.Append(lhs);
				}
				result = builder.ToString();
			}
			return result;
		}

		public static string op_Multiply(int count, string rhs)
		{
			return op_Multiply(rhs, count);
		}

		public static bool op_NotMember(string lhs, string rhs)
		{
			return !op_Member(lhs, rhs);
		}

		public static bool op_Member(string lhs, string rhs)
		{
			if (null == lhs || null == rhs)
			{
				return false;
			}
			return rhs.IndexOf(lhs) > -1;
		}

#if !NO_SYSTEM_DLL
		public static bool op_Match(string input, System.Text.RegularExpressions.Regex pattern)
		{
			return pattern.IsMatch(input);
		}

		public static bool op_Match(string input, string pattern)
		{
			return System.Text.RegularExpressions.Regex.IsMatch(input, pattern);
		}

		public static bool op_NotMatch(string input, System.Text.RegularExpressions.Regex pattern)
		{
			return !op_Match(input, pattern);
		}
	
		public static bool op_NotMatch(string input, string pattern)
		{
			return !op_Match(input, pattern);
		}
#endif

		public static string op_Modulus(string lhs, IEnumerable rhs)
		{
			return string.Format(lhs, Boo.Lang.Builtins.array(rhs));
		}

		public static string op_Modulus(string lhs, object[] rhs)
		{
			return string.Format(lhs, rhs);
		}

		public static bool op_Member(object lhs, IList rhs)
		{
			if (null == rhs)
			{
				return false;
			}
			return rhs.Contains(lhs);
		}

		public static bool op_NotMember(object lhs, IList rhs)
		{
			return !op_Member(lhs, rhs);
		}

		public static bool op_Member(object lhs, IDictionary rhs)
		{
			if (null == rhs)
			{
				return false;
			}
			return rhs.Contains(lhs);
		}

		public static bool op_NotMember(object lhs, IDictionary rhs)
		{
			return !op_Member(lhs, rhs);
		}

		public static bool op_Member(object lhs, IEnumerable rhs)
		{
			if (null == rhs)
			{
				return false;
			}
			foreach (object item in rhs)
			{
				if (EqualityOperator(lhs, item))
				{
					return true;
				}
			}
			return false;
		}

		public static bool op_NotMember(object lhs, IEnumerable rhs)
		{
			return !op_Member(lhs, rhs);
		}

		public static bool EqualityOperator(object lhs, object rhs)
		{
			if (lhs == rhs) return true;

			// Some types do overload Equals to compare
			// against null values
			if (null == lhs) return rhs.Equals(lhs);
			if (null == rhs) return lhs.Equals(rhs);

			TypeCode lhsTypeCode = Type.GetTypeCode(lhs.GetType());
			TypeCode rhsTypeCode = Type.GetTypeCode(rhs.GetType());
			if (IsNumeric(lhsTypeCode) && IsNumeric(rhsTypeCode))
			{
				return EqualityOperator(lhs, lhsTypeCode, rhs, rhsTypeCode);
			}

			Array lhsa = lhs as Array;
			if (null != lhsa)
			{
				Array rhsa = rhs as Array;
				if (null != rhsa)
				{
					return ArrayEqualityImpl(lhsa, rhsa);
				}
			}
			return lhs.Equals(rhs) || rhs.Equals(lhs);
		}

		public static bool op_Equality(Array lhs, Array rhs)
		{
			if (lhs == rhs)
			{
				return true;
			}

			if (null == lhs || null == rhs)
			{
				return false;
			}
			return ArrayEqualityImpl(lhs, rhs);
		}

		static bool ArrayEqualityImpl(Array lhs, Array rhs)
		{
			if (1 != lhs.Rank || 1 != rhs.Rank)
			{
				throw new ArgumentException("array rank must be 1");
			}

			if (lhs.Length != rhs.Length)
			{
				return false;
			}

			for (int i = 0; i < lhs.Length; ++i)
			{
				if (!EqualityOperator(lhs.GetValue(i), rhs.GetValue(i)))
				{
					return false;
				}
			}
			return true;
		}
		#endregion

		#region dynamic operator for primitive types
		private static TypeCode GetConvertTypeCode(TypeCode lhsTypeCode, TypeCode rhsTypeCode)
		{
			/* C# ECMA Spec V2
			 * 14.2.6.2 Binary numeric promotions
			 * This clause is informative.
			 * Binary numeric promotion occurs for the operands of the predefined +, ?, *, /, %, &, |, ^, ==, !=, >, <, >=,
			 * and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type
			 * which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric
			 * promotion consists of applying the following rules, in the order they appear here:
			 * � If either operand is of type decimal, the other operand is converted to type decimal, or a compiletime
			 *	 error occurs if the other operand is of type float or double.
			 * � Otherwise, if either operand is of type double, the other operand is converted to type double.
			 * � Otherwise, if either operand is of type float, the other operand is converted to type float.
			 * � Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or a
			 *	 compile-time error occurs if the other operand is of type sbyte, short, int, or long.
			 * � Otherwise, if either operand is of type long, the other operand is converted to type long.
			 * � Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int,
			 *	 both operands are converted to type long.
			 * � Otherwise, if either operand is of type uint, the other operand is converted to type uint.
			 * � Otherwise, both operands are converted to type int.
			 * [Note: The first rule disallows any operations that mix the decimal type with the double and float types.
			 *	The rule follows from the fact that there are no implicit conversions between the decimal type and the
			 *	double and float types. end note]
			 * [Note: Also note that it is not possible for an operand to be of type ulong when the other operand is of a
			 *	signed integral type. The reason is that no integral type exists that can represent the full range of ulong as
			 *	well as the signed integral types. end note]
			 * In both of the above cases, a cast expression can be used to explicitly convert one operand to a type that is
			 * compatible with the other operand.
			 */
			if (TypeCode.Decimal == lhsTypeCode || TypeCode.Decimal == rhsTypeCode)
			{
				return TypeCode.Decimal;	// not per ECMA spec
			}
			if (TypeCode.Double == lhsTypeCode || TypeCode.Double == rhsTypeCode)
			{
				return TypeCode.Double;
			}
			if (TypeCode.Single == lhsTypeCode || TypeCode.Single == rhsTypeCode)
			{
				return TypeCode.Single;
			}
			if (TypeCode.UInt64 == lhsTypeCode)
			{
				if (TypeCode.SByte == rhsTypeCode || TypeCode.Int16 == rhsTypeCode ||
					TypeCode.Int32 == rhsTypeCode || TypeCode.Int64 == rhsTypeCode)
				{
					//					throw new ArgumentException("ulong <op> " + rhsTypeCode);
					return TypeCode.Int64;	// not per Ecma spec
				}
				return TypeCode.UInt64;
			}
			if (TypeCode.UInt64 == rhsTypeCode)
			{
				if (TypeCode.SByte == lhsTypeCode || TypeCode.Int16 == lhsTypeCode ||
					TypeCode.Int32 == lhsTypeCode || TypeCode.Int64 == lhsTypeCode)
				{
					//					throw new ArgumentException(lhsTypeCode + " <op> ulong");
					return TypeCode.Int64;	// not per Ecma spec
				}
				return TypeCode.UInt64;
			}
			if (TypeCode.Int64 == lhsTypeCode || TypeCode.Int64 == rhsTypeCode)
			{
				return TypeCode.Int64;
			}
			if (TypeCode.UInt32 == lhsTypeCode)
			{
				if (TypeCode.SByte == rhsTypeCode || TypeCode.Int16 == rhsTypeCode ||
					TypeCode.Int32 == rhsTypeCode)
				{
					return TypeCode.Int64;
				}
				return TypeCode.UInt32;
			}
			if (TypeCode.UInt32 == rhsTypeCode)
			{
				if (TypeCode.SByte == lhsTypeCode || TypeCode.Int16 == lhsTypeCode ||
					TypeCode.Int32 == lhsTypeCode)
				{
					return TypeCode.Int64;
				}
				return TypeCode.UInt32;
			}
			return TypeCode.Int32;
		}

		private static object op_Multiply(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) * rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) * rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) * rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) * rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) * rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) * rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) * rhsConvertible.ToInt32(null);
			}
		}

		private static object op_Division(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) / rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) / rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) / rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) / rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) / rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) / rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) / rhsConvertible.ToInt32(null);
			}
		}

		private static object op_Addition(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) + rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) + rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) + rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) + rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) + rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) + rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) + rhsConvertible.ToInt32(null);
			}
		}

		private static object op_Subtraction(object lhs, TypeCode lhsTypeCode,
											 object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) - rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) - rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) - rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) - rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) - rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) - rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) - rhsConvertible.ToInt32(null);
			}
		}

		private static bool EqualityOperator(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) == rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) == rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) == rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) == rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) == rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) == rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) == rhsConvertible.ToInt32(null);
			}
		}

		private static bool op_GreaterThan(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) > rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) > rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) > rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) > rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) > rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) > rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) > rhsConvertible.ToInt32(null);
			}
		}

		private static bool op_GreaterThanOrEqual(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) >= rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) >= rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) >= rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) >= rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) >= rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) >= rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) >= rhsConvertible.ToInt32(null);
			}
		}

		private static bool op_LessThan(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) < rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) < rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) < rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) < rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) < rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) < rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) < rhsConvertible.ToInt32(null);
			}
		}

		private static bool op_LessThanOrEqual(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) <= rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) <= rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) <= rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) <= rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) <= rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) <= rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) <= rhsConvertible.ToInt32(null);
			}
		}

		private static object op_Modulus(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
					return lhsConvertible.ToDecimal(null) % rhsConvertible.ToDecimal(null);
				case TypeCode.Double:
					return lhsConvertible.ToDouble(null) % rhsConvertible.ToDouble(null);
				case TypeCode.Single:
					return lhsConvertible.ToSingle(null) % rhsConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) % rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) % rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) % rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) % rhsConvertible.ToInt32(null);
			}
		}

		private static double op_Exponentiation(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			return Math.Pow(lhsConvertible.ToDouble(null), rhsConvertible.ToDouble(null));
		}

		private static object op_BitwiseAnd(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
				case TypeCode.Double:
				case TypeCode.Single:
					throw new ArgumentException(lhsTypeCode + " & " + rhsTypeCode);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) & rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) & rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) & rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) & rhsConvertible.ToInt32(null);
			}
		}

		private static object op_BitwiseOr(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
				case TypeCode.Double:
				case TypeCode.Single:
					throw new ArgumentException(lhsTypeCode + " | " + rhsTypeCode);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) | rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) | rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) | rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) | rhsConvertible.ToInt32(null);
			}
		}

		private static object op_ExclusiveOr(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch (GetConvertTypeCode(lhsTypeCode, rhsTypeCode))
			{
				case TypeCode.Decimal:
				case TypeCode.Double:
				case TypeCode.Single:
					throw new ArgumentException(lhsTypeCode + " ^ " + rhsTypeCode);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) ^ rhsConvertible.ToUInt64(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) ^ rhsConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) ^ rhsConvertible.ToUInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) ^ rhsConvertible.ToInt32(null);
			}
		}

		private static object op_ShiftLeft(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;

			switch(rhsTypeCode)
			{
				case TypeCode.Decimal:
				case TypeCode.Double:
				case TypeCode.Single:
					throw new ArgumentException(lhsTypeCode + " << " + rhsTypeCode);
				default:
					break;
			}

			switch (lhsTypeCode)
			{
				case TypeCode.Decimal:
				case TypeCode.Double:
				case TypeCode.Single:
					throw new ArgumentException(lhsTypeCode + " << " + rhsTypeCode);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) << rhsConvertible.ToInt32(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) << rhsConvertible.ToInt32(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) << rhsConvertible.ToInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) << rhsConvertible.ToInt32(null);
			}
		}
		
		private static object op_ShiftRight(object lhs, TypeCode lhsTypeCode,
										  object rhs, TypeCode rhsTypeCode)
		{
			IConvertible lhsConvertible = (IConvertible)lhs;
			IConvertible rhsConvertible = (IConvertible)rhs;
			
			switch(rhsTypeCode)
			{
				case TypeCode.Decimal:
				case TypeCode.Double:
				case TypeCode.Single:
					throw new ArgumentException(lhsTypeCode + " >> " + rhsTypeCode);
				default:
					break;
			}

			switch (lhsTypeCode)
			{
				case TypeCode.Decimal:
				case TypeCode.Double:
				case TypeCode.Single:
					throw new ArgumentException(lhsTypeCode + " >> " + rhsTypeCode);
				case TypeCode.UInt64:
					return lhsConvertible.ToUInt64(null) >> rhsConvertible.ToInt32(null);
				case TypeCode.Int64:
					return lhsConvertible.ToInt64(null) >> rhsConvertible.ToInt32(null);
				case TypeCode.UInt32:
					return lhsConvertible.ToUInt32(null) >> rhsConvertible.ToInt32(null);
				case TypeCode.Int32:
				default:
					return lhsConvertible.ToInt32(null) >> rhsConvertible.ToInt32(null);
			}
		}
		
		private static object op_UnaryNegation(object operand, TypeCode operandTypeCode)
		{
			IConvertible operandConvertible = (IConvertible)operand;

			switch (operandTypeCode)
			{
				case TypeCode.Decimal:
					return -operandConvertible.ToDecimal(null);
				case TypeCode.Double:
					return -operandConvertible.ToDouble(null);
				case TypeCode.Single:
					return -operandConvertible.ToSingle(null);
				case TypeCode.UInt64:
					return -operandConvertible.ToInt64(null);
				case TypeCode.Int64:
					return -operandConvertible.ToInt64(null);
				case TypeCode.UInt32:
					return -operandConvertible.ToInt64(null);
				case TypeCode.Int32:
				default:
					return -operandConvertible.ToInt32(null);
			}
		}

		#endregion

		internal static bool IsPromotableNumeric(TypeCode code)
		{
			switch (code)
			{
				case TypeCode.Byte: return true;
				case TypeCode.SByte: return true;
				case TypeCode.Int16: return true;
				case TypeCode.Int32: return true;
				case TypeCode.Int64: return true;
				case TypeCode.UInt16: return true;
				case TypeCode.UInt32: return true;
				case TypeCode.UInt64: return true;
				case TypeCode.Single: return true;
				case TypeCode.Double: return true;
				case TypeCode.Boolean: return true;
				case TypeCode.Decimal: return true;
				case TypeCode.Char: return true;
			}
			return false;
		}

		public static IConvertible CheckNumericPromotion(object value)
		{
			IConvertible convertible = (IConvertible)value;
			return CheckNumericPromotion(convertible);
		}

		public static IConvertible CheckNumericPromotion(IConvertible convertible)
		{
			if (IsPromotableNumeric(convertible.GetTypeCode()))
			{
				return convertible;
			}
			throw new InvalidCastException();
		}

		public static Byte UnboxByte(object value)
		{
			if (value is Byte)
			{
				return (Byte)value;
			}
			return CheckNumericPromotion(value).ToByte(null);
		}

		public static SByte UnboxSByte(object value)
		{
			if (value is SByte)
			{
				return (SByte)value;
			}
			return CheckNumericPromotion(value).ToSByte(null);
		}

		public static char UnboxChar(object value)
		{
			if (value is char)
			{
				return (char)value;
			}
			return CheckNumericPromotion(value).ToChar(null);
		}

		public static Int16 UnboxInt16(object value)
		{
			if (value is Int16)
			{
				return (Int16)value;
			}
			return CheckNumericPromotion(value).ToInt16(null);
		}

		public static UInt16 UnboxUInt16(object value)
		{
			if (value is UInt16)
			{
				return (UInt16)value;
			}
			return CheckNumericPromotion(value).ToUInt16(null);
		}

		public static Int32 UnboxInt32(object value)
		{
			if (value is Int32)
			{
				return (Int32)value;
			}
			return CheckNumericPromotion(value).ToInt32(null);
		}

		public static UInt32 UnboxUInt32(object value)
		{
			if (value is UInt32)
			{
				return (UInt32)value;
			}
			return CheckNumericPromotion(value).ToUInt32(null);
		}

		public static Int64 UnboxInt64(object value)
		{
			if (value is Int64)
			{
				return (Int64)value;
			}
			return CheckNumericPromotion(value).ToInt64(null);
		}

		public static UInt64 UnboxUInt64(object value)
		{
			if (value is UInt64)
			{
				return (UInt64)value;
			}
			return CheckNumericPromotion(value).ToUInt64(null);
		}

		public static Single UnboxSingle(object value)
		{
			if (value is Single)
			{
				return (Single)value;
			}
			return CheckNumericPromotion(value).ToSingle(null);
		}

		public static Double UnboxDouble(object value)
		{
			if (value is Double)
			{
				return (Double)value;
			}
			return CheckNumericPromotion(value).ToDouble(null);
		}

		public static Decimal UnboxDecimal(object value)
		{
			if (value is Decimal)
			{
				return (Decimal)value;
			}
			return CheckNumericPromotion(value).ToDecimal(null);
		}

		public static Boolean UnboxBoolean(object value)
		{
			if (value is Boolean)
			{
				return (Boolean)value;
			}
			return CheckNumericPromotion(value).ToBoolean(null);
		}

		#region bool conversion
		public static bool ToBool(object value)
		{
			if (null == value) return false;
			if (value is bool) return (bool) value;

			Type type = value.GetType();
			return
				(bool)
				Dispatch(value, "$ToBool$", new Type[] {type}, new object[] {value}, delegate { return CreateBoolConverter(type); });
		}

		public static bool ToBool(decimal value)
		{
			return 0 != value;
		}

		public static bool ToBool(System.Single value)
		{
			return 0 != value;
		}

		public static bool ToBool(System.Double value)
		{
			return 0 != value;
		}

		private static readonly object True = true;
		private static object ToBoolTrue(object value, object[] arguments)
		{
			return True;
		}

		private static object UnboxBooleanDispatcher(object value, object[] arguments)
		{
			return UnboxBoolean(value);
		}
		
		static Dispatcher CreateBoolConverter(Type type)
		{
			MethodInfo method = FindImplicitConversionOperator(type, typeof(bool));
			if (null != method) return EmitImplicitConversionDispatcher(method);
			if (type.IsValueType) return UnboxBooleanDispatcher;
			return ToBoolTrue;
		}
		#endregion

		#region conversion proxy helpers
		internal static MethodInfo FindImplicitConversionOperator(Type from, Type to)
		{
			const BindingFlags ConversionOperatorFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy;
			MethodInfo found = FindImplicitConversionMethod(from.GetMethods(ConversionOperatorFlags), from, to);
			if (null != found) return found;
			found = FindImplicitConversionMethod(to.GetMethods(ConversionOperatorFlags), from, to);
			if (null != found) return found;
			return FindImplicitConversionMethod(GetExtensionMethods(), from, to);
		}

		private static IEnumerable<MethodInfo> GetExtensionMethods()
		{
			foreach (MemberInfo member in _extensions.Extensions)
			{
				if (member.MemberType == MemberTypes.Method) yield return (MethodInfo) member;
			}
		}

		private static MethodInfo FindImplicitConversionMethod(System.Collections.Generic.IEnumerable<MethodInfo> candidates, Type from, Type to)
		{
			foreach (MethodInfo m in candidates)
			{
				if (m.Name != "op_Implicit") continue;
				if (m.ReturnType != to) continue;
				ParameterInfo[] parameters = m.GetParameters();
				if (parameters.Length != 1) continue;
				if (!parameters[0].ParameterType.IsAssignableFrom(from)) continue;
				return m;
			}
			return null;
		}

		#endregion

		static void Error(string name, params object[] args)
		{
			throw new ApplicationException(Boo.Lang.ResourceManager.Format(name, args));
		}

		static void Error(string name)
		{
			throw new ApplicationException(Boo.Lang.ResourceManager.GetString(name));
		}
	}
}
Back to Top