예제 #1
0
        public static object Map(CallSiteStorage <EachSite> /*!*/ each, BlockParam collector, object self)
        {
            RubyArray resultArray = new RubyArray();
            object    result      = resultArray;

            Each(each, self, Proc.Create(each.Context, delegate(BlockParam /*!*/ selfBlock, object _, object item) {
                if (collector != null)
                {
                    if (collector.Yield(item, out item))
                    {
                        result = item;
                        return(selfBlock.PropagateFlow(collector, item));
                    }
                }
                resultArray.Add(item);
                return(null);
            }));
            return(result);
        }
예제 #2
0
        internal RubyInputProvider(RubyContext /*!*/ context, ICollection <string> /*!*/ arguments, RubyEncoding /*!*/ encoding)
        {
            Assert.NotNull(context, encoding);
            Assert.NotNullItems(arguments);
            _context = context;

            var args = new RubyArray();

            foreach (var arg in arguments)
            {
                ExpandArgument(args, arg, encoding);
            }

            _commandLineArguments = args;
            _lastInputLineNumber  = 1;
            _currentFileIndex     = -1;
            _singleton            = new object();
            _defaultMode          = IOMode.ReadOnly;
        }
예제 #3
0
        public static object Zip(CallSiteStorage <EachSite> /*!*/ each, BlockParam block, object self, [DefaultProtocol, NotNullItems] params IList /*!*/[] /*!*/ args)
        {
            RubyArray results = (block == null) ? new RubyArray() : null;
            object    result  = results;

            int index = 0;

            Each(each, self, Proc.Create(each.Context, delegate(BlockParam /*!*/ selfBlock, object _, object item) {
                // Collect items
                RubyArray array = new RubyArray(args.Length + 1);
                array.Add(item);
                foreach (IList otherArray in args)
                {
                    if (index < otherArray.Count)
                    {
                        array.Add(otherArray[index]);
                    }
                    else
                    {
                        array.Add(null);
                    }
                }

                index += 1;

                if (block != null)
                {
                    object blockResult;
                    if (block.Yield(array, out blockResult))
                    {
                        result = blockResult;
                        return(selfBlock.PropagateFlow(block, blockResult));
                    }
                }
                else
                {
                    results.Add(array);
                }
                return(null);
            }));

            return(result);
        }
예제 #4
0
        public static RubyArray /*!*/ ValuesAt(RubyStruct /*!*/ self, [NotNull] params object[] values)
        {
            RubyArray result = new RubyArray();

            object[] data = self.Values;

            for (int i = 0; i < values.Length; ++i)
            {
                Range range = values[i] as Range;
                if (range != null)
                {
                    bool excludeEnd;
                    int  begin, end;
                    Protocols.ConvertToIntegerRange(self.Class.Context, range, out begin, out end, out excludeEnd);

                    if (excludeEnd)
                    {
                        end -= 1;
                    }

                    begin = NormalizeIndex(data.Length, begin);
                    end   = NormalizeIndex(data.Length, end);
                    Debug.Assert(end - begin <= data.Length); // because we normalized the indicies

                    if (end - begin > 0)
                    {
                        result.Capacity += (end - begin);
                        for (int j = begin; j <= end; j++)
                        {
                            result.Add(data[j]);
                        }
                    }
                }
                else
                {
                    int index = NormalizeIndex(data.Length, Protocols.CastToFixnum(self.Class.Context, values[i]));
                    result.Add(data[index]);
                }
            }

            return(result);
        }
예제 #5
0
        public static object Shift(RubyContext /*!*/ context, object /*!*/ self)
        {
            PlatformAdaptationLayer pal       = context.DomainManager.Platform;
            IDictionary             variables = pal.GetEnvironmentVariables();

            if (variables.Count == 0)
            {
                return(null);
            }
            RubyArray result = new RubyArray(2);

            foreach (DictionaryEntry entry in pal.GetEnvironmentVariables())
            {
                result.Add(FrozenString(context, entry.Key));
                result.Add(FrozenString(context, entry.Value));
                SetEnvironmentVariable(context, (string)entry.Key, null);
                break;
            }
            return(result);
        }
예제 #6
0
        private static object Reinitialize([NotNull] BlockParam /*!*/ block, RubyArray /*!*/ self, int size)
        {
            if (size < 0)
            {
                throw RubyExceptions.CreateArgumentError("negative array size");
            }

            self.Clear();
            for (int i = 0; i < size; i++)
            {
                object item;
                if (block.Yield(i, out item))
                {
                    return(item);
                }
                self.Add(item);
            }

            return(self);
        }
