Esempio n. 1
0
        protected override void Save()
        {
            RubyArray rawFile = new RubyArray();

            foreach (ScriptFile item in this.scripts)
            {
                if (item.Editor != null)
                {
                    item.Editor.Commit();
                }
            }

            foreach (ScriptFile item in this.scripts)
            {
                RubyArray rawItem = new RubyArray();
                rawItem.Add(item.ID);
                rawItem.Add(new RubyString(item.Title).Encode(Encoding.UTF8));
                byte[] code = Ionic.Zlib.ZlibStream.CompressBuffer(UTF8BytesFromUnicodeString(item.Code));
                if (code.Length == 0)
                {
                    code = new byte[] { 120, 156, 3, 0, 0, 0, 0, 1 };
                }
                rawItem.Add(new RubyString(code));
                rawFile.Add(rawItem);
            }
            System.IO.FileStream file = System.IO.File.OpenWrite(this.filename);
            NekoKun.Serialization.RubyMarshal.RubyMarshal.Dump(file, rawFile);
            file.Close();
        }
Esempio n. 2
0
        /// <summary>
        /// Returns a Ruby array describing parameters of the method.
        /// </summary>
        public virtual RubyArray /*!*/ GetRubyParameterArray()
        {
            if (_declaringModule == null)
            {
                return(new RubyArray());
            }

            // TODO: quick approximation, we can do better

            var context = _declaringModule.Context;

            RubyArray result = new RubyArray();
            int       arity  = GetArity();

            int mandatoryCount = (arity < 0) ? -arity - 1 : arity;
            var reqSymbol      = context.CreateAsciiSymbol("req");

            for (int i = 0; i < mandatoryCount; i++)
            {
                result.Add(new RubyArray {
                    reqSymbol
                });
            }

            if (arity < 0)
            {
                result.Add(new RubyArray {
                    context.CreateAsciiSymbol("rest")
                });
            }

            return(result);
        }
Esempio n. 3
0
        protected override void Save()
        {
            object dump;

            if (this.ArrayMode)
            {
                var list = new RubyArray();
                list.Add(RubyNil.Instance);
                foreach (var item in this.contents as List <object> )
                {
                    var obj = CreateRubyObject(this.className, item as ObjectEditor.Struct);
                    if (this.idField != null)
                    {
                        obj.InstanceVariables[RubySymbol.GetSymbol(idField.ID)] = list.Count + 1;
                    }

                    list.Add(obj);
                }
                dump = list;
            }
            else
            {
                dump = CreateRubyObject(this.className, this.contents as ObjectEditor.Struct);
            }

            var file = new System.IO.FileStream(this.filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);

            NekoKun.Serialization.RubyMarshal.RubyMarshal.Dump(file, dump);
            file.Close();
        }
Esempio n. 4
0
        private RubyArray /*!*/ MakeLoadPaths(RubyOptions /*!*/ options)
        {
            var loadPaths = new RubyArray();

            if (options.HasSearchPaths)
            {
                foreach (string path in options.SearchPaths)
                {
                    loadPaths.Add(_context.EncodePath(path));
                }
            }

#if !SILVERLIGHT // no library paths on Silverlight
            string applicationBaseDir;
            try {
                applicationBaseDir = AppDomain.CurrentDomain.BaseDirectory;
            } catch (SecurityException) {
                applicationBaseDir = null;
            }

            AddAbsoluteLibraryPaths(loadPaths, applicationBaseDir, options.LibraryPaths);
#endif
            loadPaths.Add(MutableString.CreateAscii("."));
            return(loadPaths);
        }
Esempio n. 5
0
        private object InvokeSplatInternal(BlockParam /*!*/ param, object self, object[] /*!*/ args, object splattee, List <object> list)
        {
            int argsLength = args.Length;

            int nextArg, nextItem;

            CreateArgumentsFromSplattee(_parameterCount, out nextArg, out nextItem, ref args, splattee);

            var array = new RubyArray();

            // remaining args:
            while (nextArg < argsLength)
            {
                array.Add(args[nextArg++]);
            }

            // remaining items:
            if (list != null)
            {
                while (nextItem < list.Count)
                {
                    array.Add(list[nextItem++]);
                }
            }
            else if (nextItem < 1)
            {
                // splattee hasn't been added yet:
                array.Add(splattee);
            }

            return(_block(param, self, args, array));
        }
Esempio n. 6
0
        private void AddStandardLibraryPath(RubyArray /*!*/ loadPaths, string path, string applicationBaseDir)
        {
#if FEATURE_FILESYSTEM
            bool isFullPath;
            if (path != null)
            {
                try {
                    isFullPath = Platform.IsAbsolutePath(path);
                } catch {
                    loadPaths.Add(_context.EncodePath(path));
                    return;
                }
            }
            else
            {
#if DEBUG
                // For developer use, add Src/StdLib
                string devStdLib = "../../Src/StdLib";
                if (Directory.Exists(devStdLib))
                {
                    path = devStdLib;
                }
#else
                path = "../Lib";
#endif
                isFullPath = false;
            }

            if (!isFullPath)
            {
                try {
                    if (String.IsNullOrEmpty(applicationBaseDir))
                    {
                        applicationBaseDir = _context.Platform.GetEnvironmentVariable(RubyContext.BinDirEnvironmentVariable);
                        if (!Directory.Exists(applicationBaseDir))
                        {
                            applicationBaseDir = AppDomain.CurrentDomain.BaseDirectory;
                        }
                    }
                } catch (SecurityException) {
                    applicationBaseDir = null;
                }

                try {
                    path = Platform.GetFullPath(RubyUtils.CombinePaths(applicationBaseDir, path));
                } catch {
                    loadPaths.Add(_context.EncodePath(path));
                    return;
                }
            }

            path = path.Replace('\\', '/');
            loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ironruby")));
            loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ruby/site_ruby/" + _context.StandardLibraryVersion)));
            loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ruby/" + _context.StandardLibraryVersion)));
#endif
        }
