forked from IronLanguages/main
/
IListOps.cs
1482 lines (1206 loc) · 53.3 KB
/
IListOps.cs
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
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Microsoft Public License. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Microsoft Public License, please send an email to
* ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Microsoft Public License.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronRuby.Runtime;
using IronRuby.Runtime.Calls;
namespace IronRuby.Builtins {
[RubyModule(Extends = typeof(IList)), Includes(typeof(Enumerable))]
public static class IListOps {
#region Helpers
internal static int NormalizeIndex(IList/*!*/ list, int index) {
return NormalizeIndex(list.Count, index);
}
internal static int NormalizeIndex(int count, int index) {
return index < 0 ? index + count : index;
}
internal static bool NormalizeRange(int listCount, ref int start, ref int count) {
start = NormalizeIndex(listCount, start);
if (start < 0 || start > listCount || count < 0) {
return false;
}
if (count != 0) {
count = start + count > listCount ? listCount - start : count;
}
return true;
}
internal static bool NormalizeRange(ConversionStorage<int>/*!*/ fixnumCast, int listCount, Range/*!*/ range, out int begin, out int count) {
begin = Protocols.CastToFixnum(fixnumCast, range.Begin);
int end = Protocols.CastToFixnum(fixnumCast, range.End);
begin = NormalizeIndex(listCount, begin);
if (begin < 0 || begin > listCount) {
count = 0;
return false;
}
end = NormalizeIndex(listCount, end);
count = range.ExcludeEnd ? end - begin : end - begin + 1;
return true;
}
private static bool InRangeNormalized(IList/*!*/ list, ref int index) {
if (index < 0) {
index = index + list.Count;
}
return index >= 0 && index < list.Count;
}
private static IEnumerable<object>/*!*/ EnumerateRange(IList/*!*/ list, int index, int count) {
int stop = index + count;
for (int i = index; i < stop; i++) {
yield return list[i];
}
}
private static IList/*!*/ GetResultRange(CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage,
IList/*!*/ list, int index, int count) {
IList result = CreateResultArray(allocateStorage, list);
int stop = index + count;
for (int i = index; i < stop; i++) {
result.Add(list[i]);
}
return result;
}
private static void InsertRange(IList/*!*/ collection, int index, IEnumerable<object>/*!*/ items) {
List<object> list = collection as List<object>;
if (list != null) {
list.InsertRange(index, items);
} else {
int i = index;
foreach (object obj in items) {
collection.Insert(i++, obj);
}
}
}
private static void RemoveRange(IList/*!*/ collection, int index, int count) {
List<object> list = collection as List<object>;
if (list != null) {
list.RemoveRange(index, count);
} else {
for (int i = index + count - 1; i >= index; i--) {
collection.RemoveAt(i);
}
}
}
internal static void AddRange(IList/*!*/ collection, IList/*!*/ items) {
List<object> list = collection as List<object>;
if (list != null) {
list.Capacity += items.Count;
}
// note: "collection" could be the same as "items" so we can't use an enumerator
int count = items.Count;
for (int i = 0; i < count; i++) {
collection.Add(items[i]);
}
}
private static IList/*!*/ CreateResultArray(CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage, IList/*!*/ list) {
// RubyArray:
var array = list as RubyArray;
if (array != null) {
return array.CreateInstance();
}
// interop - call a default ctor to get an instance:
var allocate = allocateStorage.GetCallSite("allocate", 0);
var cls = allocateStorage.Context.GetClassOf(list);
var result = allocate.Target(allocate, cls) as IList;
if (result != null) {
return result;
}
throw RubyExceptions.CreateTypeError(String.Format("{0}#allocate should return IList", cls.Name));
}
#endregion
#region initialize_copy, replace, clear, to_a, to_ary
[RubyMethod("replace")]
[RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)]
public static IList/*!*/ Replace(RubyContext/*!*/ context, IList/*!*/ self, [NotNull, DefaultProtocol]IList/*!*/ other) {
RubyUtils.RequiresNotFrozen(context, self);
self.Clear();
AddRange(self, other);
return self;
}
[RubyMethod("clear")]
public static IList Clear(RubyContext/*!*/ context, IList/*!*/ self) {
RubyUtils.RequiresNotFrozen(context, self);
self.Clear();
return self;
}
[RubyMethod("to_a")]
[RubyMethod("to_ary")]
public static RubyArray/*!*/ ToArray(IList/*!*/ self) {
RubyArray list = new RubyArray(self.Count);
foreach (object item in self) {
list.Add(item);
}
return list;
}
#endregion
#region *, +, concat
[RubyMethod("*")]
public static IList/*!*/ Repetition(CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage, IList/*!*/ self, int repeat) {
if (repeat < 0) {
throw RubyExceptions.CreateArgumentError("negative argument");
}
IList result = CreateResultArray(allocateStorage, self);
if (result is RubyArray) {
(result as RubyArray).Capacity = self.Count * repeat;
}
for (int i = 0; i < repeat; ++i) {
AddRange(result, self);
}
allocateStorage.Context.TaintObjectBy<IList>(result, self);
return result;
}
[RubyMethod("*")]
public static MutableString Repetition(ConversionStorage<MutableString>/*!*/ tosConversion, IList/*!*/ self, [NotNull]MutableString/*!*/ separator) {
return Join(tosConversion, self, separator);
}
[RubyMethod("*")]
public static object Repetition(CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage, ConversionStorage<MutableString>/*!*/ tosConversion, IList/*!*/ self, [DefaultProtocol]Union<MutableString, int> repeat) {
if (repeat.IsFixnum()) {
return Repetition(allocateStorage, self, repeat.Fixnum());
} else {
return Repetition(tosConversion, self, repeat.String());
}
}
[RubyMethod("+")]
public static RubyArray/*!*/ Concatenate(IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
RubyArray result = new RubyArray(self.Count + other.Count);
AddRange(result, self);
AddRange(result, other);
return result;
}
[RubyMethod("concat")]
public static IList/*!*/ Concat(RubyContext/*!*/ context, IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
if (other.Count > 0) {
RubyUtils.RequiresNotFrozen(context, self);
}
AddRange(self, other);
return self;
}
[RubyMethod("-")]
public static RubyArray/*!*/ Difference(RubyContext/*!*/ context, IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
// MRI follows hashing semantics here, so doesn't actually call eql?/hash for Fixnum/Symbol
IEqualityComparer<object> comparer = context.EqualityComparer;
RubyArray result = new RubyArray();
// TODO: optimize this
foreach (object selfElement in self) {
bool found = false;
foreach (object otherElement in other) {
bool sameHashcode = comparer.GetHashCode(selfElement) == comparer.GetHashCode(otherElement);
bool isEql = comparer.Equals(selfElement, otherElement);
if (sameHashcode && isEql) {
found = true;
break;
}
}
if (!found) {
result.Add(selfElement);
}
}
return result;
}
#endregion
#region ==, <=>, eql?, hash
[RubyMethod("==")]
public static bool Equals(ConversionStorage<IList>/*!*/ arrayTryCast, BinaryOpStorage/*!*/ equals, IList/*!*/ self, object other) {
IList otherAsArray = Protocols.TryCastToArray(arrayTryCast, other);
return otherAsArray != null ? Equals(equals, self, otherAsArray) : false;
}
[MultiRuntimeAware]
private static RubyUtils.RecursionTracker _EqualsTracker = new RubyUtils.RecursionTracker();
[RubyMethod("==")]
public static bool Equals(BinaryOpStorage/*!*/ equals, IList/*!*/ self, [NotNull]IList/*!*/ other) {
Assert.NotNull(self, other);
if (object.ReferenceEquals(self, other)) {
return true;
}
if (self.Count != other.Count) {
return false;
}
using (IDisposable handle = _EqualsTracker.TrackObject(self)) {
if (handle == null) {
// hashing of recursive array
return false;
}
for (int i = 0; i < self.Count; ++i) {
bool result = Protocols.IsEqual(equals, self[i], other[i]);
if (!result) {
return false;
}
}
}
return true;
}
[MultiRuntimeAware]
private static RubyUtils.RecursionTracker _infiniteComparisonTracker = new RubyUtils.RecursionTracker();
[RubyMethod("<=>")]
public static object Compare(BinaryOpStorage/*!*/ comparisonStorage, IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
using (IDisposable handle = _infiniteComparisonTracker.TrackObject(self)) {
if (handle == null) {
return 0;
}
int limit = Math.Min(self.Count, other.Count);
var compare = comparisonStorage.GetCallSite("<=>");
for (int i = 0; i < limit; i++) {
object result = compare.Target(compare, self[i], other[i]);
if (!(result is int) || (int)result != 0) {
return result;
}
}
return ScriptingRuntimeHelpers.Int32ToObject(Math.Sign(self.Count - other.Count));
}
}
[RubyMethod("eql?")]
public static bool HashEquals(IList/*!*/ self, object other) {
return RubyArray.Equals(self, other);
}
[RubyMethod("hash")]
public static int GetHashCode(IList/*!*/ self) {
return RubyArray.GetHashCode(self);
}
#endregion
#region slice, [], at
[RubyMethod("[]")]
[RubyMethod("slice")]
public static object GetElement(IList list, [DefaultProtocol]int index) {
return InRangeNormalized(list, ref index) ? list[index] : null;
}
[RubyMethod("[]")]
[RubyMethod("slice")]
public static IList GetElements(CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage,
IList/*!*/ list, [DefaultProtocol]int index, [DefaultProtocol]int count) {
if (!NormalizeRange(list.Count, ref index, ref count)) {
return null;
}
return GetResultRange(allocateStorage, list, index, count);
}
[RubyMethod("[]")]
[RubyMethod("slice")]
public static IList GetElement(ConversionStorage<int>/*!*/ fixnumCast,
CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage,
IList array, [NotNull]Range/*!*/ range) {
int start, count;
if (!NormalizeRange(fixnumCast, array.Count, range, out start, out count)) {
return null;
}
return count < 0 ? CreateResultArray(allocateStorage, array) : GetElements(allocateStorage, array, start, count);
}
[RubyMethod("at")]
public static object At(IList/*!*/ self, [DefaultProtocol]int index) {
return GetElement(self, index);
}
#endregion
#region []=
public static void ExpandList(IList list, int index) {
int diff = index - list.Count;
for (int i = 0; i < diff; i++) {
list.Add(null);
}
}
public static void OverwriteOrAdd(IList list, int index, object value) {
if (index < list.Count) {
list[index] = value;
} else {
list.Add(value);
}
}
public static void DeleteItems(IList list, int index, int length) {
if (index >= list.Count) {
ExpandList(list, index);
} else {
// normalize for max length
if (index + length > list.Count) {
length = list.Count - index;
}
RemoveRange(list, index, length);
}
}
[RubyMethod("[]=")]
public static object SetElement(RubyContext/*!*/ context, IList/*!*/ self, [DefaultProtocol]int index, object value) {
RubyUtils.RequiresNotFrozen(context, self);
index = NormalizeIndex(self, index);
if (index < 0) {
throw RubyExceptions.CreateIndexError(String.Format("index {0} out of array", index));
}
if (index < self.Count) {
// TODO: conversions
self[index] = value;
} else {
ExpandList(self, index);
self.Add(value);
}
return value;
}
[RubyMethod("[]=")]
public static object SetElement(ConversionStorage<IList>/*!*/ arrayTryCast, IList/*!*/ self,
[DefaultProtocol]int index, [DefaultProtocol]int length, object value) {
RubyUtils.RequiresNotFrozen(arrayTryCast.Context, self);
if (length < 0) {
throw RubyExceptions.CreateIndexError(String.Format("negative length ({0})", length));
}
index = NormalizeIndex(self, index);
if (index < 0) {
throw RubyExceptions.CreateIndexError(String.Format("index {0} out of array", index));
}
IList valueAsList = value as IList;
if (valueAsList == null) {
valueAsList = Protocols.TryCastToArray(arrayTryCast, value);
}
if (value == null || (valueAsList != null && valueAsList.Count == 0)) {
DeleteItems(self, index, length);
} else {
if (valueAsList == null) {
Insert(arrayTryCast.Context, self, index, value);
if (length > 0) {
RemoveRange(self, index + 1, Math.Min(length, self.Count - index - 1));
}
} else {
if (value == self) {
valueAsList = new object[self.Count];
self.CopyTo(valueAsList as object[], 0);
}
ExpandList(self, index);
int limit = length > valueAsList.Count ? valueAsList.Count : length;
for (int i = 0; i < limit; i++) {
OverwriteOrAdd(self, index + i, valueAsList[i]);
}
if (length < valueAsList.Count) {
InsertRange(self, index + limit, EnumerateRange(valueAsList, limit, valueAsList.Count - limit));
}
else {
RemoveRange(self, index + limit, Math.Min(length - valueAsList.Count, self.Count - (index + limit)));
}
}
}
return value;
}
[RubyMethod("[]=")]
public static object SetElement(ConversionStorage<IList>/*!*/ arrayTryCast, ConversionStorage<int>/*!*/ fixnumCast,
IList/*!*/ self, [NotNull]Range/*!*/ range, object value) {
RubyUtils.RequiresNotFrozen(fixnumCast.Context, self);
int begin = Protocols.CastToFixnum(fixnumCast, range.Begin);
int end = Protocols.CastToFixnum(fixnumCast, range.End);
begin = begin < 0 ? begin + self.Count : begin;
if (begin < 0) {
throw RubyExceptions.CreateRangeError(String.Format("{0}..{1} out of range", begin, end));
}
end = end < 0 ? end + self.Count : end;
int count = range.ExcludeEnd ? end - begin : end - begin + 1;
return SetElement(arrayTryCast, self, begin, Math.Max(count, 0), value);
}
#endregion
#region &, |
[RubyMethod("&")]
public static RubyArray/*!*/ Intersection(RubyContext/*!*/ context, IList/*!*/ self, [DefaultProtocol]IList/*!*/ other) {
Dictionary<object, bool> items = new Dictionary<object, bool>(context.EqualityComparer);
RubyArray result = new RubyArray();
// first get the items in the RHS
foreach (object item in other) {
items[item] = true;
}
// now, go through the items in the LHS, adding ones that were also in the RHS
// this ensures that we return the items in the correct order
foreach (object item in self) {
if (items.Remove(item)) {
result.Add(item);
if (items.Count == 0) {
break; // all done
}
}
}
return result;
}
[RubyMethod("|")]
public static RubyArray/*!*/ Union(RubyContext/*!*/ context, IList/*!*/ self, [DefaultProtocol]IList other) {
var seen = new Dictionary<object, bool>(context.EqualityComparer);
var result = new RubyArray();
// Union merges the two arrays, removing duplicates
foreach (object item in self) {
if (!seen.ContainsKey(item)) {
seen.Add(item, true);
result.Add(item);
}
}
foreach (object item in other) {
if (!seen.ContainsKey(item)) {
seen.Add(item, true);
result.Add(item);
}
}
return result;
}
#endregion
#region assoc, rassoc
public static IList GetContainerOf(BinaryOpStorage/*!*/ equals, IList list, int index, object item) {
foreach (object current in list) {
IList subArray = current as IList;
if (subArray != null && subArray.Count > index) {
if (Protocols.IsEqual(equals, subArray[index], item)) {
return subArray;
}
}
}
return null;
}
[RubyMethod("assoc")]
public static IList GetContainerOfFirstItem(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
return GetContainerOf(equals, self, 0, item);
}
[RubyMethod("rassoc")]
public static IList/*!*/ GetContainerOfSecondItem(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
return GetContainerOf(equals, self, 1, item);
}
#endregion
#region collect!, map!, compact, compact!
[RubyMethod("collect!")]
[RubyMethod("map!")]
public static object CollectInPlace(RubyContext/*!*/ context, BlockParam block, IList/*!*/ self) {
Assert.NotNull(context, self);
if (self.Count > 0 && block == null) {
throw RubyExceptions.NoBlockGiven();
}
RubyUtils.RequiresNotFrozen(context, self);
int i = 0;
while (i < self.Count) {
object result;
if (block.Yield(self[i], out result)) {
return result;
}
self[i] = result;
i++;
}
return self;
}
[RubyMethod("compact")]
public static IList/*!*/ Compact(CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage, IList/*!*/ self) {
IList result = CreateResultArray(allocateStorage, self);
foreach (object item in self) {
if (item != null) {
result.Add(item);
}
}
allocateStorage.Context.TaintObjectBy<IList>(result, self);
return result;
}
[RubyMethod("compact!")]
public static IList CompactInPlace(RubyContext/*!*/ context, IList/*!*/ self) {
RubyUtils.RequiresNotFrozen(context, self);
bool changed = false;
int i = 0;
while (i < self.Count) {
if (self[i] == null) {
changed = true;
self.RemoveAt(i);
} else {
i++;
}
}
return changed ? self : null;
}
#endregion
#region delete, delete_at
public static bool Remove(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
int i = 0;
bool removed = false;
while (i < self.Count) {
if (Protocols.IsEqual(equals, self[i], item)) {
RubyUtils.RequiresNotFrozen(equals.Context, self);
self.RemoveAt(i);
removed = true;
} else {
++i;
}
}
return removed;
}
[RubyMethod("delete")]
public static object Delete(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
return Remove(equals, self, item) ? item : null;
}
[RubyMethod("delete")]
public static object Delete(BinaryOpStorage/*!*/ equals, BlockParam block, IList/*!*/ self, object item) {
bool removed = Remove(equals, self, item);
if (!removed && block != null) {
object result;
block.Yield(out result);
return result;
}
return removed ? item : null;
}
[RubyMethod("delete_at")]
public static object DeleteAt(RubyContext/*!*/ context, IList/*!*/ self, [DefaultProtocol]int index) {
RubyUtils.RequiresNotFrozen(context, self);
index = index < 0 ? index + self.Count : index;
if (index < 0 || index > self.Count) {
return null;
}
object result = GetElement(self, index);
self.RemoveAt(index);
return result;
}
[RubyMethod("delete_if")]
public static object DeleteIf(RubyContext/*!*/ context, BlockParam block, IList/*!*/ self) {
bool changed, jumped;
DeleteIf(context, block, self, out changed, out jumped);
return self;
}
private static object DeleteIf(RubyContext/*!*/ context, BlockParam block, IList/*!*/ self, out bool changed, out bool jumped) {
RubyUtils.RequiresNotFrozen(context, self);
changed = false;
jumped = false;
if (block == null && self.Count > 0) {
throw RubyExceptions.NoBlockGiven();
}
// TODO: if block jumpes the array is not modified:
int i = 0;
while (i < self.Count) {
object result;
if (block.Yield(self[i], out result)) {
jumped = true;
return result;
}
if (RubyOps.IsTrue(result)) {
changed = true;
self.RemoveAt(i);
} else {
i++;
}
}
return null;
}
[RubyMethod("reject!")]
public static object RejectInPlace(RubyContext/*!*/ context, BlockParam block, IList/*!*/ self) {
bool changed, jumped;
object result = DeleteIf(context, block, self, out changed, out jumped);
if (jumped) return result;
if (changed) return self;
return null;
}
#endregion
#region each, each_index
[RubyMethod("each")]
public static object Each(RubyContext/*!*/ context, BlockParam block, IList/*!*/ self) {
Assert.NotNull(context, self);
if (self.Count > 0 && block == null) {
throw RubyExceptions.NoBlockGiven();
}
for (int i = 0; i < self.Count; i++) {
object result;
if (block.Yield(self[i], out result)) {
return result;
}
}
return self;
}
[RubyMethod("each_index")]
public static object EachIndex(RubyContext/*!*/ context, BlockParam block, IList/*!*/ self) {
Assert.NotNull(context, self);
if (self.Count > 0 && block == null) {
throw RubyExceptions.NoBlockGiven();
}
int i = 0;
while (i < self.Count) {
object result;
if (block.Yield(i, out result)) {
return result;
}
i++;
}
return self;
}
#endregion
#region fetch
[RubyMethod("fetch")]
public static object Fetch(
ConversionStorage<int>/*!*/ fixnumCast,
BlockParam outOfRangeValueProvider,
IList/*!*/ list,
object/*!*/ index,
[Optional]object defaultValue) {
int convertedIndex = Protocols.CastToFixnum(fixnumCast, index);
if (InRangeNormalized(list, ref convertedIndex)) {
return list[convertedIndex];
}
if (outOfRangeValueProvider != null) {
if (defaultValue != Missing.Value) {
fixnumCast.Context.ReportWarning("block supersedes default value argument");
}
object result;
outOfRangeValueProvider.Yield(index, out result);
return result;
}
if (defaultValue == Missing.Value) {
throw RubyExceptions.CreateIndexError("index " + convertedIndex + " out of array");
}
return defaultValue;
}
#endregion
#region fill
[RubyMethod("fill")]
public static IList/*!*/ Fill(RubyContext/*!*/ context, IList/*!*/ self, object obj, [DefaultParameterValue(0)]int start) {
RubyUtils.RequiresNotFrozen(context, self);
// Note: Array#fill(obj, start) is not equivalent to Array#fill(obj, start, 0)
// (as per MRI behavior, the latter can expand the array if start > length, but the former doesn't)
start = Math.Max(0, NormalizeIndex(self, start));
for (int i = start; i < self.Count; i++) {
self[i] = obj;
}
return self;
}
[RubyMethod("fill")]
public static IList/*!*/ Fill(RubyContext/*!*/ context, IList/*!*/ self, object obj, int start, int length) {
RubyUtils.RequiresNotFrozen(context, self);
// Note: Array#fill(obj, start) is not equivalent to Array#fill(obj, start, 0)
// (as per MRI behavior, the latter can expand the array if start > length, but the former doesn't)
start = Math.Max(0, NormalizeIndex(self, start));
ExpandList(self, Math.Min(start, start + length));
for (int i = 0; i < length; i++) {
OverwriteOrAdd(self, start + i, obj);
}
return self;
}
[RubyMethod("fill")]
public static IList/*!*/ Fill(ConversionStorage<int>/*!*/ fixnumCast, IList/*!*/ self, object obj, object start, [DefaultParameterValue(null)]object length) {
int startFixnum = (start == null) ? 0 : Protocols.CastToFixnum(fixnumCast, start);
if (length == null) {
return Fill(fixnumCast.Context, self, obj, startFixnum);
} else {
return Fill(fixnumCast.Context, self, obj, startFixnum, Protocols.CastToFixnum(fixnumCast, length));
}
}
[RubyMethod("fill")]
public static IList/*!*/ Fill(ConversionStorage<int>/*!*/ fixnumCast, IList/*!*/ self, object obj, Range/*!*/ range) {
int begin = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.Begin));
int end = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.End));
int length = Math.Max(0, end - begin + (range.ExcludeEnd ? 0 : 1));
return Fill(fixnumCast.Context, self, obj, begin, length);
}
[RubyMethod("fill")]
public static object Fill(RubyContext/*!*/ context, [NotNull]BlockParam/*!*/ block, IList/*!*/ self, [DefaultParameterValue(0)]int start) {
RubyUtils.RequiresNotFrozen(context, self);
start = Math.Max(0, NormalizeIndex(self, start));
for (int i = start; i < self.Count; i++) {
object result;
if (block.Yield(i, out result)) {
return result;
}
self[i] = result;
}
return self;
}
[RubyMethod("fill")]
public static object Fill(RubyContext/*!*/ context, [NotNull]BlockParam/*!*/ block, IList/*!*/ self, int start, int length) {
RubyUtils.RequiresNotFrozen(context, self);
start = Math.Max(0, NormalizeIndex(self, start));
ExpandList(self, Math.Min(start, start + length));
for (int i = start; i < start + length; i++) {
object result;
if (block.Yield(i, out result)) {
return result;
}
OverwriteOrAdd(self, i, result);
}
return self;
}
[RubyMethod("fill")]
public static object Fill(ConversionStorage<int>/*!*/ fixnumCast, [NotNull]BlockParam/*!*/ block, IList/*!*/ self, object start, [DefaultParameterValue(null)]object length) {
int startFixnum = (start == null) ? 0 : Protocols.CastToFixnum(fixnumCast, start);
if (length == null) {
return Fill(fixnumCast.Context, block, self, startFixnum);
} else {
return Fill(fixnumCast.Context, block, self, startFixnum, Protocols.CastToFixnum(fixnumCast, length));
}
}
[RubyMethod("fill")]
public static object Fill(ConversionStorage<int>/*!*/ fixnumCast, [NotNull]BlockParam/*!*/ block, IList/*!*/ self, Range/*!*/ range) {
int begin = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.Begin));
int end = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.End));
int length = Math.Max(0, end - begin + (range.ExcludeEnd ? 0 : 1));
return Fill(fixnumCast.Context, block, self, begin, length);
}
#endregion
#region first, last
[RubyMethod("first")]
public static object First(IList/*!*/ self) {
return self.Count == 0 ? null : self[0];
}
[RubyMethod("first")]
public static IList/*!*/ First(IList/*!*/ self, [DefaultProtocol]int count) {
if (count < 0) {
throw RubyExceptions.CreateArgumentError("negative array size (or size too big)");
}
count = count > self.Count ? self.Count : count;
return RubyArray.Create(self as IList<object>, 0, count);
}
[RubyMethod("last")]
public static object Last(IList/*!*/ self) {
return self.Count == 0 ? null : self[self.Count - 1];
}
[RubyMethod("last")]
public static IList/*!*/ Last(IList/*!*/ self, [DefaultProtocol]int count) {
if (count < 0) {
throw RubyExceptions.CreateArgumentError("negative array size (or size too big)");
}
count = count > self.Count ? self.Count : count;
return RubyArray.Create(self as IList<object>, self.Count - count, count);
}
#endregion
#region flatten, flatten!
[MultiRuntimeAware]
private static RubyUtils.RecursionTracker _infiniteFlattenTracker = new RubyUtils.RecursionTracker();
public static bool TryFlattenArray(
CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage,
ConversionStorage<IList>/*!*/ tryToAry,
IList list, out IList/*!*/ result) {
result = CreateResultArray(allocateStorage, list);
using (IDisposable handle = _infiniteFlattenTracker.TrackObject(list)) {
if (handle == null) {
throw RubyExceptions.CreateArgumentError("tried to flatten recursive array");
}
bool flattened = false;
for (int i = 0; i < list.Count; i++) {
IList item = Protocols.TryCastToArray(tryToAry, list[i]);
if (item != null) {
flattened = true;
IList flattenedList;
TryFlattenArray(allocateStorage, tryToAry, item, out flattenedList);
if (flattenedList != null) {
AddRange(result, flattenedList);
} else {
result.Add(item);
}
} else {
result.Add(list[i]);
}
}
return flattened;
}
}
[RubyMethod("flatten")]
public static IList/*!*/ Flatten(
CallSiteStorage<Func<CallSite, RubyClass, object>>/*!*/ allocateStorage,
ConversionStorage<IList>/*!*/ tryToAry,
RubyContext/*!*/ context, IList/*!*/ self) {
IList result;
TryFlattenArray(allocateStorage, tryToAry, self, out result);
return result;
}
[RubyMethod("flatten!")]