예제 #7
0
        public static RubyArray /*!*/ ValuesAt(ConversionStorage <int> /*!*/ fixnumCast, RubyStruct /*!*/ self, params object[] /*!*/ values)
        {
            RubyArray result = new RubyArray();

            object[] data = self.Values;

            for (int i = 0; i < values.Length; ++i)
            {
                Range range = values[i] as Range;
                if (range != null)
                {
                    int begin = Protocols.CastToFixnum(fixnumCast, range.Begin);
                    int end   = Protocols.CastToFixnum(fixnumCast, range.End);

                    if (range.ExcludeEnd)
                    {
                        end -= 1;
                    }

                    begin = NormalizeIndex(data.Length, begin);
                    end   = NormalizeIndex(data.Length, end);
                    Debug.Assert(end - begin <= data.Length); // because we normalized the indicies

                    if (end - begin > 0)
                    {
                        result.AddCapacity(end - begin);
                        for (int j = begin; j <= end; j++)
                        {
                            result.Add(data[j]);
                        }
                    }
                }
                else
                {
                    int index = NormalizeIndex(data.Length, Protocols.CastToFixnum(fixnumCast, values[i]));
                    result.Add(data[index]);
                }
            }

            return(result);
        }
예제 #8
0
        private void ExpandArgument(RubyArray /*!*/ args, string /*!*/ arg)
        {
            if (arg.IndexOf('*') != -1 || arg.IndexOf('?') != -1)
            {
                bool added = false;
                foreach (string path in Glob.GlobResults(_context, arg, 0))
                {
                    args.Add(MutableString.Create(path));
                    added = true;
                }

                if (!added)
                {
                    args.Add(MutableString.Create(arg));
                }
            }
            else
            {
                args.Add(MutableString.Create(arg));
            }
        }
예제 #9
0
        public static RubyArray Grep(RubyContext /*!*/ context, BlockParam action, object self, object pattern)
        {
            RubyArray result = new RubyArray();

            Each(context, self, Proc.Create(context, delegate(BlockParam /*!*/ selfBlock, object item) {
                if (RubySites.CaseEqual(context, pattern, item))
                {
                    if (action != null)
                    {
                        if (action.Yield(item, out item))
                        {
                            return(item);
                        }
                    }
                    result.Add(item);
                }
                return(null);
            }));

            return(result);
        }
예제 #10
0
        public static object Select(RubyContext /*!*/ context, BlockParam block, IDictionary <object, object> /*!*/ self)
        {
            RubyArray list = new RubyArray();

            foreach (var pair in CopyKeyValuePairs(self))
            {
                object result;
                if (block.Yield(CustomStringDictionary.ObjToNull(pair.Key), pair.Value, out result))
                {
                    return(result);
                }

                // Select the key, unless 'false' or 'nil' is returned
                if (RubyOps.IsTrue(result))
                {
                    list.Add(MakeArray(pair));
                }
            }

            return(list);
        }
예제 #11
0
        public static object Shift(RubyContext /*!*/ context, object /*!*/ self)
        {
            PlatformAdaptationLayer pal       = context.DomainManager.Platform;
            IDictionary             variables = pal.GetEnvironmentVariables();

            if (variables.Count == 0)
            {
                return(null);
            }
            RubyArray result = new RubyArray(2);

            foreach (DictionaryEntry entry in pal.GetEnvironmentVariables())
            {
                string key = entry.Key.ToString();
                result.Add(MutableString.Create(key).Freeze());
                result.Add(MutableString.Create(entry.Value.ToString()).Freeze());
                pal.SetEnvironmentVariable(key, null);
                break;
            }
            return(result);
        }
예제 #12
0
        private void ExpandArgument(RubyArray /*!*/ args, string /*!*/ arg, RubyEncoding /*!*/ encoding)
        {
            if (arg.IndexOf('*') != -1 || arg.IndexOf('?') != -1)
            {
                bool added = false;
                foreach (string path in Glob.GetMatches(_context.DomainManager.Platform, arg, 0))
                {
                    args.Add(MutableString.Create(path, encoding));
                    added = true;
                }

                if (!added)
                {
                    args.Add(MutableString.Create(arg, encoding));
                }
            }
            else
            {
                args.Add(MutableString.Create(arg, encoding));
            }
        }
예제 #13
0
        public static object Select([NotNull] BlockParam /*!*/ block, MatchData /*!*/ self)
        {
            RubyArray result = new RubyArray();

            for (int i = 0; i < self.GroupCount; i++)
            {
                MutableString value = self.GetGroupValue(i);

                object blockResult;
                if (block.Yield(value, out blockResult))
                {
                    return(blockResult);
                }

                if (RubyOps.IsTrue(blockResult))
                {
                    result.Add(value);
                }
            }
            return(result);
        }