Esempio n. 7
0
 public static RubyArray Accept(RubyContext/*!*/ context, RubySocket/*!*/ self)
 {
     RubyArray result = new RubyArray(2);
     RubySocket s = new RubySocket(context, self.Socket.Accept());
     result.Add(s);
     SocketAddress addr = s.Socket.RemoteEndPoint.Serialize();
     result.Add(MutableString.CreateAscii(addr.ToString()));
     return result;
 }
Esempio n. 8
0
        public static RubyArray /*!*/ UnPackInetSockAddr(RubyClass /*!*/ self,
                                                         [DefaultProtocol, NotNull] MutableString /*!*/ address)
        {
            IPEndPoint ep     = UnpackSockAddr(address);
            RubyArray  result = new RubyArray(2);

            result.Add(ep.Port);
            result.Add(MutableString.CreateAscii(ep.Address.ToString()));
            return(result);
        }
Esempio n. 9
0
        public static RubyArray /*!*/ Accept(RubyContext /*!*/ context, RubySocket /*!*/ self)
        {
            RubyArray  result = new RubyArray(2);
            RubySocket s      = new RubySocket(context, self.Socket.Accept());

            result.Add(s);
            SocketAddress addr = s.Socket.RemoteEndPoint.Serialize();

            result.Add(MutableString.CreateAscii(addr.ToString()));
            return(result);
        }
Esempio n. 10
0
        internal static RubyArray /*!*/ GetAddressArray(RubyContext /*!*/ context, EndPoint /*!*/ endPoint, bool doNotReverseLookup)
        {
            RubyArray result = new RubyArray(4);

            IPEndPoint ep = (IPEndPoint)endPoint;

            result.Add(MutableString.CreateAscii(AddressFamilyToString(ep.AddressFamily)));
            result.Add(ep.Port);
            result.Add(HostNameToMutableString(context, IPAddressToHostName(ep.Address, doNotReverseLookup)));
            result.Add(MutableString.CreateAscii(ep.Address.ToString()));
            return(result);
        }
Esempio n. 11
0
        public static object DefineFinalizer(RespondToStorage/*!*/ respondTo, BinaryOpStorage/*!*/ call, RubyModule/*!*/ self, object obj, object finalizer)
        {
            if (!Protocols.RespondTo(respondTo, finalizer, "call")) {
                throw RubyExceptions.CreateArgumentError("finalizer should be callable (respond to :call)");
            }

            respondTo.Context.SetInstanceVariable(obj, FinalizerInvoker.InstanceVariableName, new FinalizerInvoker(call.GetCallSite("call"), finalizer));
            RubyArray result = new RubyArray(2);
            result.Add(0);
            result.Add(finalizer);
            return result;
        }
Esempio n. 12
0
        public void SetLoadPaths(IEnumerable <string /*!*/> /*!*/ paths)
        {
            ContractUtils.RequiresNotNullItems(paths, "paths");

            lock (_loadPaths) {
                _loadPaths.Clear();
                foreach (string path in paths)
                {
                    _loadPaths.Add(_context.EncodePath(path));
                }
            }
        }
Esempio n. 13
0
        public static RubyArray /*!*/ SysAccept(RubyContext /*!*/ context, RubySocket /*!*/ self)
        {
            RubyArray result = new RubyArray(2);
            // TODO: Do we need some kind of strong reference to the socket
            // here to stop the RubySocket from being garbage collected?
            RubySocket s = new RubySocket(context, self.Socket.Accept());

            result.Add(s.GetFileDescriptor());
            SocketAddress addr = s.Socket.RemoteEndPoint.Serialize();

            result.Add(MutableString.CreateAscii(addr.ToString()));
            return(result);
        }
Esempio n. 14
0
        public static RubyArray/*!*/ GetAvailableEncodings(RubyClass/*!*/ self) {
            // TODO: loads all encodings, we should be lazy with encoding creation

            var infos = Encoding.GetEncodings();
            var result = new RubyArray(1 + infos.Length);

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

            foreach (var info in infos) {
                result.Add(RubyEncoding.GetRubyEncoding(info.GetEncoding()));
            }
            return result;
        }
Esempio n. 15
0
        private void AddStandardLibraryPath(RubyArray /*!*/ loadPaths, string path, string applicationBaseDir)
        {
#if !SILVERLIGHT // no library paths on Silverlight
            bool isFullPath;
            if (path != null)
            {
                try {
                    isFullPath = Platform.IsAbsolutePath(path);
                } catch {
                    loadPaths.Add(_context.EncodePath(path));
                    return;
                }
            }
            else
            {
                path       = "../Lib";
                isFullPath = false;
            }

            if (!isFullPath)
            {
                try {
                    if (String.IsNullOrEmpty(applicationBaseDir))
                    {
                        applicationBaseDir = _context.Platform.GetEnvironmentVariable(RubyContext.BinDirEnvironmentVariable);
                        if (!Directory.Exists(applicationBaseDir))
                        {
                            applicationBaseDir = AppDomain.CurrentDomain.BaseDirectory;
                        }
                    }
                } catch (SecurityException) {
                    applicationBaseDir = null;
                }

                try {
                    path = Platform.GetFullPath(RubyUtils.CombinePaths(applicationBaseDir, path));
                } catch {
                    loadPaths.Add(_context.EncodePath(path));
                    return;
                }
            }

            path = path.Replace('\\', '/');
            loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ironruby")));
            loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ruby/site_ruby/" + _context.StandardLibraryVersion)));
            loadPaths.Add(_context.EncodePath(RubyUtils.CombinePaths(path, "ruby/" + _context.StandardLibraryVersion)));
#endif
        }
