PageRenderTime 60ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/IronPython_Main/Languages/Ruby/Libraries.LCA_RESTRICTED/Extensions/IListOps.cs

#
C# | 1979 lines | 1538 code | 347 blank | 94 comment | 384 complexity | 4f7136339172020ecf7de6feabfcb79a MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. /* ****************************************************************************
  2. *
  3. * Copyright (c) Microsoft Corporation.
  4. *
  5. * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6. * copy of the license can be found in the License.html file at the root of this distribution. If
  7. * you cannot locate the Apache License, Version 2.0, please send an email to
  8. * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. * by the terms of the Apache License, Version 2.0.
  10. *
  11. * You must not remove this notice, or any other, from this software.
  12. *
  13. *
  14. * ***************************************************************************/
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.Reflection;
  20. using System.Runtime.CompilerServices;
  21. using System.Runtime.InteropServices;
  22. using Microsoft.Scripting;
  23. using Microsoft.Scripting.Generation;
  24. using Microsoft.Scripting.Runtime;
  25. using Microsoft.Scripting.Utils;
  26. using IronRuby.Runtime;
  27. using IronRuby.Runtime.Calls;
  28. using IronRuby.Runtime.Conversions;
  29. namespace IronRuby.Builtins {
  30. using EachSite = Func<CallSite, object, Proc, object>;
  31. [RubyModule(Extends = typeof(IList), Restrictions = ModuleRestrictions.None)]
  32. [Includes(typeof(Enumerable))]
  33. public static class IListOps {
  34. #region Helpers
  35. // MRI: Some operations check frozen flag even if they don't change the array content.
  36. private static void RequireNotFrozen(IList/*!*/ self) {
  37. RubyArray array = self as RubyArray;
  38. if (array != null && array.IsFrozen) {
  39. throw RubyExceptions.CreateObjectFrozenError();
  40. }
  41. }
  42. internal static int NormalizeIndex(IList/*!*/ list, int index) {
  43. return NormalizeIndex(list.Count, index);
  44. }
  45. internal static int NormalizeIndexThrowIfNegative(IList/*!*/ list, int index) {
  46. index = NormalizeIndex(list.Count, index);
  47. if (index < 0) {
  48. throw RubyExceptions.CreateIndexError("index {0} out of array", index);
  49. }
  50. return index;
  51. }
  52. internal static int NormalizeIndex(int count, int index) {
  53. return index < 0 ? index + count : index;
  54. }
  55. internal static bool NormalizeRange(int listCount, ref int start, ref int count) {
  56. start = NormalizeIndex(listCount, start);
  57. if (start < 0 || start > listCount || count < 0) {
  58. return false;
  59. }
  60. if (count != 0) {
  61. count = start + count > listCount ? listCount - start : count;
  62. }
  63. return true;
  64. }
  65. internal static bool NormalizeRange(ConversionStorage<int>/*!*/ fixnumCast, int listCount, Range/*!*/ range, out int begin, out int count) {
  66. begin = Protocols.CastToFixnum(fixnumCast, range.Begin);
  67. int end = Protocols.CastToFixnum(fixnumCast, range.End);
  68. begin = NormalizeIndex(listCount, begin);
  69. if (begin < 0 || begin > listCount) {
  70. count = 0;
  71. return false;
  72. }
  73. end = NormalizeIndex(listCount, end);
  74. count = range.ExcludeEnd ? end - begin : end - begin + 1;
  75. return true;
  76. }
  77. private static bool InRangeNormalized(IList/*!*/ list, ref int index) {
  78. if (index < 0) {
  79. index = index + list.Count;
  80. }
  81. return index >= 0 && index < list.Count;
  82. }
  83. private static IList/*!*/ GetResultRange(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ list, int index, int count) {
  84. IList result = CreateResultArray(allocateStorage, list);
  85. int stop = index + count;
  86. for (int i = index; i < stop; i++) {
  87. result.Add(list[i]);
  88. }
  89. return result;
  90. }
  91. private static void InsertRange(IList/*!*/ list, int index, IList/*!*/ items, int start, int count) {
  92. RubyArray array;
  93. List<object> listOfObject;
  94. ICollection<object> collection;
  95. if ((array = list as RubyArray) != null) {
  96. array.InsertRange(index, items, start, count);
  97. } else if ((listOfObject = list as List<object>) != null && ((collection = items as ICollection<object>) != null) && start == 0 && count == collection.Count) {
  98. listOfObject.InsertRange(index, collection);
  99. } else {
  100. for (int i = 0; i < count; i++) {
  101. list.Insert(index + i, items[start + i]);
  102. }
  103. }
  104. }
  105. internal static void RemoveRange(IList/*!*/ collection, int index, int count) {
  106. if (count <= 1) {
  107. if (count > 0) {
  108. collection.RemoveAt(index);
  109. }
  110. return;
  111. }
  112. List<object> list;
  113. RubyArray array;
  114. if ((array = collection as RubyArray) != null) {
  115. array.RemoveRange(index, count);
  116. } else if ((list = collection as List<object>) != null) {
  117. list.RemoveRange(index, count);
  118. } else {
  119. for (int i = index + count - 1; i >= index; i--) {
  120. collection.RemoveAt(i);
  121. }
  122. }
  123. }
  124. internal static void AddRange(IList/*!*/ collection, IList/*!*/ items) {
  125. RubyArray array;
  126. int count = items.Count;
  127. if (count <= 1) {
  128. if (count > 0) {
  129. collection.Add(items[0]);
  130. } else if ((array = collection as RubyArray) != null) {
  131. array.RequireNotFrozen();
  132. }
  133. return;
  134. }
  135. array = collection as RubyArray;
  136. if (array != null) {
  137. array.AddRange(items);
  138. } else {
  139. for (int i = 0; i < count; i++) {
  140. collection.Add(items[i]);
  141. }
  142. }
  143. }
  144. private static IList/*!*/ CreateResultArray(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ list) {
  145. // RubyArray:
  146. var array = list as RubyArray;
  147. if (array != null) {
  148. return array.CreateInstance();
  149. }
  150. // interop - call a default ctor to get an instance:
  151. var allocate = allocateStorage.GetCallSite("allocate", 0);
  152. var cls = allocateStorage.Context.GetClassOf(list);
  153. var result = allocate.Target(allocate, cls) as IList;
  154. if (result != null) {
  155. return result;
  156. }
  157. throw RubyExceptions.CreateTypeError("{0}#allocate should return IList", cls.Name);
  158. }
  159. internal static IEnumerable<Int32>/*!*/ ReverseEnumerateIndexes(IList/*!*/ collection) {
  160. for (int originalSize = collection.Count, i = originalSize - 1; i >= 0; i--) {
  161. yield return i;
  162. if (collection.Count < originalSize) {
  163. i = originalSize - (originalSize - collection.Count);
  164. originalSize = collection.Count;
  165. }
  166. }
  167. }
  168. #endregion
  169. #region initialize_copy, replace, clear, to_a, to_ary
  170. [RubyMethod("replace")]
  171. [RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)]
  172. public static IList/*!*/ Replace(IList/*!*/ self, [NotNull, DefaultProtocol]IList/*!*/ other) {
  173. self.Clear();
  174. AddRange(self, other);
  175. return self;
  176. }
  177. [RubyMethod("clear")]
  178. public static IList Clear(IList/*!*/ self) {
  179. self.Clear();
  180. return self;
  181. }
  182. [RubyMethod("to_a")]
  183. [RubyMethod("to_ary")]
  184. public static RubyArray/*!*/ ToArray(IList/*!*/ self) {
  185. RubyArray list = new RubyArray(self.Count);
  186. foreach (object item in self) {
  187. list.Add(item);
  188. }
  189. return list;
  190. }
  191. #endregion
  192. #region *, +, concat
  193. [RubyMethod("*")]
  194. public static IList/*!*/ Repetition(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self, int repeat) {
  195. if (repeat < 0) {
  196. throw RubyExceptions.CreateArgumentError("negative argument");
  197. }
  198. IList result = CreateResultArray(allocateStorage, self);
  199. RubyArray array = result as RubyArray;
  200. if (array != null) {
  201. array.AddCapacity(self.Count * repeat);
  202. }
  203. for (int i = 0; i < repeat; ++i) {
  204. AddRange(result, self);
  205. }
  206. allocateStorage.Context.TaintObjectBy(result, self);
  207. return result;
  208. }
  209. [RubyMethod("*")]
  210. public static MutableString Repetition(ConversionStorage<MutableString>/*!*/ tosConversion,
  211. IList/*!*/ self, [NotNull]MutableString/*!*/ separator) {
  212. return Join(tosConversion, self, separator);
  213. }
  214. [RubyMethod("*")]
  215. public static object Repetition(UnaryOpStorage/*!*/ allocateStorage, ConversionStorage<MutableString>/*!*/ tosConversion,
  216. IList/*!*/ self, [DefaultProtocol, NotNull]Union<MutableString, int> repeat) {
  217. if (repeat.IsFixnum()) {
  218. return Repetition(allocateStorage, self, repeat.Fixnum());
  219. } else {
  220. return Repetition(tosConversion, self, repeat.String());
  221. }
  222. }
  223. [RubyMethod("+")]
  224. public static RubyArray/*!*/ Concatenate(IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
  225. RubyArray result = new RubyArray(self.Count + other.Count);
  226. AddRange(result, self);
  227. AddRange(result, other);
  228. return result;
  229. }
  230. [RubyMethod("concat")]
  231. public static IList/*!*/ Concat(IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
  232. AddRange(self, other);
  233. return self;
  234. }
  235. [RubyMethod("-")]
  236. public static RubyArray/*!*/ Difference(UnaryOpStorage/*!*/ hashStorage, BinaryOpStorage/*!*/ eqlStorage,
  237. IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
  238. RubyArray result = new RubyArray();
  239. // cost: (|self| + |other|) * (hash + eql) + dict
  240. var remove = new Dictionary<object, bool>(new EqualityComparer(hashStorage, eqlStorage));
  241. bool removeNull = false;
  242. foreach (var item in other) {
  243. if (item != null) {
  244. remove[item] = true;
  245. } else {
  246. removeNull = true;
  247. }
  248. }
  249. foreach (var item in self) {
  250. if (!(item != null ? remove.ContainsKey(item) : removeNull)) {
  251. result.Add(item);
  252. }
  253. }
  254. return result;
  255. }
  256. internal static int IndexOf(CallSite<Func<CallSite, object, object, object>>/*!*/ equalitySite, IList/*!*/ self, object item) {
  257. for (int i = 0; i < self.Count; i++) {
  258. if (Protocols.IsTrue(equalitySite.Target(equalitySite, item, self[i]))) {
  259. return i;
  260. }
  261. }
  262. return -1;
  263. }
  264. #endregion
  265. #region ==, <=>, eql?, hash
  266. [RubyMethod("==")]
  267. public static bool Equals(RespondToStorage/*!*/ respondTo, BinaryOpStorage/*!*/ equals, IList/*!*/ self, object other) {
  268. return Protocols.RespondTo(respondTo, other, "to_ary") && Protocols.IsEqual(equals, other, self);
  269. }
  270. [MultiRuntimeAware]
  271. private static RubyUtils.RecursionTracker _EqualsTracker = new RubyUtils.RecursionTracker();
  272. [RubyMethod("==")]
  273. public static bool Equals(BinaryOpStorage/*!*/ equals, IList/*!*/ self, [NotNull]IList/*!*/ other) {
  274. Assert.NotNull(self, other);
  275. if (ReferenceEquals(self, other)) {
  276. return true;
  277. }
  278. if (self.Count != other.Count) {
  279. return false;
  280. }
  281. using (IDisposable handleSelf = _EqualsTracker.TrackObject(self), handleOther = _EqualsTracker.TrackObject(other)) {
  282. if (handleSelf == null && handleOther == null) {
  283. // both arrays went recursive:
  284. return true;
  285. }
  286. var site = equals.GetCallSite("==");
  287. for (int i = 0; i < self.Count; ++i) {
  288. if (!Protocols.IsEqual(site, self[i], other[i])) {
  289. return false;
  290. }
  291. }
  292. }
  293. return true;
  294. }
  295. [MultiRuntimeAware]
  296. private static RubyUtils.RecursionTracker _ComparisonTracker = new RubyUtils.RecursionTracker();
  297. [RubyMethod("<=>")]
  298. public static object Compare(BinaryOpStorage/*!*/ comparisonStorage, ConversionStorage<IList>/*!*/ toAry, IList/*!*/ self, object other) {
  299. IList otherArray = Protocols.TryCastToArray(toAry, other);
  300. return (otherArray != null) ? Compare(comparisonStorage, self, otherArray) : null;
  301. }
  302. [RubyMethod("<=>")]
  303. public static object Compare(BinaryOpStorage/*!*/ comparisonStorage, IList/*!*/ self, [NotNull]IList/*!*/ other) {
  304. using (IDisposable handleSelf = _ComparisonTracker.TrackObject(self), handleOther = _ComparisonTracker.TrackObject(other)) {
  305. if (handleSelf == null && handleOther == null) {
  306. // both arrays went recursive:
  307. return ScriptingRuntimeHelpers.Int32ToObject(0);
  308. }
  309. int limit = Math.Min(self.Count, other.Count);
  310. var compare = comparisonStorage.GetCallSite("<=>");
  311. for (int i = 0; i < limit; i++) {
  312. object result = compare.Target(compare, self[i], other[i]);
  313. if (!(result is int) || (int)result != 0) {
  314. return result;
  315. }
  316. }
  317. return ScriptingRuntimeHelpers.Int32ToObject(Math.Sign(self.Count - other.Count));
  318. }
  319. }
  320. [RubyMethod("eql?")]
  321. public static bool HashEquals(BinaryOpStorage/*!*/ eqlStorage, IList/*!*/ self, object other) {
  322. return RubyArray.Equals(eqlStorage, self, other);
  323. }
  324. [RubyMethod("hash")]
  325. public static int GetHashCode(UnaryOpStorage/*!*/ hashStorage, ConversionStorage<int>/*!*/ fixnumCast, IList/*!*/ self) {
  326. return RubyArray.GetHashCode(hashStorage, fixnumCast, self);
  327. }
  328. #endregion
  329. #region slice, [], at
  330. [RubyMethod("[]")]
  331. [RubyMethod("slice")]
  332. public static object GetElement(IList list, [DefaultProtocol]int index) {
  333. return InRangeNormalized(list, ref index) ? list[index] : null;
  334. }
  335. [RubyMethod("[]")]
  336. [RubyMethod("slice")]
  337. public static IList GetElements(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ list, [DefaultProtocol]int index, [DefaultProtocol]int count) {
  338. if (!NormalizeRange(list.Count, ref index, ref count)) {
  339. return null;
  340. }
  341. return GetResultRange(allocateStorage, list, index, count);
  342. }
  343. [RubyMethod("[]")]
  344. [RubyMethod("slice")]
  345. public static IList GetElement(ConversionStorage<int>/*!*/ fixnumCast, UnaryOpStorage/*!*/ allocateStorage, IList array, [NotNull]Range/*!*/ range) {
  346. int start, count;
  347. if (!NormalizeRange(fixnumCast, array.Count, range, out start, out count)) {
  348. return null;
  349. }
  350. return count < 0 ? CreateResultArray(allocateStorage, array) : GetElements(allocateStorage, array, start, count);
  351. }
  352. [RubyMethod("at")]
  353. public static object At(IList/*!*/ self, [DefaultProtocol]int index) {
  354. return GetElement(self, index);
  355. }
  356. #endregion
  357. #region []=
  358. public static void ExpandList(IList list, int index) {
  359. int diff = index - list.Count;
  360. for (int i = 0; i < diff; i++) {
  361. list.Add(null);
  362. }
  363. }
  364. public static void OverwriteOrAdd(IList list, int index, object value) {
  365. if (index < list.Count) {
  366. list[index] = value;
  367. } else {
  368. list.Add(value);
  369. }
  370. }
  371. public static void DeleteItems(IList list, int index, int length) {
  372. if (index >= list.Count) {
  373. ExpandList(list, index);
  374. } else {
  375. // normalize for max length
  376. if (index + length > list.Count) {
  377. length = list.Count - index;
  378. }
  379. if (length == 0) {
  380. RequireNotFrozen(list);
  381. } else {
  382. RemoveRange(list, index, length);
  383. }
  384. }
  385. }
  386. [RubyMethod("[]=")]
  387. public static object SetElement(RubyArray/*!*/ self, [DefaultProtocol]int index, object value) {
  388. index = NormalizeIndexThrowIfNegative(self, index);
  389. if (index >= self.Count) {
  390. self.AddMultiple(index + 1 - self.Count, null);
  391. }
  392. return self[index] = value;
  393. }
  394. [RubyMethod("[]=")]
  395. public static object SetElement(IList/*!*/ self, [DefaultProtocol]int index, object value) {
  396. index = NormalizeIndexThrowIfNegative(self, index);
  397. if (index < self.Count) {
  398. self[index] = value;
  399. } else {
  400. ExpandList(self, index);
  401. self.Add(value);
  402. }
  403. return value;
  404. }
  405. [RubyMethod("[]=")]
  406. public static object SetElement(ConversionStorage<IList>/*!*/ arrayTryCast, IList/*!*/ self,
  407. [DefaultProtocol]int index, [DefaultProtocol]int length, object value) {
  408. if (length < 0) {
  409. throw RubyExceptions.CreateIndexError("negative length ({0})", length);
  410. }
  411. index = NormalizeIndexThrowIfNegative(self, index);
  412. if (value == null) {
  413. DeleteItems(self, index, length);
  414. return null;
  415. }
  416. IList valueAsList = value as IList;
  417. if (valueAsList == null) {
  418. valueAsList = Protocols.TryCastToArray(arrayTryCast, value);
  419. }
  420. if (valueAsList != null && valueAsList.Count == 0) {
  421. DeleteItems(self, index, length);
  422. } else {
  423. if (valueAsList == null) {
  424. Insert(self, index, value);
  425. if (length > 0) {
  426. RemoveRange(self, index + 1, Math.Min(length, self.Count - index - 1));
  427. }
  428. } else {
  429. if (value == self) {
  430. var newList = new object[self.Count];
  431. self.CopyTo(newList, 0);
  432. valueAsList = newList;
  433. }
  434. ExpandList(self, index);
  435. int limit = length > valueAsList.Count ? valueAsList.Count : length;
  436. for (int i = 0; i < limit; i++) {
  437. OverwriteOrAdd(self, index + i, valueAsList[i]);
  438. }
  439. if (length < valueAsList.Count) {
  440. InsertRange(self, index + limit, valueAsList, limit, valueAsList.Count - limit);
  441. } else {
  442. RemoveRange(self, index + limit, Math.Min(length - valueAsList.Count, self.Count - (index + limit)));
  443. }
  444. }
  445. }
  446. return value;
  447. }
  448. [RubyMethod("[]=")]
  449. public static object SetElement(ConversionStorage<IList>/*!*/ arrayTryCast, ConversionStorage<int>/*!*/ fixnumCast,
  450. IList/*!*/ self, [NotNull]Range/*!*/ range, object value) {
  451. int begin = Protocols.CastToFixnum(fixnumCast, range.Begin);
  452. int end = Protocols.CastToFixnum(fixnumCast, range.End);
  453. begin = begin < 0 ? begin + self.Count : begin;
  454. if (begin < 0) {
  455. throw RubyExceptions.CreateRangeError("{0}..{1} out of range", begin, end);
  456. }
  457. end = end < 0 ? end + self.Count : end;
  458. int count = range.ExcludeEnd ? end - begin : end - begin + 1;
  459. return SetElement(arrayTryCast, self, begin, Math.Max(count, 0), value);
  460. }
  461. #endregion
  462. #region &, |
  463. [RubyMethod("&")]
  464. public static RubyArray/*!*/ Intersection(UnaryOpStorage/*!*/ hashStorage, BinaryOpStorage/*!*/ eqlStorage,
  465. IList/*!*/ self, [DefaultProtocol]IList/*!*/ other) {
  466. Dictionary<object, bool> items = new Dictionary<object, bool>(new EqualityComparer(hashStorage, eqlStorage));
  467. RubyArray result = new RubyArray();
  468. // first get the items in the RHS
  469. foreach (object item in other) {
  470. items[item] = true;
  471. }
  472. // now, go through the items in the LHS, adding ones that were also in the RHS
  473. // this ensures that we return the items in the correct order
  474. foreach (object item in self) {
  475. if (items.Remove(item)) {
  476. result.Add(item);
  477. if (items.Count == 0) {
  478. break; // all done
  479. }
  480. }
  481. }
  482. return result;
  483. }
  484. private static void AddUniqueItems(IList/*!*/ list, IList/*!*/ result, Dictionary<object, bool> seen, ref bool nilSeen) {
  485. foreach (object item in list) {
  486. if (item == null) {
  487. if (!nilSeen) {
  488. nilSeen = true;
  489. result.Add(null);
  490. }
  491. continue;
  492. }
  493. if (!seen.ContainsKey(item)) {
  494. seen.Add(item, true);
  495. result.Add(item);
  496. }
  497. }
  498. }
  499. [RubyMethod("|")]
  500. public static RubyArray/*!*/ Union(UnaryOpStorage/*!*/ hashStorage, BinaryOpStorage/*!*/ eqlStorage,
  501. IList/*!*/ self, [DefaultProtocol]IList other) {
  502. var seen = new Dictionary<object, bool>(new EqualityComparer(hashStorage, eqlStorage));
  503. bool nilSeen = false;
  504. var result = new RubyArray();
  505. // Union merges the two arrays, removing duplicates
  506. AddUniqueItems(self, result, seen, ref nilSeen);
  507. AddUniqueItems(other, result, seen, ref nilSeen);
  508. return result;
  509. }
  510. #endregion
  511. #region assoc, rassoc
  512. public static IList GetContainerOf(BinaryOpStorage/*!*/ equals, IList list, int index, object item) {
  513. foreach (object current in list) {
  514. IList subArray = current as IList;
  515. if (subArray != null && subArray.Count > index) {
  516. if (Protocols.IsEqual(equals, subArray[index], item)) {
  517. return subArray;
  518. }
  519. }
  520. }
  521. return null;
  522. }
  523. [RubyMethod("assoc")]
  524. public static IList GetContainerOfFirstItem(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
  525. return GetContainerOf(equals, self, 0, item);
  526. }
  527. [RubyMethod("rassoc")]
  528. public static IList/*!*/ GetContainerOfSecondItem(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
  529. return GetContainerOf(equals, self, 1, item);
  530. }
  531. #endregion
  532. #region collect!, map!, compact, compact!
  533. [RubyMethod("collect!")]
  534. [RubyMethod("map!")]
  535. public static object CollectInPlace(BlockParam collector, IList/*!*/ self) {
  536. return (collector != null) ? CollectInPlaceImpl(collector, self) : new Enumerator((_, block) => CollectInPlaceImpl(block, self));
  537. }
  538. private static object CollectInPlaceImpl(BlockParam/*!*/ collector, IList/*!*/ self) {
  539. int i = 0;
  540. while (i < self.Count) {
  541. object result;
  542. if (collector.Yield(self[i], out result)) {
  543. return result;
  544. }
  545. self[i] = result;
  546. i++;
  547. }
  548. return self;
  549. }
  550. [RubyMethod("compact")]
  551. public static IList/*!*/ Compact(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self) {
  552. IList result = CreateResultArray(allocateStorage, self);
  553. foreach (object item in self) {
  554. if (item != null) {
  555. result.Add(item);
  556. }
  557. }
  558. allocateStorage.Context.TaintObjectBy(result, self);
  559. return result;
  560. }
  561. [RubyMethod("compact!")]
  562. public static IList CompactInPlace(IList/*!*/ self) {
  563. RequireNotFrozen(self);
  564. bool changed = false;
  565. int i = 0;
  566. while (i < self.Count) {
  567. if (self[i] == null) {
  568. changed = true;
  569. self.RemoveAt(i);
  570. } else {
  571. i++;
  572. }
  573. }
  574. return changed ? self : null;
  575. }
  576. #endregion
  577. #region delete, delete_at, reject, reject!
  578. public static bool Remove(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
  579. int i = 0;
  580. bool removed = false;
  581. while (i < self.Count) {
  582. if (Protocols.IsEqual(equals, self[i], item)) {
  583. self.RemoveAt(i);
  584. removed = true;
  585. } else {
  586. i++;
  587. }
  588. }
  589. return removed;
  590. }
  591. [RubyMethod("delete")]
  592. public static object Delete(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
  593. return Remove(equals, self, item) ? item : null;
  594. }
  595. [RubyMethod("delete")]
  596. public static object Delete(BinaryOpStorage/*!*/ equals, BlockParam block, IList/*!*/ self, object item) {
  597. bool removed = Remove(equals, self, item);
  598. if (!removed && block != null) {
  599. object result;
  600. block.Yield(out result);
  601. return result;
  602. }
  603. return removed ? item : null;
  604. }
  605. [RubyMethod("delete_at")]
  606. public static object DeleteAt(IList/*!*/ self, [DefaultProtocol]int index) {
  607. index = index < 0 ? index + self.Count : index;
  608. if (index < 0 || index >= self.Count) {
  609. return null;
  610. }
  611. object result = GetElement(self, index);
  612. self.RemoveAt(index);
  613. return result;
  614. }
  615. [RubyMethod("delete_if")]
  616. public static object DeleteIf(BlockParam block, IList/*!*/ self) {
  617. return (block != null) ? DeleteIfImpl(block, self) : new Enumerator((_, innerBlock) => DeleteIfImpl(innerBlock, self));
  618. }
  619. private static object DeleteIfImpl(BlockParam/*!*/ block, IList/*!*/ self) {
  620. bool changed, jumped;
  621. DeleteIf(block, self, out changed, out jumped);
  622. return self;
  623. }
  624. [RubyMethod("reject!")]
  625. public static object RejectInPlace(BlockParam block, IList/*!*/ self) {
  626. return (block != null) ? RejectInPlaceImpl(block, self) : new Enumerator((_, innerBlock) => RejectInPlaceImpl(innerBlock, self));
  627. }
  628. private static object RejectInPlaceImpl(BlockParam/*!*/ block, IList/*!*/ self) {
  629. bool changed, jumped;
  630. object result = DeleteIf(block, self, out changed, out jumped);
  631. return jumped ? result : changed ? self : null;
  632. }
  633. [RubyMethod("reject")]
  634. public static object Reject(CallSiteStorage<EachSite>/*!*/ each, UnaryOpStorage/*!*/ allocate,
  635. BlockParam predicate, IList/*!*/ self) {
  636. return (predicate != null) ? RejectImpl(each, allocate, predicate, self) : new Enumerator((_, block) => RejectImpl(each, allocate, block, self));
  637. }
  638. private static object RejectImpl(CallSiteStorage<EachSite>/*!*/ each, UnaryOpStorage/*!*/ allocate,
  639. BlockParam/*!*/ predicate, IList/*!*/ self) {
  640. IList result = CreateResultArray(allocate, self);
  641. for (int i = 0; i < self.Count; i++) {
  642. object item = self[i];
  643. object blockResult;
  644. if (predicate.Yield(item, out blockResult)) {
  645. return blockResult;
  646. }
  647. if (RubyOps.IsFalse(blockResult)) {
  648. result.Add(item);
  649. }
  650. }
  651. return result;
  652. }
  653. private static object DeleteIf(BlockParam/*!*/ block, IList/*!*/ self, out bool changed, out bool jumped) {
  654. Assert.NotNull(block, self);
  655. changed = false;
  656. jumped = false;
  657. RequireNotFrozen(self);
  658. // TODO: if block jumps the array is not modified:
  659. int i = 0;
  660. while (i < self.Count) {
  661. object result;
  662. if (block.Yield(self[i], out result)) {
  663. jumped = true;
  664. return result;
  665. }
  666. if (RubyOps.IsTrue(result)) {
  667. changed = true;
  668. self.RemoveAt(i);
  669. } else {
  670. i++;
  671. }
  672. }
  673. return null;
  674. }
  675. #endregion
  676. #region each, each_index
  677. [RubyMethod("each")]
  678. public static object Each(BlockParam block, IList/*!*/ self) {
  679. if (self.Count > 0 && block == null) {
  680. throw RubyExceptions.NoBlockGiven();
  681. }
  682. for (int i = 0; i < self.Count; i++) {
  683. object result;
  684. if (block.Yield(self[i], out result)) {
  685. return result;
  686. }
  687. }
  688. return self;
  689. }
  690. [RubyMethod("each_index")]
  691. public static object EachIndex(BlockParam block, IList/*!*/ self) {
  692. if (self.Count > 0 && block == null) {
  693. throw RubyExceptions.NoBlockGiven();
  694. }
  695. int i = 0;
  696. while (i < self.Count) {
  697. object result;
  698. if (block.Yield(i, out result)) {
  699. return result;
  700. }
  701. i++;
  702. }
  703. return self;
  704. }
  705. #endregion
  706. #region fetch
  707. [RubyMethod("fetch")]
  708. public static object Fetch(
  709. ConversionStorage<int>/*!*/ fixnumCast,
  710. BlockParam outOfRangeValueProvider,
  711. IList/*!*/ list,
  712. object/*!*/ index,
  713. [Optional]object defaultValue) {
  714. int convertedIndex = Protocols.CastToFixnum(fixnumCast, index);
  715. if (InRangeNormalized(list, ref convertedIndex)) {
  716. return list[convertedIndex];
  717. }
  718. if (outOfRangeValueProvider != null) {
  719. if (defaultValue != Missing.Value) {
  720. fixnumCast.Context.ReportWarning("block supersedes default value argument");
  721. }
  722. object result;
  723. outOfRangeValueProvider.Yield(index, out result);
  724. return result;
  725. }
  726. if (defaultValue == Missing.Value) {
  727. throw RubyExceptions.CreateIndexError("index {0} out of array", convertedIndex);
  728. }
  729. return defaultValue;
  730. }
  731. #endregion
  732. #region fill
  733. [RubyMethod("fill")]
  734. public static IList/*!*/ Fill(IList/*!*/ self, object obj, [DefaultParameterValue(0)]int start) {
  735. // Note: Array#fill(obj, start) is not equivalent to Array#fill(obj, start, 0)
  736. // (as per MRI behavior, the latter can expand the array if start > length, but the former doesn't)
  737. start = Math.Max(0, NormalizeIndex(self, start));
  738. for (int i = start; i < self.Count; i++) {
  739. self[i] = obj;
  740. }
  741. return self;
  742. }
  743. [RubyMethod("fill")]
  744. public static IList/*!*/ Fill(IList/*!*/ self, object obj, int start, int length) {
  745. // Note: Array#fill(obj, start) is not equivalent to Array#fill(obj, start, 0)
  746. // (as per MRI behavior, the latter can expand the array if start > length, but the former doesn't)
  747. start = Math.Max(0, NormalizeIndex(self, start));
  748. ExpandList(self, Math.Min(start, start + length));
  749. for (int i = 0; i < length; i++) {
  750. OverwriteOrAdd(self, start + i, obj);
  751. }
  752. return self;
  753. }
  754. [RubyMethod("fill")]
  755. public static IList/*!*/ Fill(ConversionStorage<int>/*!*/ fixnumCast, IList/*!*/ self, object obj, object start, [DefaultParameterValue(null)]object length) {
  756. int startFixnum = (start == null) ? 0 : Protocols.CastToFixnum(fixnumCast, start);
  757. if (length == null) {
  758. return Fill(self, obj, startFixnum);
  759. } else {
  760. return Fill(self, obj, startFixnum, Protocols.CastToFixnum(fixnumCast, length));
  761. }
  762. }
  763. [RubyMethod("fill")]
  764. public static IList/*!*/ Fill(ConversionStorage<int>/*!*/ fixnumCast, IList/*!*/ self, object obj, [NotNull]Range/*!*/ range) {
  765. int begin = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.Begin));
  766. int end = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.End));
  767. int length = Math.Max(0, end - begin + (range.ExcludeEnd ? 0 : 1));
  768. return Fill(self, obj, begin, length);
  769. }
  770. [RubyMethod("fill")]
  771. public static object Fill([NotNull]BlockParam/*!*/ block, IList/*!*/ self, [DefaultParameterValue(0)]int start) {
  772. start = Math.Max(0, NormalizeIndex(self, start));
  773. for (int i = start; i < self.Count; i++) {
  774. object result;
  775. if (block.Yield(i, out result)) {
  776. return result;
  777. }
  778. self[i] = result;
  779. }
  780. return self;
  781. }
  782. [RubyMethod("fill")]
  783. public static object Fill([NotNull]BlockParam/*!*/ block, IList/*!*/ self, int start, int length) {
  784. start = Math.Max(0, NormalizeIndex(self, start));
  785. ExpandList(self, Math.Min(start, start + length));
  786. for (int i = start; i < start + length; i++) {
  787. object result;
  788. if (block.Yield(i, out result)) {
  789. return result;
  790. }
  791. OverwriteOrAdd(self, i, result);
  792. }
  793. return self;
  794. }
  795. [RubyMethod("fill")]
  796. public static object Fill(ConversionStorage<int>/*!*/ fixnumCast, [NotNull]BlockParam/*!*/ block, IList/*!*/ self, object start, [DefaultParameterValue(null)]object length) {
  797. int startFixnum = (start == null) ? 0 : Protocols.CastToFixnum(fixnumCast, start);
  798. if (length == null) {
  799. return Fill(block, self, startFixnum);
  800. } else {
  801. return Fill(block, self, startFixnum, Protocols.CastToFixnum(fixnumCast, length));
  802. }
  803. }
  804. [RubyMethod("fill")]
  805. public static object Fill(ConversionStorage<int>/*!*/ fixnumCast, [NotNull]BlockParam/*!*/ block, IList/*!*/ self, [NotNull]Range/*!*/ range) {
  806. int begin = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.Begin));
  807. int end = NormalizeIndex(self, Protocols.CastToFixnum(fixnumCast, range.End));
  808. int length = Math.Max(0, end - begin + (range.ExcludeEnd ? 0 : 1));
  809. return Fill(block, self, begin, length);
  810. }
  811. #endregion
  812. #region first, last
  813. [RubyMethod("first")]
  814. public static object First(IList/*!*/ self) {
  815. return self.Count == 0 ? null : self[0];
  816. }
  817. [RubyMethod("first")]
  818. public static IList/*!*/ First(IList/*!*/ self, [DefaultProtocol]int count) {
  819. if (count < 0) {
  820. throw RubyExceptions.CreateArgumentError("negative array size (or size too big)");
  821. }
  822. if (count > self.Count) {
  823. count = self.Count;
  824. }
  825. return new RubyArray(self, 0, count);
  826. }
  827. [RubyMethod("last")]
  828. public static object Last(IList/*!*/ self) {
  829. return self.Count == 0 ? null : self[self.Count - 1];
  830. }
  831. [RubyMethod("last")]
  832. public static IList/*!*/ Last(IList/*!*/ self, [DefaultProtocol]int count) {
  833. if (count < 0) {
  834. throw RubyExceptions.CreateArgumentError("negative array size (or size too big)");
  835. }
  836. if (count > self.Count) {
  837. count = self.Count;
  838. }
  839. return new RubyArray(self, self.Count - count, count);
  840. }
  841. #endregion
  842. #region flatten, flatten!
  843. private static int IndexOfList(ConversionStorage<IList>/*!*/ tryToAry, IList/*!*/ list, int start, out IList listItem) {
  844. for (int i = start; i < list.Count; i++) {
  845. listItem = Protocols.TryCastToArray(tryToAry, list[i]);
  846. if (listItem != null) {
  847. return i;
  848. }
  849. }
  850. listItem = null;
  851. return -1;
  852. }
  853. /// <summary>
  854. /// Enumerates all items of the list recursively - if there are any items convertible to IList the items of that lists are enumerated as well.
  855. /// Returns null if there are no nested lists and so the list can be enumerated using a standard enumerator.
  856. /// </summary>
  857. public static IEnumerable<object> EnumerateRecursively(ConversionStorage<IList>/*!*/ tryToAry, IList/*!*/ list, Func<IList, object>/*!*/ loopDetected) {
  858. IList nested;
  859. int nestedIndex = IndexOfList(tryToAry, list, 0, out nested);
  860. if (nestedIndex == -1) {
  861. return null;
  862. }
  863. return EnumerateRecursively(tryToAry, list, list, nested, nestedIndex, loopDetected);
  864. }
  865. private static IEnumerable<object>/*!*/ EnumerateRecursively(ConversionStorage<IList>/*!*/ tryToAry, IList/*!*/ root,
  866. IList/*!*/ list, IList nested, int nestedIndex, Func<IList, object>/*!*/ loopDetected) {
  867. var worklist = new Stack<KeyValuePair<IList, int>>();
  868. var recursionPath = new Dictionary<object, bool>(ReferenceEqualityComparer.Instance);
  869. int start = 0;
  870. while (true) {
  871. if (nestedIndex >= 0) {
  872. // push a workitem for the items following the nested list:
  873. if (nestedIndex < list.Count - 1) {
  874. worklist.Push(new KeyValuePair<IList, int>(list, nestedIndex + 1));
  875. }
  876. // yield items preceding the nested list:
  877. for (int i = start; i < nestedIndex; i++) {
  878. yield return list[i];
  879. }
  880. // push a workitem for the nested list:
  881. if (nestedIndex != -1) {
  882. worklist.Push(new KeyValuePair<IList, int>(nested, 0));
  883. }
  884. } else {
  885. // there is no nested list => yield all remaining items:
  886. for (int i = start; i < list.Count; i++) {
  887. yield return list[i];
  888. }
  889. }
  890. // finished nested list workitem:
  891. if (start == 0) {
  892. recursionPath.Remove(list);
  893. }
  894. next:
  895. if (worklist.Count == 0) {
  896. break;
  897. }
  898. var workitem = worklist.Pop();
  899. list = workitem.Key;
  900. start = workitem.Value;
  901. // starting nested workitem:
  902. if (start == 0) {
  903. if (ReferenceEquals(nested, root) || recursionPath.ContainsKey(nested)) {
  904. yield return loopDetected(nested);
  905. goto next;
  906. } else {
  907. recursionPath.Add(nested, true);
  908. }
  909. }
  910. nestedIndex = IndexOfList(tryToAry, list, start, out nested);
  911. }
  912. }
  913. [RubyMethod("flatten")]
  914. public static IList/*!*/ Flatten(UnaryOpStorage/*!*/ allocateStorage, ConversionStorage<IList>/*!*/ tryToAry, IList/*!*/ self) {
  915. IList result = CreateResultArray(allocateStorage, self);
  916. var recEnum = EnumerateRecursively(tryToAry, self, (_) => { throw RubyExceptions.CreateArgumentError("tried to flatten recursive array"); });
  917. if (recEnum != null) {
  918. foreach (var item in recEnum) {
  919. result.Add(item);
  920. }
  921. } else {
  922. AddRange(result, self);
  923. }
  924. return result;
  925. }
  926. [RubyMethod("flatten!")]
  927. public static IList FlattenInPlace(ConversionStorage<IList>/*!*/ tryToAry, RubyArray/*!*/ self) {
  928. self.RequireNotFrozen();
  929. return FlattenInPlace(tryToAry, (IList)self);
  930. }
  931. [RubyMethod("flatten!")]
  932. public static IList FlattenInPlace(ConversionStorage<IList>/*!*/ tryToAry, IList/*!*/ self) {
  933. IList nested;
  934. int nestedIndex = IndexOfList(tryToAry, self, 0, out nested);
  935. if (nestedIndex == -1) {
  936. return null;
  937. }
  938. var remaining = new object[self.Count - nestedIndex];
  939. for (int i = 0, j = nestedIndex; i < remaining.Length; i++) {
  940. remaining[i] = self[j++];
  941. }
  942. bool isRecursive = false;
  943. var recEnum = EnumerateRecursively(tryToAry, self, remaining, nested, 0, (rec) => {
  944. isRecursive = true;
  945. return rec;
  946. });
  947. // rewrite items following the first nested list (including the list):
  948. int itemCount = nestedIndex;
  949. foreach (var item in recEnum) {
  950. if (itemCount < self.Count) {
  951. self[itemCount] = item;
  952. } else {
  953. self.Add(item);
  954. }
  955. itemCount++;
  956. }
  957. // empty arrays can make the list shrink:
  958. while (self.Count > itemCount) {
  959. self.RemoveAt(self.Count - 1);
  960. }
  961. if (isRecursive) {
  962. throw RubyExceptions.CreateArgumentError("tried to flatten recursive array");
  963. }
  964. return self;
  965. }
  966. #endregion
  967. #region include?, find_index/index, rindex
  968. [RubyMethod("include?")]
  969. public static bool Include(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
  970. return FindIndex(equals, null, self, item) != null;
  971. }
  972. [RubyMethod("find_index")]
  973. [RubyMethod("index")]
  974. public static Enumerator/*!*/ GetFindIndexEnumerator(BlockParam predicate, IList/*!*/ self) {
  975. Debug.Assert(predicate == null);
  976. throw new NotImplementedError("TODO: find_index enumerator");
  977. }
  978. [RubyMethod("find_index")]
  979. [RubyMethod("index")]
  980. public static object FindIndex([NotNull]BlockParam/*!*/ predicate, IList/*!*/ self) {
  981. for (int i = 0; i < self.Count; i++) {
  982. object blockResult;
  983. if (predicate.Yield(self[i], out blockResult)) {
  984. return blockResult;
  985. }
  986. if (Protocols.IsTrue(blockResult)) {
  987. return ScriptingRuntimeHelpers.Int32ToObject(i);
  988. }
  989. }
  990. return null;
  991. }
  992. [RubyMethod("find_index")]
  993. [RubyMethod("index")]
  994. public static object FindIndex(BinaryOpStorage/*!*/ equals, BlockParam predicate, IList/*!*/ self, object value) {
  995. if (predicate != null) {
  996. equals.Context.ReportWarning("given block not used");
  997. }
  998. for (int i = 0; i < self.Count; i++) {
  999. if (Protocols.IsEqual(equals, self[i], value)) {
  1000. return ScriptingRuntimeHelpers.Int32ToObject(i);
  1001. }
  1002. }
  1003. return null;
  1004. }
  1005. [RubyMethod("rindex")]
  1006. public static object ReverseIndex([NotNull]BlockParam/*!*/ predicate, IList/*!*/ self) {
  1007. foreach (int i in IListOps.ReverseEnumerateIndexes(self)) {
  1008. object blockResult;
  1009. if (predicate.Yield(self[i], out blockResult)) {
  1010. return blockResult;
  1011. }
  1012. if (Protocols.IsTrue(blockResult)) {
  1013. return ScriptingRuntimeHelpers.Int32ToObject(i);
  1014. }
  1015. }
  1016. return null;
  1017. }
  1018. [RubyMethod("rindex")]
  1019. public static object ReverseIndex(BinaryOpStorage/*!*/ equals, BlockParam predicate, IList/*!*/ self, object item) {
  1020. if (predicate != null) {
  1021. equals.Context.ReportWarning("given block not used");
  1022. }
  1023. foreach (int i in IListOps.ReverseEnumerateIndexes(self)) {
  1024. if (Protocols.IsEqual(equals, self[i], item)) {
  1025. return ScriptingRuntimeHelpers.Int32ToObject(i);
  1026. }
  1027. }
  1028. return null;
  1029. }
  1030. #endregion
  1031. #region indexes, indices, values_at
  1032. [RubyMethod("indexes")]
  1033. [RubyMethod("indices")]
  1034. public static object Indexes(ConversionStorage<int>/*!*/ fixnumCast,
  1035. UnaryOpStorage/*!*/ allocateStorage,
  1036. IList/*!*/ self, params object[]/*!*/ values) {
  1037. fixnumCast.Context.ReportWarning("Array#indexes and Array#indices are deprecated; use Array#values_at");
  1038. RubyArray result = new RubyArray();
  1039. for (int i = 0; i < values.Length; ++i) {
  1040. Range range = values[i] as Range;
  1041. if (range != null) {
  1042. IList fragment = GetElement(fixnumCast, allocateStorage, self, range);
  1043. if (fragment != null) {
  1044. result.Add(fragment);
  1045. }
  1046. } else {
  1047. result.Add(GetElement(self, Protocols.CastToFixnum(fixnumCast, values[i])));
  1048. }
  1049. }
  1050. return result;
  1051. }
  1052. [RubyMethod("values_at")]
  1053. public static RubyArray/*!*/ ValuesAt(ConversionStorage<int>/*!*/ fixnumCast,
  1054. UnaryOpStorage/*!*/ allocateStorage,
  1055. IList/*!*/ self, params object[]/*!*/ values) {
  1056. RubyArray result = new RubyArray();
  1057. for (int i = 0; i < values.Length; i++) {
  1058. Range range = values[i] as Range;
  1059. if (range != null) {
  1060. int start, count;
  1061. if (!NormalizeRange(fixnumCast, self.Count, range, out start, out count)) {
  1062. continue;
  1063. }
  1064. if (count > 0) {
  1065. result.AddRange(GetElements(allocateStorage, self, start, count));
  1066. if (start + count >= self.Count) {
  1067. result.Add(null);
  1068. }
  1069. }
  1070. } else {
  1071. result.Add(GetElement(self, Protocols.CastToFixnum(fixnumCast, values[i])));
  1072. }
  1073. }
  1074. return result;
  1075. }
  1076. #endregion
  1077. #region join, to_s, inspect
  1078. private static void JoinRecursive(ConversionStorage<MutableString>/*!…

Large files files are truncated, but you can click here to view the full file