예제 #14
0
        public static bool Equal(
            UnaryOpStorage /*!*/ messageStorage, UnaryOpStorage /*!*/ backtraceStorage, BinaryOpStorage /*!*/ stringEqlStorage,
            BinaryOpStorage /*!*/ arrayEqlStorage, RespondToStorage /*!*/ respondTo, Exception /*!*/ self, object /*!*/ other)
        {
            if (!Protocols.RespondTo(respondTo, other, "message") || !Protocols.RespondTo(respondTo, other, "backtrace"))
            {
                return(false);
            }

            var messageSite  = messageStorage.GetCallSite("message");
            var selfMessage  = messageSite.Target(messageSite, self);
            var otherMessage = messageSite.Target(messageSite, other);

            var backtraceSite  = backtraceStorage.GetCallSite("backtrace");
            var selfBacktrace  = backtraceSite.Target(backtraceSite, self) as System.Collections.IList;
            var otherBacktrace = backtraceSite.Target(backtraceSite, other);

            var stringEqlSite = stringEqlStorage.GetCallSite("==");

            return(true.Equals(stringEqlSite.Target(stringEqlSite, selfMessage, otherMessage)) &&
                   RubyArray.Equals(arrayEqlStorage, selfBacktrace, otherBacktrace));
        }
예제 #15
0
        public static object Reinitialize(ConversionStorage <Union <IList, int> > /*!*/ toAryToInt,
                                          BlockParam block, RubyArray /*!*/ self, [NotNull] object /*!*/ arrayOrSize)
        {
            var context = toAryToInt.Context;

            var site  = toAryToInt.GetSite(CompositeConversionAction.Make(context, CompositeConversion.ToAryToInt));
            var union = site.Target(site, arrayOrSize);

            if (union.First != null)
            {
                // block ignored
                return(Reinitialize(self, union.First));
            }
            else if (block != null)
            {
                return(Reinitialize(block, self, union.Second));
            }
            else
            {
                return(ReinitializeByRepeatedValue(context, self, union.Second, null));
            }
        }