Esempio n. 16
0
        private static RubyArray /*!*/ AddBacktrace(RubyArray /*!*/ result, InterpreterState /*!*/ frame, int skipFrames)
        {
            do
            {
                if (skipFrames == 0)
                {
                    string methodName;

                    // TODO: generalize for all languages
                    if (frame.ScriptCode.LanguageContext is RubyContext)
                    {
                        methodName = ParseRubyMethodName(frame.Lambda.Name);
                    }
                    else
                    {
                        methodName = frame.Lambda.Name;
                    }

                    result.Add(MutableString.Create(FormatFrame(
                                                        frame.ScriptCode.SourceUnit.Path,
                                                        frame.CurrentLocation.Line,
                                                        methodName
                                                        )));
                }
                else
                {
                    skipFrames--;
                }

                frame = frame.Caller;
            } while (frame != null);

            return(result);
        }
Esempio n. 17
0
        private static RubyArray /*!*/ AddBacktrace(RubyArray /*!*/ result, IEnumerable <StackFrame> stackTrace, bool hasFileAccessPermission,
                                                    int skipFrames)
        {
            if (stackTrace != null)
            {
                foreach (StackFrame frame in stackTrace)
                {
                    if (IsVisibleFrame(frame.GetMethod()))
                    {
                        if (skipFrames == 0)
                        {
                            string methodName, file;
                            int    line;
                            GetStackFrameInfo(frame, hasFileAccessPermission, out methodName, out file, out line);
                            result.Add(MutableString.Create(FormatFrame(file, line, methodName)));
                        }
                        else
                        {
                            skipFrames--;
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 18
0
        public void RubyArray_Indexer()
        {
            RubyArray a;

            a = new RubyArray();
            a.Add(0);
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 0 }));
            a[1] = 1;
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 0, 1 }));
            a[4] = 4;
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 0, 1, null, null, 4 }));
            a[6] = 6;
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 0, 1, null, null, 4, null, 6 }));

            a = new RubyArray(new object[] { null, null, 2, 3 }, 2, 2);
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 2, 3 }));
            a[3] = 4;
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 2, 3, null, 4 }));

            a = new RubyArray(new object[] { null, null, 2, 3 }, 2, 2);
            Assert((int)a[0] == 2);
            object x;

            AssertExceptionThrown <IndexOutOfRangeException>(() => x = a[2]);
        }
Esempio n. 19
0
 internal RubyArray/*!*/ GetMembers(RubyContext/*!*/ context) {
     RubyArray list = new RubyArray(_names.Length);
     foreach (string id in _names) {
         list.Add(context.StringifyIdentifier(id));
     }
     return list;
 }
Esempio n. 20
0
        //TODO: remove Ruby-specific stuff from this layer
        public RubyArray /*!*/ ConstructSequence(Node /*!*/ sequenceNode)
        {
            SequenceNode seq = sequenceNode as SequenceNode;

            if (seq == null)
            {
                throw new ConstructorException("expected a sequence node, but found: " + sequenceNode);
            }
            IList <Node> @internal = seq.Nodes;
            RubyArray    val       = new RubyArray(@internal.Count);

            foreach (Node node in @internal)
            {
                object   obj      = ConstructObject(node);
                LinkNode linkNode = obj as LinkNode;
                if (linkNode != null)
                {
                    int ix = val.Count;
                    AddFixer(linkNode.Linked, delegate(Node n, object real) {
                        val[ix] = real;
                    });
                }
                val.Add(obj);
            }
            return(val);
        }
Esempio n. 21
0
 internal RubyArray/*!*/ GetMembers() {
     RubyArray list = new RubyArray(Members.Length);
     foreach (string id in Members) {
         list.Add(MutableString.Create(id));
     }
     return list;
 }
Esempio n. 22
0
        private object InvokeInternal(BlockParam /*!*/ param, object self, object[] /*!*/ args)
        {
            // TODO
            if (args.Length < _parameterCount)
            {
                Array.Resize(ref args, _parameterCount);
                return(_block(param, self, args, RubyOps.MakeArray0()));
            }
            else if (args.Length == _parameterCount)
            {
                return(_block(param, self, args, RubyOps.MakeArray0()));
            }
            else
            {
                var actualArgs = new object[_parameterCount];

                for (int i = 0; i < actualArgs.Length; i++)
                {
                    actualArgs[i] = args[i];
                }

                var array = new RubyArray(args.Length - _parameterCount);
                for (int i = _parameterCount; i < args.Length; i++)
                {
                    array.Add(args[i]);
                }

                return(_block(param, self, actualArgs, array));
            }
        }
Esempio n. 23
0
        public override RubyArray /*!*/ GetRubyParameterArray()
        {
            var context   = _declaringScope.RubyContext;
            var reqSymbol = context.CreateAsciiSymbol("req");
            var optSymbol = context.CreateAsciiSymbol("opt");
            var ps        = _body.Ast.Parameters;

            RubyArray result = new RubyArray();

            for (int i = 0; i < ps.LeadingMandatoryCount; i++)
            {
                result.Add(new RubyArray {
                    reqSymbol, context.EncodeIdentifier(((LocalVariable)ps.Mandatory[i]).Name)
                });
            }

            foreach (var p in ps.Optional)
            {
                result.Add(new RubyArray {
                    optSymbol, context.EncodeIdentifier(((LocalVariable)p.Left).Name)
                });
            }

            if (ps.Unsplat != null)
            {
                result.Add(new RubyArray {
                    context.CreateAsciiSymbol("rest"), context.EncodeIdentifier(((LocalVariable)ps.Unsplat).Name)
                });
            }

            for (int i = ps.LeadingMandatoryCount; i < ps.Mandatory.Length; i++)
            {
                result.Add(new RubyArray {
                    reqSymbol, context.EncodeIdentifier(((LocalVariable)ps.Mandatory[i]).Name)
                });
            }

            if (ps.Block != null)
            {
                result.Add(new RubyArray {
                    context.CreateAsciiSymbol("block"), context.EncodeIdentifier(ps.Block.Name)
                });
            }

            return(result);
        }
Esempio n. 24
0
 internal RubyArray/*!*/ GetMembers() {
     RubyArray list = new RubyArray(_names.Length);
     foreach (string id in _names) {
         // TODO: we need to add encoding to symbols and preserve it here:
         list.Add(MutableString.Create(id, RubyEncoding.UTF8));
     }
     return list;
 }
Esempio n. 25
0
        private RubyArray /*!*/ MakeLoadPaths(RubyOptions /*!*/ options)
        {
            var loadPaths = new RubyArray();

            if (options.HasSearchPaths)
            {
                foreach (string path in options.SearchPaths)
                {
                    loadPaths.Add(_context.EncodePath(path));
                }
            }

            AddStandardLibraryPath(loadPaths, options.StandardLibraryPath, options.ApplicationBase);
            // TODO: remove?
            loadPaths.Add(MutableString.CreateAscii("."));
            return(loadPaths);
        }
Esempio n. 26
0
        public static RubyArray/*!*/ OpenPipe(
            RubyContext/*!*/ context, 
            object self, 
            [DefaultProtocol, NotNull]MutableString/*!*/ command) {

            Process process = RubyIOOps.OpenPipe(context, command, true, true, true);
            RubyArray result = new RubyArray();
            result.Add(new RubyIO(context, null, process.StandardInput, IOMode.WriteOnly));
            result.Add(new RubyIO(context, process.StandardOutput, null, IOMode.ReadOnly));
            result.Add(new RubyIO(context, process.StandardError, null, IOMode.ReadOnly));

            if (context.RubyOptions.Compatibility >= RubyCompatibility.Ruby19) {
                result.Add(ThreadOps.RubyThreadInfo.FromThread(System.Threading.Thread.CurrentThread));
            }

            return result;
        }
Esempio n. 27
0
        public static RubyArray GetAddressInfo(
            ConversionStorage<MutableString>/*!*/ stringCast, ConversionStorage<int>/*!*/ fixnumCast, 
            RubyClass/*!*/ self, object hostNameOrAddress, object port,
            [DefaultParameterValue(null)]object family,
            [DefaultParameterValue(0)]object socktype,
            [DefaultParameterValue(0)]object protocol,
            [DefaultParameterValue(null)]object flags) {

            IPHostEntry entry = (hostNameOrAddress != null) ? 
                GetHostEntry(ConvertToHostString(stringCast, hostNameOrAddress)) : MakeEntry(IPAddress.Any);

            int iPort = ConvertToPortNum(stringCast, fixnumCast, port);

            // Sadly the family, socktype, protocol and flags get passed through at best and ignored at worst, 
            // since System.Net does not provide for them
            AddressFamily addrFamily = ConvertToAddressFamily(stringCast, fixnumCast, family);
            int socketType = Protocols.CastToFixnum(fixnumCast, socktype);
            int protocolType = Protocols.CastToFixnum(fixnumCast, protocol);

            RubyArray results = new RubyArray(entry.AddressList.Length);
            for (int i = 0; i < entry.AddressList.Length; ++i) {
                IPAddress address = entry.AddressList[i];

                RubyArray result = new RubyArray(9);
                result.Add(ToAddressFamilyString(address.AddressFamily));
                result.Add(iPort);
                if (DoNotReverseLookup(self.Context).Value) {
                    result.Add(MutableString.CreateAscii(address.ToString()));
                } else {
                    IPHostEntry alias = GetHostEntry(address);
                    // TODO (encoding):
                    result.Add(MutableString.Create(alias.HostName, RubyEncoding.UTF8));
                }
                result.Add(MutableString.CreateAscii(address.ToString()));
                result.Add((int)address.AddressFamily);
                result.Add(socketType);

                // TODO: protocol type:
                result.Add(protocolType);

                results.Add(result);
            }
            return results;
        }
Esempio n. 28
0
        public static RubyArray /*!*/ GetNameInfo(RubyClass /*!*/ self, [NotNull] RubyArray /*!*/ hostInfo, [Optional] object flags)
        {
            if (hostInfo.Count < 3 || hostInfo.Count > 4)
            {
                throw RubyExceptions.CreateArgumentError("First parameter must be a 3 or 4 element array");
            }

            // We only support AF_INET (IP V4) family
            AddressFamily addressFamily = ConvertToAddressFamily(self.Context, hostInfo[0]);

            if (addressFamily != AddressFamily.InterNetwork)
            {
                throw new SocketException((int)SocketError.AddressFamilyNotSupported);
            }

            // Lookup the service name for the given port.
            int         port    = ConvertToPortNum(self.Context, hostInfo[1]);
            ServiceName service = SearchForService(port);

            // hostInfo[2] should have a host name
            // if it exists and is not null hostInfo[3] should have an IP address
            // in that case we use that rather than the host name.
            MutableString address = ConvertToHostString(self.Context, hostInfo[2]);

            if (hostInfo.Count > 3 && hostInfo[3] != null)
            {
                address = ConvertToHostString(self.Context, hostInfo[3]);
            }

            IPHostEntry entry = GetHostEntry(address.ConvertToString());

            RubyArray result = new RubyArray(2);

            result.Add(MutableString.Create(entry.HostName));
            if (service != null)
            {
                result.Add(MutableString.Create(service.Name));
            }
            else
            {
                result.Add(port);
            }
            return(result);
        }