예제 #16
0
        private static RubyArray /*!*/ MakeResult(WaitHandle /*!*/[] /*!*/ handles, ref int handleIndex, int signaling, RubyArray ioObjects)
        {
            RubyArray result = new RubyArray();

            if (ioObjects != null)
            {
                for (int i = 0; i < ioObjects.Count; i++)
                {
#if SILVERLIGHT
                    if (handleIndex == signaling || handles[handleIndex].WaitOne(0))
                    {
#else
                    if (handleIndex == signaling || handles[handleIndex].WaitOne(0, false))
                    {
#endif
                        result.Add(ioObjects[i]);
                    }
                    handleIndex++;
                }
            }
            return(result);
        }
예제 #17
0
        public static RubyArray /*!*/ GetEntries(object self, [NotNull] MutableString /*!*/ dirname)
        {
            string strDir = dirname.ConvertToString();

            string[] rawEntries = null;

            try {
                rawEntries = Directory.GetFileSystemEntries(strDir);
            } catch (Exception ex) {
                throw ToRubyException(ex, strDir, DirectoryOperation.Open);
            }

            RubyArray ret = new RubyArray(rawEntries.Length + 2);

            ret.Add(MutableString.Create("."));
            ret.Add(MutableString.Create(".."));
            foreach (string entry in rawEntries)
            {
                ret.Add(MutableString.Create(Path.GetFileName(entry)));
            }
            return(ret);
        }
예제 #18
0
        internal static RubyArray /*!*/ GetMethods(RubyModule /*!*/ self, bool inherited, RubyMethodAttributes attributes,
                                                   IEnumerable <string> foreignMembers)
        {
            var result = new RubyArray();

            using (self.Context.ClassHierarchyLocker()) {
                self.ForEachMember(inherited, attributes, foreignMembers, (name, module, member) => {
                    if (member.IsInteropMember && (module.Restrictions & ModuleRestrictions.NoNameMapping) == 0 && RubyUtils.HasMangledName(name))
                    {
                        if (Tokenizer.IsMethodName(name) || Tokenizer.IsOperatorName(name))
                        {
                            result.Add(new ClrName(name));
                        }
                    }
                    else
                    {
                        result.Add(self.Context.StringifyIdentifier(name));
                    }
                });
            }
            return(result);
        }
예제 #19
0
        public static object Grep(CallSiteStorage <EachSite> /*!*/ each, BinaryOpStorage /*!*/ caseEquals,
                                  BlockParam action, object self, object pattern)
        {
            RubyArray resultArray = new RubyArray();
            object    result      = resultArray;
            var       site        = caseEquals.GetCallSite("===");

            Each(each, self, Proc.Create(each.Context, delegate(BlockParam /*!*/ selfBlock, object _, object item) {
                if (RubyOps.IsTrue(site.Target(site, pattern, item)))
                {
                    if (action != null && action.Yield(item, out item))
                    {
                        result = item;
                        return(selfBlock.PropagateFlow(action, item));
                    }
                    resultArray.Add(item);
                }
                return(null);
            }));

            return(result);
        }
예제 #20
0
        public static IList /*!*/ Flatten(ConversionStorage <IList> /*!*/ tryToAry, IDictionary <object, object> /*!*/ self,
                                          [DefaultProtocol, DefaultParameterValue(1)] int maxDepth)
        {
            if (maxDepth == 0)
            {
                return(ToArray(self));
            }

            if (maxDepth > 0)
            {
                maxDepth--;
            }

            RubyArray result = new RubyArray();
            IList     list;

            foreach (KeyValuePair <object, object> pair in self)
            {
                if (maxDepth != 0 && (list = Protocols.TryCastToArray(tryToAry, pair.Key)) != null)
                {
                    IListOps.Flatten(tryToAry, list, maxDepth - 1, result);
                }
                else
                {
                    result.Add(pair.Key);
                }

                if (maxDepth != 0 && (list = Protocols.TryCastToArray(tryToAry, pair.Value)) != null)
                {
                    IListOps.Flatten(tryToAry, list, maxDepth - 1, result);
                }
                else
                {
                    result.Add(pair.Value);
                }
            }
            return(result);
        }
예제 #21
0
        public static object Each(RubyContext /*!*/ context, BlockParam block, object /*!*/ self)
        {
            PlatformAdaptationLayer pal       = context.DomainManager.Platform;
            IDictionary             variables = pal.GetEnvironmentVariables();

            if (variables.Count > 0 && block == null)
            {
                throw RubyExceptions.NoBlockGiven();
            }

            foreach (DictionaryEntry entry in variables)
            {
                RubyArray array = new RubyArray(2);
                array.Add(FrozenString(context, entry.Key));
                array.Add(FrozenString(context, entry.Value));
                object result;
                if (block.Yield(array, out result))
                {
                    return(result);
                }
            }
            return(self);
        }
예제 #22
0
        private static object FilterImpl(CallSiteStorage <EachSite> /*!*/ each, BlockParam /*!*/ predicate, object self, bool acceptingValue)
        {
            RubyArray resultArray = new RubyArray();
            object    result      = resultArray;

            Each(each, self, Proc.Create(each.Context, delegate(BlockParam /*!*/ selfBlock, object _, object item) {
                object blockResult;
                if (predicate.Yield(item, out blockResult))
                {
                    result = blockResult;
                    return(selfBlock.PropagateFlow(predicate, blockResult));
                }

                // Check if the result is what we expect (use true to select, false to reject)
                if (Protocols.IsTrue(blockResult) == acceptingValue)
                {
                    resultArray.Add(item);
                }
                return(null);
            }));

            return(result);
        }
예제 #23
0
        public static object Partition(CallSiteStorage <EachSite> /*!*/ each, BlockParam predicate, object self)
        {
            RubyArray trueSet  = new RubyArray();
            RubyArray falseSet = new RubyArray();
            RubyArray pair     = new RubyArray(2);

            pair.Add(trueSet);
            pair.Add(falseSet);
            object result = pair;

            Each(each, self, Proc.Create(each.Context, delegate(BlockParam /*!*/ selfBlock, object _, object item) {
                if (predicate == null)
                {
                    throw RubyExceptions.NoBlockGiven();
                }

                object blockResult;
                if (predicate.Yield(item, out blockResult))
                {
                    result = blockResult;
                    return(selfBlock.PropagateFlow(predicate, blockResult));
                }

                if (Protocols.IsTrue(blockResult))
                {
                    trueSet.Add(item);
                }
                else
                {
                    falseSet.Add(item);
                }

                return(null);
            }));

            return(result);
        }
예제 #24
0
        public static RubyArray /*!*/ SortBy(RubyContext /*!*/ context, BlockParam keySelector, object self)
        {
            // collect key, value pairs
            List <KeyValuePair <object, object> > keyValuePairs = new List <KeyValuePair <object, object> >();

            // Collect the key, value pairs
            Each(context, self, Proc.Create(context, delegate(BlockParam /*!*/ selfBlock, object item) {
                if (keySelector == null)
                {
                    throw RubyExceptions.NoBlockGiven();
                }

                object key;
                if (keySelector.Yield(item, out key))
                {
                    return(key);
                }

                keyValuePairs.Add(new KeyValuePair <object, object>(key, item));
                return(null);
            }));

            // sort by keys
            keyValuePairs.Sort(delegate(KeyValuePair <object, object> x, KeyValuePair <object, object> y) {
                return(Protocols.Compare(context, x.Key, y.Key));
            });

            // return values
            RubyArray result = new RubyArray(keyValuePairs.Count);

            foreach (KeyValuePair <object, object> pair in keyValuePairs)
            {
                result.Add(pair.Value);
            }

            return(result);
        }
예제 #25
0
        public static object Map(CallSiteStorage <EachSite> /*!*/ each, [NotNull] BlockParam /*!*/ collector, object self)
        {
            RubyArray resultArray = new RubyArray();
            object    result      = resultArray;

            if (collector.Proc.Dispatcher.ParameterCount <= 1 && !collector.Proc.Dispatcher.HasUnsplatParameter && !collector.Proc.Dispatcher.HasProcParameter)
            {
                // optimize for a block with a single parameter:
                Each(each, self, Proc.Create(each.Context, delegate(BlockParam /*!*/ selfBlock, object _, object item) {
                    object blockResult;
                    if (collector.Yield(item, out blockResult))
                    {
                        result = blockResult;
                        return(selfBlock.PropagateFlow(collector, blockResult));
                    }
                    resultArray.Add(blockResult);
                    return(null);
                }));
            }
            else
            {
                // general case:
                Each(each, self, Proc.Create(each.Context, 0, delegate(BlockParam /*!*/ selfBlock, object _, object[] __, RubyArray args) {
                    Debug.Assert(__.Length == 0);

                    object blockResult;
                    if (collector.YieldSplat(args, out blockResult))
                    {
                        result = blockResult;
                        return(selfBlock.PropagateFlow(collector, blockResult));
                    }
                    resultArray.Add(blockResult);
                    return(null);
                }));
            }
            return(result);
        }
예제 #26
0
        public static RubyArray /*!*/ GetDefinedConstants(RubyModule /*!*/ self)
        {
            var visited = new Dictionary <string, bool>();
            var result  = new RubyArray();

            bool hideGlobalConstants = !ReferenceEquals(self, self.Context.ObjectClass);

            self.ForEachConstant(true, delegate(RubyModule /*!*/ module, string name, object value) {
                if (name == null)
                {
                    // terminate enumeration when Object is reached
                    return(hideGlobalConstants && ReferenceEquals(module, module.Context.ObjectClass));
                }

                if (!visited.ContainsKey(name))
                {
                    visited.Add(name, true);
                    result.Add(MutableString.Create(name));
                }
                return(false);
            });

            return(result);
        }
예제 #27
0
        public static RubyArray /*!*/ GetNameList(RubyClass /*!*/ self)
        {
            var infos  = Encoding.GetEncodings();
            var result = new RubyArray(1 + infos.Length);

            // Ruby specific:
            result.Add(MutableString.CreateAscii(RubyEncoding.Binary.Name));

            foreach (var info in infos)
            {
                result.Add(MutableString.Create(RubyEncoding.GetRubySpecificName(info.CodePage) ?? info.Name));
            }

            foreach (var alias in RubyEncoding.Aliases.Keys)
            {
                result.Add(MutableString.CreateAscii(alias));
            }

            result.Add(MutableString.CreateAscii("locale"));
            result.Add(MutableString.CreateAscii("external"));
            result.Add(MutableString.CreateAscii("filesystem"));

            return(result);
        }
예제 #28
0
        public static RubyArray /*!*/ Drop(CallSiteStorage <EachSite> /*!*/ each, object self, [DefaultProtocol] int count)
        {
            if (count < 0)
            {
                throw RubyExceptions.CreateArgumentError("attempt to drop negative size");
            }

            var result = new RubyArray();

            Each(each, self, Proc.Create(each.Context, delegate(BlockParam /*!*/ selfBlock, object _, object item) {
                if (count > 0)
                {
                    count--;
                }
                else
                {
                    result.Add(item);
                }

                return(null);
            }));

            return(result);
        }
예제 #29
0
        public static object Modulo(BigInteger /*!*/ self, int other)
        {
            RubyArray result = DivMod(self, other);

            return(result[1]);
        }
예제 #30
0
 public static RubyArray /*!*/ SetBacktrace(Exception /*!*/ self, [NotNull] MutableString /*!*/ backtrace)
 {
     return(RubyExceptionData.GetInstance(self).Backtrace = RubyArray.Create(backtrace));
 }