Esempio n. 29
0
            public static RubyArray Execute(RhoDatabase /*!*/ self, MutableString /*!*/ sqlStatement, Boolean isBatch, RubyArray args)
            {
                try
                {
                    RubyArray retArr = new RubyArray();

                    if (isBatch)
                    {
                        self.m_db.executeBatchSQL(sqlStatement.ToString());
                    }
                    else
                    {
                        Object[] values = null;
                        if (args != null && args.Count > 0)
                        {
                            if (args[0] != null && args[0] is RubyArray)
                            {
                                values = ((RubyArray)args[0]).ToArray();
                            }
                            else
                            {
                                values = args.ToArray();
                            }
                        }

                        using (IDBResult rows = self.m_db.executeSQL(sqlStatement.ToString(), values, true))
                        {
                            if (rows != null)
                            {
                                MutableString[] colNames = null;
                                for (; !rows.isEnd(); rows.next())
                                {
                                    IDictionary <object, object> map = new Dictionary <object, object>();
                                    Hash row = new Hash(map);
                                    for (int nCol = 0; nCol < rows.getColCount(); nCol++)
                                    {
                                        if (colNames == null)
                                        {
                                            colNames = getOrigColNames(rows);
                                        }

                                        row.Add(colNames[nCol], rows.getRubyValueByIdx(nCol));
                                    }
                                    retArr.Add(row);
                                }
                            }
                        }
                    }

                    return(retArr);
                }catch (Exception exc)
                {
                    //TODO: throw ruby exception
                    throw exc;
                }
            }
Esempio n. 30
0
        public static RubyArray /*!*/ OpenPipe(
            RubyContext /*!*/ context,
            object self,
            [DefaultProtocol, NotNull] MutableString /*!*/ command)
        {
            Process   process = RubyProcess.CreateProcess(context, command, true, true, true);
            RubyArray result  = new RubyArray();

            result.Add(new RubyIO(context, null, process.StandardInput, IOMode.WriteOnly));
            result.Add(new RubyIO(context, process.StandardOutput, null, IOMode.ReadOnly));
            result.Add(new RubyIO(context, process.StandardError, null, IOMode.ReadOnly));

            if (context.RubyOptions.Compatibility >= RubyCompatibility.Ruby19)
            {
                result.Add(ThreadOps.RubyThreadInfo.FromThread(System.Threading.Thread.CurrentThread));
            }

            return(result);
        }
Esempio n. 31
0
        // R(N, *, =)
        public override object InvokeSplatRhs(BlockParam /*!*/ param, object self, Proc procArg, object[] /*!*/ args, IList /*!*/ splattee, object rhs)
        {
            var list = new RubyArray(splattee.Count + 1);

            list.AddRange(splattee);
            list.Add(rhs);
            splattee = list;

            return(InvokeSplatInternal(param, self, procArg, args, list));
        }
Esempio n. 32
0
    public RubyArray getArray()
    {
        RubyArray a = new RubyArray();

        for (int i = 0; i < answerArray.Length; i++)
        {
            a.Add(answerArray[i]);
        }

        return(a);
    }
Esempio n. 33
0
        internal static RubyArray /*!*/ GetAddressArray(RubyContext /*!*/ context, EndPoint endPoint)
        {
            RubyArray result = new RubyArray(4);

            IPEndPoint ep = (IPEndPoint)endPoint;

            result.Add(MutableString.Create(AddressFamilyToString(ep.AddressFamily)));
            result.Add(ep.Port);
            if (DoNotReverseLookup(context).Value)
            {
                result.Add(MutableString.Create(ep.Address.ToString()));
            }
            else
            {
                // TODO: MRI returns localhost rather than the local machine name here
                result.Add(MutableString.Create(Dns.GetHostEntry(ep.Address).HostName));
            }
            result.Add(MutableString.Create(ep.Address.ToString()));
            return(result);
        }
Esempio n. 34
0
        public static RubyArray /*!*/ GetCrcTable(RubyModule /*!*/ self)
        {
            var result = new RubyArray(crcTable.Length);

            for (int i = 0; i < crcTable.Length; i++)
            {
                result.Add(Protocols.Normalize(crcTable[i]));
            }

            return(result);
        }
Esempio n. 35
0
 public static object EachCons(CallSiteStorage <EachSite> /*!*/ each, BlockParam /*!*/ block, object self, [DefaultProtocol] int sliceSize)
 {
     return(EachSlice(each, block, self, sliceSize, false, (slice) => {
         RubyArray newSlice = new RubyArray(slice.Count);
         for (int i = 1; i < slice.Count; i++)
         {
             newSlice.Add(slice[i]);
         }
         return newSlice;
     }));
 }
Esempio n. 36
0
        public static RubyArray /*!*/ GetNameInfo(RubyClass /*!*/ self,
                                                  [DefaultProtocol, NotNull] MutableString /*!*/ address, [Optional] object flags)
        {
            IPEndPoint  ep      = UnpackSockAddr(address);
            IPHostEntry entry   = GetHostEntry(ep.Address, false);
            ServiceName service = SearchForService(ep.Port);

            RubyArray result = new RubyArray(2);

            result.Add(HostNameToMutableString(self.Context, entry.HostName));
            if (service != null)
            {
                result.Add(MutableString.Create(service.Name));
            }
            else
            {
                result.Add(ep.Port);
            }
            return(result);
        }
Esempio n. 37
0
        public static RubyArray GetGroup(RubyContext/*!*/ context, MatchData/*!*/ self, [DefaultProtocol]int start, [DefaultProtocol]int length) {
            if (!IListOps.NormalizeRange(self.Groups.Count, ref start, ref length)) {
                return null;
            }

            RubyArray result = new RubyArray();
            for (int i = 0; i < length; i++) {
                result.Add(self.GetGroupValue(context, start + i));
            }

            return result;
        }
Esempio n. 38
0
        public static RubyArray/*!*/ List([NotNull]ThreadGroup/*!*/ self) {
            ThreadOps.RubyThreadInfo[] threads = ThreadOps.RubyThreadInfo.Threads;
            RubyArray result = new RubyArray(threads.Length);
            foreach (ThreadOps.RubyThreadInfo threadInfo in threads) {
                Thread thread = threadInfo.Thread;
                if (thread != null && threadInfo.Group == self) {
                    result.Add(thread);
                }
            }

            return result;
        }
Esempio n. 39
0
        public void RubyArray_Add()
        {
            RubyArray a;

            a = new RubyArray();

            for (int i = 0; i < Utils.MinListSize; i++)
            {
                a.Add(i);
                Assert((int)a[i] == i && a.Count == i + 1 && a.Capacity == Utils.MinListSize);
            }

            Assert(((IList)a).Add(Utils.MinListSize) == Utils.MinListSize);
            Assert(a.Count == Utils.MinListSize + 1);
            for (int i = 0; i < a.Count; i++)
            {
                Assert((int)a[i] == i);
            }

            a = new RubyArray(new[] { 1, 2, 3 });
            a.AddCapacity(0);
            Assert(a.Count == 3);
            a.AddCapacity(100);
            Assert(a.Count == 3 && a.Capacity >= 103);

            a = new RubyArray(new[] { 1, 2, 3 });
            a.AddMultiple(0, 4);
            AssertValueEquals(a, 1, 2, 3);
            a.AddMultiple(5, 4);
            AssertValueEquals(a, 1, 2, 3, 4, 4, 4, 4, 4);

            a = new RubyArray(new[] { 1, 2, 3 });
            a.AddRange(new object[0]);
            AssertValueEquals(a, 1, 2, 3);
            a.AddRange(new[] { 4 });
            AssertValueEquals(a, 1, 2, 3, 4);
            a.AddRange(new[] { 5, 6, 7, 8, 9, 10 });
            AssertValueEquals(a, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            a.AddRange(new[] { 11 });
            AssertValueEquals(a, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

            a = new RubyArray();
            a.AddRange((IEnumerable) new RubyArray(new[] { 1, 2, 3 }));
            a.AddRange((IList) new RubyArray(new[] { 1, 2, 3 }), 1, 2);
            AssertValueEquals(a, 1, 2, 3, 2, 3);

            a.Freeze();
            AssertExceptionThrown <InvalidOperationException>(() => a.Add(1));
            AssertExceptionThrown <InvalidOperationException>(() => a.AddCapacity(10));
            AssertExceptionThrown <InvalidOperationException>(() => a.AddMultiple(10, 10));
            AssertExceptionThrown <InvalidOperationException>(() => a.AddRange(new object[0]));
            AssertExceptionThrown <InvalidOperationException>(() => a.AddRange(Enumerable(0)));
        }
Esempio n. 40
0
        public static RubyArray/*!*/ TOA(RubyContext/*!*/ context, object self) {
            RubyArray result = new RubyArray();
            RubyArray lines;

            while (context.InputProvider.HasMoreFiles()) {
                lines = RubyIOOps.ReadLines(context, context.InputProvider.GetOrResetCurrentStream());
                //TODO: result.append(lines)???
                foreach (var line in lines) {
                    result.Add(line);
                }
            }
            return result;
        }
Esempio n. 41
0
 public static RubyArray Map(CallSiteStorage<EachSite>/*!*/ each, BlockParam collector, object self) {
     RubyArray result = new RubyArray();
     Each(each, self, Proc.Create(each.Context, delegate(BlockParam/*!*/ selfBlock, object _, object item) {
         if (collector != null) {
             if (collector.Yield(item, out item)) {
                 return item;
             }
         }
         result.Add(item);
         return null;
     }));
     return result;
 }
Esempio n. 42
0
        internal static RubyArray /*!*/ CreateHostEntryArray(RubyContext /*!*/ context, IPHostEntry /*!*/ hostEntry, bool packIpAddresses)
        {
            RubyArray result = new RubyArray(4);

            // host name:
            result.Add(HostNameToMutableString(context, hostEntry.HostName));

            // aliases:
            RubyArray aliases = new RubyArray(hostEntry.Aliases.Length);

            foreach (string alias in hostEntry.Aliases)
            {
                aliases.Add(HostNameToMutableString(context, alias));
            }
            result.Add(aliases);

            // address (the first IPv4):
            foreach (IPAddress address in hostEntry.AddressList)
            {
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    result.Add((int)address.AddressFamily);
                    if (packIpAddresses)
                    {
                        byte[]        bytes = address.GetAddressBytes();
                        MutableString str   = MutableString.CreateBinary();
                        str.Append(bytes, 0, bytes.Length);
                        result.Add(str);
                    }
                    else
                    {
                        result.Add(MutableString.CreateAscii(address.ToString()));
                    }
                    break;
                }
            }
            return(result);
        }
Esempio n. 43
0
        public static RubyArray Ancestors(RubyModule/*!*/ self)
        {
            RubyArray ancestors = new RubyArray();

            using (self.Context.ClassHierarchyLocker()) {
                self.ForEachAncestor(true, delegate(RubyModule/*!*/ module) {
                    if (!module.IsSingletonClass) {
                        ancestors.Add(module);
                    }
                    return false;
                });
            }
            return ancestors;
        }
Esempio n. 44
0
        public void IListOps_EnumerateRecursively1()
        {
            var a = new RubyArray();
            var b = new RubyArray();
            b.Add(new RubyArray { new RubyArray { b } });
            a.Add(b);

            var result = IListOps.EnumerateRecursively(new Runtime.ConversionStorage<System.Collections.IList>(Context), a, -1, list => {
                Assert(list == b);
                return 123;
            }).ToArray();

            Assert(result.Length == 1 && (int)result[0] == 123);
        }
Esempio n. 45
0
        public void RubyArray_Add()
        {
            RubyArray a;
            a = new RubyArray();

            for (int i = 0; i < Utils.MinListSize; i++) {
                a.Add(i);
                Assert((int)a[i] == i && a.Count == i + 1 && a.Capacity == Utils.MinListSize);
            }

            Assert(((IList)a).Add(Utils.MinListSize) == Utils.MinListSize);
            Assert(a.Count == Utils.MinListSize + 1);
            for (int i = 0; i < a.Count; i++) {
                Assert((int)a[i] == i);
            }

            a = new RubyArray(new[] { 1,2,3 });
            a.AddCapacity(0);
            Assert(a.Count == 3);
            a.AddCapacity(100);
            Assert(a.Count == 3 && a.Capacity >= 103);

            a = new RubyArray(new[] { 1, 2, 3 });
            a.AddMultiple(0, 4);
            AssertValueEquals(a, 1, 2, 3);
            a.AddMultiple(5, 4);
            AssertValueEquals(a, 1, 2, 3, 4, 4, 4, 4, 4);

            a = new RubyArray(new[] { 1, 2, 3 });
            a.AddRange(new object[0]);
            AssertValueEquals(a, 1, 2, 3);
            a.AddRange(new[] { 4 });
            AssertValueEquals(a, 1, 2, 3, 4);
            a.AddRange(new[] { 5, 6, 7, 8, 9, 10 });
            AssertValueEquals(a, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            a.AddRange(new[] { 11 });
            AssertValueEquals(a, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

            a = new RubyArray();
            a.AddRange((IEnumerable)new RubyArray(new[] { 1, 2, 3 }));
            a.AddRange((IList)new RubyArray(new[] { 1, 2, 3 }), 1, 2);
            AssertValueEquals(a, 1, 2, 3, 2, 3);

            a.Freeze();
            AssertExceptionThrown<RuntimeError>(() => a.Add(1));
            AssertExceptionThrown<RuntimeError>(() => a.AddCapacity(10));
            AssertExceptionThrown<RuntimeError>(() => a.AddMultiple(10, 10));
            AssertExceptionThrown<RuntimeError>(() => a.AddRange(new object[0]));
            AssertExceptionThrown<RuntimeError>(() => a.AddRange(Enumerable(0)));
        }
Esempio n. 46
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));
            }
        }
Esempio n. 47
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));
            }
        }
Esempio n. 48
0
        public static Hash ToJsonRawObject(RubyScope scope, MutableString self)
        {
            byte[] selfBuffer = self.ToByteArray();
            var array = new RubyArray(selfBuffer.Length);
            foreach (byte b in selfBuffer) {
                array.Add(b & 0xFF);
            }

            var context = scope.RubyContext;
            var result = new Hash(context);
            var createId = Helpers.GetCreateId(scope);

            result.Add(createId, MutableString.Create(context.GetClassName(self), RubyEncoding.Binary));
            result.Add(MutableString.CreateAscii("raw"), array);
            return result;
        }
Esempio n. 49
0
        public static IList/*!*/ ToArray(ConversionStorage<IList>/*!*/ tryToAry, ConversionStorage<IList>/*!*/ tryToA, object self, object obj) {
            IList result = Protocols.TryCastToArray(tryToAry, obj);
            if (result != null) {
                return result;
            }

            // MRI 1.9 calls to_a (MRI 1.8 doesn't):
            //if (context.RubyOptions.Compatibility > RubyCompatibility.Ruby18) {
            result = Protocols.TryConvertToArray(tryToA, obj);
            if (result != null) {
                return result;
            }
            //}

            result = new RubyArray();
            if (obj != null) {
                result.Add(obj);
            }
            return result;
        }
Esempio n. 50
0
        public static RubyArray GetAddressInfo(
            ConversionStorage<MutableString>/*!*/ stringCast, ConversionStorage<int>/*!*/ fixnumCast, 
            RubyClass/*!*/ self, object hostNameOrAddress, object port,
            [DefaultParameterValue(null)]object family,
            [DefaultParameterValue(0)]object socktype,
            [DefaultParameterValue(0)]object protocol,
            [DefaultParameterValue(null)]object flags) {

            RubyContext context = self.Context;

            IPHostEntry entry = (hostNameOrAddress != null) ?
                GetHostEntry(ConvertToHostString(stringCast, hostNameOrAddress), DoNotReverseLookup(context).Value) : 
                MakeEntry(IPAddress.Any, DoNotReverseLookup(context).Value);

            int iPort = ConvertToPortNum(stringCast, fixnumCast, port);

            // TODO: ignore family, the only supported families are InterNetwork and InterNetworkV6
            ConvertToAddressFamily(stringCast, fixnumCast, family);
            int socketType = Protocols.CastToFixnum(fixnumCast, socktype);
            int protocolType = Protocols.CastToFixnum(fixnumCast, protocol);

            RubyArray results = new RubyArray(entry.AddressList.Length);
            for (int i = 0; i < entry.AddressList.Length; ++i) {
                IPAddress address = entry.AddressList[i];

                RubyArray result = new RubyArray(9);
                result.Add(ToAddressFamilyString(address.AddressFamily));
                result.Add(iPort);
                result.Add(HostNameToMutableString(context, IPAddressToHostName(address, DoNotReverseLookup(context).Value)));
                result.Add(MutableString.CreateAscii(address.ToString()));
                result.Add((int)address.AddressFamily);
                result.Add(socketType);

                // TODO: protocol type:
                result.Add(protocolType);

                results.Add(result);
            }
            return results;
        }
Esempio n. 51
0
 public static RubyArray/*!*/ OpenPipe(RubyClass/*!*/ self) {
     Stream reader, writer;
     RubyPipe.CreatePipe(out reader, out writer);
     RubyArray result = new RubyArray(2);
     result.Add(new RubyIO(self.Context, reader, IOMode.ReadOnly));
     result.Add(new RubyIO(self.Context, writer, IOMode.WriteOnly));
     return result;
 }
Esempio n. 52
0
        public static RubyArray/*!*/ Zip(CallSiteStorage<EachSite>/*!*/ each, ConversionStorage<IList>/*!*/ tryToA, BlockParam block,
            object self, [NotNull]params object[] args) {
            RubyArray results = (block == null) ? new RubyArray() : null;

            // Call to_a on each argument
            IList[] otherArrays = new IList[args.Length];
            for (int i = 0; i < args.Length; i++) {
                otherArrays[i] = Protocols.TryConvertToArray(tryToA, args[i]);
            }

            int index = 0;
            Each(each, self, Proc.Create(each.Context, delegate(BlockParam/*!*/ selfBlock, object _, object item) {
                // Collect items
                RubyArray array = new RubyArray(otherArrays.Length + 1);
                array.Add(item);
                foreach (IList otherArray in otherArrays) {
                    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)) {
                        return blockResult;
                    }
                } else {
                    results.Add(array);
                }
                return null;
            }));

            return results;
        }
Esempio n. 53
0
        public static RubyArray/*!*/ SortBy(
            CallSiteStorage<EachSite>/*!*/ each, 
            BinaryOpStorage/*!*/ comparisonStorage,
            BinaryOpStorage/*!*/ lessThanStorage,
            BinaryOpStorage/*!*/ greaterThanStorage,
            BlockParam keySelector, object self) {

            // collect key, value pairs
            List<KeyValuePair<object, object>> keyValuePairs = new List<KeyValuePair<object, object>>();

            // Collect the key, value pairs
            Each(each, self, Proc.Create(each.Context, delegate(BlockParam/*!*/ selfBlock, object _, 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(comparisonStorage, lessThanStorage, greaterThanStorage, 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;
        }
Esempio n. 54
0
        public static RubyArray/*!*/ Partition(CallSiteStorage<EachSite>/*!*/ each, BlockParam predicate, object self) {
            RubyArray trueSet = new RubyArray();
            RubyArray falseSet = new RubyArray();

            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)) {
                    return blockResult;
                }

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

                return null;
            }));

            RubyArray pair = new RubyArray(2);
            pair.Add(trueSet);
            pair.Add(falseSet);
            return pair;
        }
Esempio n. 55
0
        public static RubyArray Grep(CallSiteStorage<EachSite>/*!*/ each, BinaryOpStorage/*!*/ caseEquals, 
            BlockParam action, object self, object pattern) {

            RubyArray result = new RubyArray();
            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) {
                        if (action.Yield(item, out item)) {
                            return item;
                        }
                    }
                    result.Add(item);
                }
                return null;
            }));

            return result;
        }
Esempio n. 56
0
        private static RubyArray/*!*/ Filter(CallSiteStorage<EachSite>/*!*/ each, BlockParam predicate, object self, bool acceptingValue) {
            RubyArray result = new RubyArray();

            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)) {
                    return blockResult;
                }

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

            return result;
        }
Esempio n. 57
0
        public static RubyArray/*!*/ ToArray(CallSiteStorage<EachSite>/*!*/ each, object self) {
            RubyArray data = new RubyArray();

            Each(each, self, Proc.Create(each.Context, delegate(BlockParam/*!*/ selfBlock, object _, object item) {
                data.Add(item);
                return null;
            }));

            return data;
        }
Esempio n. 58
0
        public static RubyArray/*!*/ ReadLines(RubyContext/*!*/ context, RubyIO/*!*/ self, [DefaultProtocol]MutableString separator, [DefaultProtocol]int limit) {
            RubyArray result = new RubyArray();

            // no dynamic call, doesn't modify $_ scope variable:
            MutableString line;
            while ((line = self.ReadLineOrParagraph(separator, limit)) != null) {
                result.Add(line);
            }

            self.LineNumber += result.Count;
            context.InputProvider.LastInputLineNumber = self.LineNumber;
            return result;
        }
Esempio n. 59
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;
        }
Esempio n. 60
0
        private static RubyArray SelectInternal(RubyContext/*!*/ context, RubyArray read, RubyArray write, RubyArray error, TimeSpan timeout) {
            WaitHandle[] handles = null;
            RubyArray result;

            if (read == null && write == null && error == null) {
                Thread.Sleep(timeout);
                return null;
            }

            try {
                handles = GetWaitHandles(context, read, write, error);
                int index;
                try {
#if SILVERLIGHT
                    index = WaitHandle.WaitAny(handles, timeout);
#else
                    index = WaitHandle.WaitAny(handles, timeout, false);
#endif
                    if (index == WaitHandle.WaitTimeout) {
                        return null;
                    }
                } catch (Exception e) {
                    throw RubyExceptions.CreateEINVAL(e.Message, e);
                }

                result = new RubyArray();
                int handleIndex = 0;
                result.Add(MakeResult(handles, ref handleIndex, index, read));
                result.Add(MakeResult(handles, ref handleIndex, index, write));
                result.Add(MakeResult(handles, ref handleIndex, index, error));
            } finally {
                // should we close the handles? 
                //if (handles != null) {
                //    for (int i = 0; i < handles.Length; i++) {
                //        if (handles[i] != null) {
                //            handles[i].Close();
                //        }
                //    }
                //}
            }
            return result;
        }