public static object dosync(RubyModule/*!*/ self, RubyArray args)
        {
            object res = null;
            try
            {
                boolean bShowStatus = true;	
                String query_params = "";
                if ( args != null && args.Count > 0 )	
                {
                    String str = ((MutableString)args[0]).ToString();	
                    //bShowStatus = args[0].Equals(RubyConstant.QTRUE)||"true".equalsIgnoreCase(str);	
                    bShowStatus = "true".equalsIgnoreCase(str);	
                }
        
                if (args != null && args.Count > 1)
                    query_params = ((MutableString)args[1]).ToString();
                
                SyncThread.getInstance().addQueueCommand(new SyncThread.SyncCommand(SyncThread.scSyncAll, bShowStatus, query_params));

                res = SyncThread.getInstance().getRetValue();
            }
            catch (Exception ex)
            {
                Exception rubyEx = self.Context.CurrentException;
                if (rubyEx == null)
                {
                    rubyEx = RubyExceptionData.InitializeException(new RuntimeError(ex.Message.ToString()), ex.Message);
                }
                LOG.ERROR("dosync", ex);
                throw rubyEx;
            }

            return res;
        }
Exemple #2
0
 public Script(int section, string title, string text)
 {
     _rmScript = new RubyArray() { section, Ruby.ConvertString(title), Ruby.ZlibDeflate(text)};
       _section = section;
       _name = title;
       UpdateTabName();
 }
Exemple #3
0
 internal RubyArray/*!*/ GetMembers(RubyContext/*!*/ context) {
     RubyArray list = new RubyArray(_names.Length);
     foreach (string id in _names) {
         list.Add(context.StringifyIdentifier(id));
     }
     return list;
 }
Exemple #4
0
 public RhoParamArray(RhoParams oParams, String name) : base(oParams)
 {
     m_array = null;
     Object ar = findHashParam(name);
     if (ar != null && (ar is RubyArray))
         m_array = (RubyArray)ar;    
 }
Exemple #5
0
 internal RubyArray/*!*/ GetMembers() {
     RubyArray list = new RubyArray(Members.Length);
     foreach (string id in Members) {
         list.Add(MutableString.Create(id));
     }
     return list;
 }
Exemple #6
0
 public Script(RubyArray rmScript)
 {
     _rmScript = rmScript;
       _section = (int)_rmScript[0];
       _name = Ruby.ConvertString((MutableString)_rmScript[1]);
       UpdateTabName();
 }
        // Called lazily to create a Ruby backtrace.
        private void CreateBacktrace() {
            RubyArray result;

            int skipFrames = 0;
            bool hasFileAccessPermissions = DetectFileAccessPermissions();

#if SILVERLIGHT // TODO: StackTrace.ctor(exception) security critical
            // throw-site trace is built already:
            result = _backtrace ?? new RubyArray();
#else
            result = new RubyArray();
            if (_throwSiteTrace == null) {
                SetCompiledTrace();
            }

            AddBacktrace(result, _throwSiteTrace.GetFrames(), hasFileAccessPermissions, skipFrames);
#endif
            if (_catchSiteTrace != null) {
                // skip one frame - the catch-site frame is already included
                AddBacktrace(result, _catchSiteTrace.GetFrames(), hasFileAccessPermissions, 1);
            }

            _backtrace = result;
            _backtraceInitialized = true;
        }
Exemple #8
0
 public static Node ToYamlNode(RubyContext/*!*/ context, RubyArray/*!*/ self, [NotNull]RubyRepresenter/*!*/ rep)
 {
     return rep.Sequence(
         rep.GetTagUri(self, Tags.Seq, typeof(RubyArray)),
         self,
         rep.GetYamlStyle(self) != ScalarQuotingStyle.None ? FlowStyle.Inline : FlowStyle.Block
     );
 }
Exemple #9
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;
 }
Exemple #10
0
        public static void Create(RubyModule/*!*/ self, int barType, RubyArray args)
        {
            if (args != null && args.Count > 0)
                RhodesApp.createToolBar(barType, (Object)args);

            if (barType == 2)
                RhodesApp.removeToolBar();
        }
Exemple #11
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();
                        }

                        try
                        {
                            self.m_db.Lock();
                            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);
                                    }
                                }
                            }
                        }
                        finally
                        {
                            self.m_db.Unlock();
                        }
                    }

                    return retArr;
                }catch (Exception exc)
                {
                    //TODO: throw ruby exception
                    throw exc;
                }
            }
Exemple #12
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;
 }
Exemple #13
0
            public static void destroyTables(RhoDatabase/*!*/ self, RubyArray arInclude, RubyArray arExclude)
            {
                Vector<String> vecIncludes = RhoRuby.makeVectorStringFromArray(arInclude);
                Vector<String> vecExcludes = RhoRuby.makeVectorStringFromArray(arExclude);

                self.m_db.rb_destroy_tables(vecIncludes, vecExcludes);

                //throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
                //TODO: threw ruby exception

            }
Exemple #14
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;
        }
Exemple #15
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;
        }
Exemple #16
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;
        }
        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;
        }
Exemple #18
0
 public static RubyArray Map(RubyContext/*!*/ context, BlockParam collector, object self) {
     RubyArray result = new RubyArray();
     Each(context, self, Proc.Create(context, delegate(BlockParam/*!*/ selfBlock, object item) {
         if (collector != null) {
             if (collector.Yield(item, out item)) {
                 return item;
             }
         }
         result.Add(item);
         return null;
     }));
     return result;
 }
Exemple #19
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;
 }
Exemple #20
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)));
        }
Exemple #21
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;
        }
Exemple #22
0
            public static void destroyTables(RhoDatabase/*!*/ self, RubyArray arInclude, RubyArray arExclude)
            {
                try
                {
                    Vector<String> vecIncludes = RhoRuby.makeVectorStringFromArray(arInclude);
                    Vector<String> vecExcludes = RhoRuby.makeVectorStringFromArray(arExclude);

                    self.m_db.rb_destroy_tables(vecIncludes, vecExcludes);
                }
                catch (Exception ex)
                {
                    LOG.HandleRubyException(ex, RhoRuby.rubyContext.CurrentException, "destroy_tables");
                }
            }
Exemple #23
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;
        }
        internal RubyInputProvider(RubyContext/*!*/ context, ICollection<string>/*!*/ arguments) {
            Assert.NotNull(context);
            Assert.NotNullItems(arguments);
            _context = context;

            var args = new RubyArray();
            foreach (var arg in arguments) {
                ExpandArgument(args, arg);
            }

            _commandLineArguments = args;
            _lastInputLineNumber = 1;
            _singleton = new object();
        }
Exemple #25
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);
        }
        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));
            }
        }
Exemple #27
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));
            }
        }
Exemple #28
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;
        }
        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;
        }
Exemple #30
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;
        }
Exemple #31
0
        public Vector <String> makeVectorStringFromArray(RubyArray ar)
        {
            Vector <String> arRes = new Vector <String>();

            for (int i = 0; ar != null && i < ar.Count; i++)
            {
                Object item = ar[i];
                if (item != null && item is MutableString)
                {
                    arRes.Add(((MutableString)item).ToString());
                }
                else
                {
                    arRes.Add(String.Empty);
                }
            }

            return(arRes);
        }
Exemple #32
0
        public void RubyArray_Misc()
        {
            RubyArray a;

            a = new RubyArray(new[] { 3, 5, 2, 4, 1 });
            a.InsertRange(0, new[] { 10, 20 });
            a.RemoveRange(0, 2);

            a.Sort();
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 1, 2, 3, 4, 5 }));
            a.Sort((x, y) => (int)x == (int)y ? 0 : ((int)x < (int)y ? 1 : -1));
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 5, 4, 3, 2, 1 }));
            a.Reverse();
            Assert(ArrayUtils.ValueEquals(a.ToArray(), new object[] { 1, 2, 3, 4, 5 }));

            a.Freeze();
            AssertExceptionThrown <InvalidOperationException>(() => a.Reverse());
            AssertExceptionThrown <InvalidOperationException>(() => a.Sort());
        }
        public static RubyArray /*!*/ ReadLines(StringIO /*!*/ self, [DefaultProtocol] MutableString separator, [DefaultProtocol] int limit)
        {
            var       content = self.GetReadableContent();
            RubyArray result  = new RubyArray();

            // TODO: limit

            // no dynamic call, doesn't modify $_ scope variable:
            MutableString line;
            int           position = self._position;

            while ((line = ReadLine(content, separator, ref position)) != null)
            {
                result.Add(line);
                self._lineNumber++;
            }
            self._position = position;
            return(result);
        }
Exemple #34
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);
        }
Exemple #35
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);
        }
Exemple #36
0
        /// <summary>
        /// If the SCRIPT_LINES__ constant is set, we need to publish the file being loaded,
        /// along with the contents of the file
        /// </summary>
        private void AddScriptLines(SourceUnit file)
        {
            ConstantStorage storage;

            if (!_context.ObjectClass.TryResolveConstant(null, "SCRIPT_LINES__", out storage))
            {
                return;
            }

            IDictionary scriptLines = storage.Value as IDictionary;

            if (scriptLines == null)
            {
                return;
            }

            lock (scriptLines) {
                // Read in the contents of the file

                RubyArray        lines    = new RubyArray();
                SourceCodeReader reader   = file.GetReader();
                RubyEncoding     encoding = RubyEncoding.GetRubyEncoding(reader.Encoding);
                using (reader) {
                    reader.SeekLine(1);
                    while (true)
                    {
                        string lineStr = reader.ReadLine();
                        if (lineStr == null)
                        {
                            break;
                        }
                        MutableString line = MutableString.CreateMutable(lineStr.Length + 1, encoding);
                        line.Append(lineStr).Append('\n');
                        lines.Add(line);
                    }
                }

                // Publish the contents of the file, keyed by the file name
                MutableString path = MutableString.Create(file.Document.FileName, _context.GetPathEncoding());
                scriptLines[path] = lines;
            }
        }
Exemple #37
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);
        }
Exemple #38
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);
        }
Exemple #39
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);
        }
Exemple #40
0
        public static Node ToYamlNode(RubyStruct /*!*/ self, [NotNull] RubyRepresenter /*!*/ rep)
        {
            RubyContext context = self.Class.Context;
            RubyArray   members = _Members.Target(_Members, context, self);
            RubyArray   values  = _Values.Target(_Values, context, self);

            if (members.Count != values.Count)
            {
                throw new ArgumentException("Struct values and members returned arrays of different lengths");
            }

            Hash map = new Hash(self.Class.Context);

            for (int i = 0; i < members.Count; i++)
            {
                IDictionaryOps.SetElement(context, map, members[i], values[i]);
            }
            RubyRepresenter.AddYamlProperties(context, self, map);
            return(rep.Map(self, map));
        }
Exemple #41
0
        public RubyToken Convert(JToken json)
        {
            switch (json.Type)
            {
            case JTokenType.Array:
                var arrayToken = new RubyArray();
                foreach (var item in (JArray)json)
                {
                    arrayToken.Add(Convert(item));
                }
                return(arrayToken);

            case JTokenType.Object:
                var objectToken = new RubyObject();
                var jsonObject  = (JObject)json;
                foreach (var property in jsonObject)
                {
                    if (property.Key == "typeName")
                    {
                        objectToken.RubyClass.Name = property.Value.Value <string>();
                    }
                    else
                    {
                        objectToken[property.Key] = Convert(property.Value);
                    }
                }
                return(objectToken);

            case JTokenType.Null:
                return(new RubyValue((object)null));

            case JTokenType.Boolean:
                return(new RubyValue(json.Value <bool>()));

            case JTokenType.String:
                return(new RubyValue(json.Value <string>()));

            default:
                return(new RubyValue(((JValue)json).Value));
            }
        }
Exemple #42
0
        public static RubyArray /*!*/ GetNameInfo(ConversionStorage <MutableString> /*!*/ stringCast, ConversionStorage <int> /*!*/ fixnumCast,
                                                  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");
            }

            RubyContext context = self.Context;

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

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

            // Lookup the service name for the given port.
            int         port    = ConvertToPortNum(stringCast, fixnumCast, 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.
            object      hostName = (hostInfo.Count > 3 && hostInfo[3] != null) ? hostInfo[3] : hostInfo[2];
            IPHostEntry entry    = GetHostEntry(ConvertToHostString(stringCast, hostName), false);

            RubyArray result = new RubyArray(2);

            result.Add(HostNameToMutableString(context, entry.HostName));
            if (service != null)
            {
                result.Add(MutableString.Create(service.Name));
            }
            else
            {
                result.Add(port);
            }
            return(result);
        }
Exemple #43
0
        // R(N, *, =)
        public override object InvokeSplatRhs(BlockParam /*!*/ param, object self, object[] /*!*/ args, object splattee, object rhs)
        {
            var array = new RubyArray(args);

            RubyOps.SplatAppend(array, splattee);
            array.Add(rhs);

            if (array.Count == 1)
            {
                return(_block(param, self, rhs));
            }

            Debug.Assert(array.Count >= 2);

            if (!HasSingleCompoundParameter)
            {
                param.MultipleValuesForBlockParameterWarning(array.Count);
            }

            return(_block(param, self, array));
        }
Exemple #44
0
 private void AddAbsoluteLibraryPaths(RubyArray /*!*/ result, string applicationBaseDir, ICollection <string> /*!*/ paths)
 {
     foreach (var path in paths)
     {
         string fullPath;
         if (applicationBaseDir != null)
         {
             try {
                 fullPath = Platform.IsAbsolutePath(path) ? path : Platform.GetFullPath(Path.Combine(applicationBaseDir, path));
             } catch (Exception) {
                 // error will be reported on first require:
                 fullPath = path;
             }
         }
         else
         {
             fullPath = path;
         }
         result.Add(_context.EncodePath(fullPath.Replace('\\', '/')));
     }
 }
Exemple #45
0
        internal void SetCompiledTrace()
        {
            Debug.Assert(!_backtraceInitialized);

#if SILVERLIGHT // TODO: StackTrace.ctor(exception) security critical
            _catchSiteTrace = new StackTrace();

            var result = new RubyArray();
            foreach (string line in _exception.StackTrace.Split('\n'))
            {
                string frame = line.Trim();
                if (frame.StartsWith("at "))
                {
                    frame = frame.Substring("at ".Length);
                }

                if (frame.StartsWith("_stub_") ||
                    frame.StartsWith("Microsoft.Scripting") ||
                    frame.StartsWith("System.Runtime") ||
                    frame.StartsWith("IronRuby.Builtins.Kernel.RaiseException") ||
                    frame.StartsWith("IronRuby.Builtins.Kernel.MethodMissing"))
                {
                    continue;
                }

                int    lineNumber = 0;
                string fileName   = null;
                string methodName = frame;
                TryParseRubyMethodName(ref methodName, ref fileName, ref lineNumber);
                result.Add(FormatFrame(methodName, lineNumber, fileName));
            }

            // save partial trace:
            _backtrace = result;
#else
            _catchSiteTrace = new StackTrace(true);
            _throwSiteTrace = new StackTrace(_exception, true);
#endif
        }
Exemple #46
0
    public void setResult(RubyArray array)
    {
        int length = array.Count;

        if (length > answerArray.Length)
        {
            return;
        }
        for (int i = 0; i < length; i++)
        {
            if (array[i].GetType() == typeof(MutableString))
            {
                MutableString value = (MutableString)array[i];
                if (value.ToString() == "on")
                {
                    playerArray[i] = 1;
                }
                else if (value.ToString() == "off")
                {
                    playerArray[i] = 0;
                }
            }
        }

        //画像差し替え
        for (int i = 0; i < shields.Length; i++)
        {
            Debug.Log(i);
            if (playerArray[i] == 1)
            {
                shields[i].GetComponent <SpriteRenderer>().sprite = on_img;
            }
            else
            {
                shields[i].GetComponent <SpriteRenderer>().sprite = off_img;
            }
        }
    }
Exemple #47
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);
        }
Exemple #48
0
        public static Node ToYamlNode(MutableString /*!*/ self, [NotNull] RubyRepresenter /*!*/ rep)
        {
            if (RubyOps.IsTrue(_IsBinaryData.Target(_IsBinaryData, rep.Context, self)))
            {
                return(rep.BaseCreateNode(self.ConvertToBytes()));
            }

            string    str   = self.ConvertToString();
            RubyArray props = RubyRepresenter.ToYamlProperties(rep.Context, self);

            if (props.Count == 0)
            {
                MutableString taguri = RubyRepresenter.TagUri(rep.Context, self);

                char style = (char)0;
                if (str.StartsWith(":"))
                {
                    style = '"';
                }
                else
                {
                    MutableString styleStr = RubyRepresenter.ToYamlStyle(rep.Context, self) as MutableString;
                    if (styleStr != null && styleStr.Length > 0)
                    {
                        style = styleStr.GetChar(0);
                    }
                }

                return(rep.Scalar(taguri != null ? taguri.ConvertToString() : "", str, style));
            }

            Hash map = new Hash(rep.Context);

            map.Add(MutableString.Create("str"), str);
            RubyRepresenter.AddYamlProperties(rep.Context, self, map, props);
            return(rep.Map(self, map));
        }
        private object InvokeSplatInternal(BlockParam /*!*/ param, object self, Proc procArg, object[] /*!*/ args, IList /*!*/ splattee)
        {
            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:
            while (nextItem < splattee.Count)
            {
                array.Add(splattee[nextItem++]);
            }

            return(_block(param, self, args, array));
        }
Exemple #50
0
        internal static RubyArray /*!*/ CreateHostEntryArray(IPHostEntry hostEntry, bool packIpAddresses)
        {
            RubyArray result = new RubyArray(4);

            // Canonical Hostname
            result.Add(MutableString.Create(hostEntry.HostName));

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

            foreach (string alias in hostEntry.Aliases)
            {
                aliases.Add(MutableString.Create(alias));
            }
            result.Add(aliases);

            // Address Type
            result.Add((int)hostEntry.AddressList[0].AddressFamily);

            // IP Address
            foreach (IPAddress address in hostEntry.AddressList)
            {
                if (packIpAddresses)
                {
                    byte[]        bytes = address.GetAddressBytes();
                    MutableString str   = MutableString.CreateBinary();
                    str.Append(bytes, 0, bytes.Length);
                    result.Add(str);
                }
                else
                {
                    result.Add(MutableString.Create(address.ToString()));
                }
            }
            return(result);
        }
        /// <summary>
        ///     static void w_object(VALUE obj, struct dump_arg *arg, int limit)
        /// </summary>
        /// <param name="obj"></param>
        public void WriteObject(object obj)
        {
            int num;

            if (_m_objects.TryGetValue(obj, out num))
            {
                WriteByte(RubyMarshal.Types.LINK);
                WriteLong(num);
                return;
            }
            if (obj == null || obj == RubyNil.Instance)
            {
                WriteByte(RubyMarshal.Types.NIL);
            }
            else if (obj is bool && (bool)obj)
            {
                WriteByte(RubyMarshal.Types.TRUE);
            }
            else if (obj is bool && (bool)obj == false)
            {
                WriteByte(RubyMarshal.Types.FALSE);
            }
            else if (obj is RubyBool ruby_bool)
            {
                WriteByte(ruby_bool.Value ? RubyMarshal.Types.TRUE : RubyMarshal.Types.FALSE);
            }
            else if (obj is int || obj is long || obj is RubyFixnum)
            {
                long v;
                if (obj is int | obj is long)
                {
                    v = (long)obj;
                }
                else
                {
                    v = ((RubyFixnum)obj).Value;
                }
                // (2**30).class   => Bignum
                // (2**30-1).class => Fixnum
                // (-2**30-1).class=> Bignum
                // (-2**30).class  => Fixnum
                if (v <= RubyFixnum.MaxValue && v >= RubyFixnum.MinValue)
                {
                    WriteByte(RubyMarshal.Types.FIXNUM);
                    WriteLong((int)v);
                }
                else
                {
                    WriteObject(RubyBignum.Create(v));
                }
            }
            else if (obj is RubySymbol ruby_symbol)
            {
                WriteSymbol(ruby_symbol);
            }

            else
            {
                var fobj  = obj as RubyObject;
                var hasiv = false;
                if (fobj != null)
                {
                    hasiv = (obj is RubyArray || obj is RubyHash) && fobj.InstanceVariables.Count > 0;
                }
                if (fobj is RubyString ruby_string)
                {
                    hasiv |= StringStyle == RubyMarshal.StringStyleType.Style19 && fobj.Encoding != null &&
                             ruby_string.Text.Length > 0;
                }

                if (obj is DefaultRubyUserDefinedMarshalDumpObject default_ruby_user_defined_marshal_dump_object)
                {
                    if (hasiv)
                    {
                        WriteByte(RubyMarshal.Types.INSTANCE_VARIABLE);
                    }
                    WriteClass(RubyMarshal.Types.USER_MARSHAL, obj, false);
                    default_ruby_user_defined_marshal_dump_object.Write(_m_writer);
                    if (hasiv)
                    {
                        WriteObjectInstanceVariable(fobj);
                    }
                    _m_objects.Add(obj, _m_objects.Count);
                    return;
                }
                if (obj is RubyUserDefinedObject ruby_user_defined_object)
                {
                    if (hasiv)
                    {
                        WriteByte(RubyMarshal.Types.INSTANCE_VARIABLE);
                    }
                    _m_writer.Write(RubyMarshal.Types.USER_DEFINED);
                    WriteSymbol(fobj.ClassName);
                    ruby_user_defined_object.Write(_m_writer);
                    if (hasiv)
                    {
                        WriteObjectInstanceVariable(fobj);
                    }
                    _m_objects.Add(obj, _m_objects.Count);
                    return;
                }

                _m_objects.Add(obj, _m_objects.Count);

                if (hasiv)
                {
                    WriteByte(RubyMarshal.Types.INSTANCE_VARIABLE);
                }

                if (obj is RubyClass ruby_class)
                {
                    WriteByte(RubyMarshal.Types.CLASS);
                    WriteCString(ruby_class.Name);
                }
                else if (obj is RubyModule ruby_module)
                {
                    WriteByte(RubyMarshal.Types.MODULE);
                    WriteCString(ruby_module.Name);
                }
                else if (obj is float _float)
                {
                    WriteByte(RubyMarshal.Types.FLOAT);
                    WriteFloat(_float);
                }
                else if (obj is double _double)
                {
                    WriteByte(RubyMarshal.Types.FLOAT);
                    WriteFloat(_double);
                }
                else if (obj is RubyFloat ruby_float)
                {
                    WriteByte(RubyMarshal.Types.FLOAT);
                    WriteFloat(ruby_float);
                }
                else if (obj is RubyBignum ruby_bignum)
                {
                    char ch;
                    if (ruby_bignum.Sign > 0)
                    {
                        ch = '+';
                    }
                    else if (ruby_bignum.Sign < 0)
                    {
                        ch = '-';
                    }
                    else
                    {
                        ch = '0';
                    }
                    _m_writer.Write((byte)ch);
                    var words = ruby_bignum.GetWords();
                    var num2  = words.Length * 2;
                    var index = words.Length - 1;

                    /*
                     * var flag = false;
                     * if (words.Length > 0 && words[index] >> 0x10 == 0)
                     * {
                     *  num--;
                     *  flag = true;
                     * }*/
                    var flag = words.Length > 0 && words[index] >> 0x10 == 0;
                    WriteLong(num2);
                    for (var i = 0; i < words.Length; i++)
                    {
                        if (flag && i == index)
                        {
                            _m_writer.Write((ushort)words[i]);
                        }
                        else
                        {
                            _m_writer.Write(words[i]);
                        }
                    }
                }
                else if (obj is RubyString || obj is string)
                {
                    RubyString v;
                    if (obj is string _string)
                    {
                        v = new RubyString(_string);
                    }
                    else
                    {
                        v = (RubyString)obj;
                    }
                    WriteUserClass(v, RubyClass.GetClass("String"));
                    WriteByte(RubyMarshal.Types.STRING);
                    WriteBytes(v.Raw);
                }
                else if (obj is RubyRegexp ruby_regexp)
                {
                    WriteUserClass(obj, RubyClass.GetClass("Regexp"));
                    WriteByte(RubyMarshal.Types.REGEXP);
                    WriteBytes(ruby_regexp.pattern.Raw);
                    WriteByte((byte)ruby_regexp.options);
                }
                else if (obj is RubyArray || obj is List <object> )
                {
                    RubyArray v;
                    if (obj is List <object> list)
                    {
                        v = new RubyArray(list);
                    }
                    else
                    {
                        v = (RubyArray)obj;
                    }
                    WriteUserClass(v, RubyClass.GetClass("Array"));
                    WriteByte(RubyMarshal.Types.ARRAY);
                    WriteLong(v.Length);
                    foreach (var t in v)
                    {
                        WriteObject(t);
                    }
                }
                else if (obj is RubyHash ruby_hash)
                {
                    WriteUserClass(obj, RubyClass.GetClass("Hash"));
                    WriteByte(ruby_hash.DefaultValue != null
                        ? RubyMarshal.Types.HASH_WITH_DEFAULT
                        : RubyMarshal.Types.HASH);
                    WriteLong(ruby_hash.Length);
                    foreach (var item in ruby_hash)
                    {
                        WriteObject(item.Key);
                        WriteObject(item.Value);
                    }
                    if (ruby_hash.DefaultValue != null)
                    {
                        WriteObject(ruby_hash.DefaultValue);
                    }
                }
                else if (obj is RubyStruct ruby_struct)
                {
                    WriteUserClass(obj, RubyClass.GetClass("Struct"));
                    WriteLong(ruby_struct.InstanceVariables.Count);
                    foreach (var item in ruby_struct.InstanceVariables)
                    {
                        WriteObject(item.Key);
                        WriteObject(item.Value);
                    }
                }
                else if (obj is RubyObject ruby_object)
                {
                    WriteClass(RubyMarshal.Types.OBJECT, obj, true);
                    WriteObjectInstanceVariable(ruby_object);
                }
                else
                {
                    throw new InvalidDataException($"can't dump {obj.GetType().FullName}");
                }
                if (hasiv)
                {
                    WriteInstanceVariable(fobj, fobj.InstanceVariables);
                }
            }
        }
 public static MutableString ToJson(RubyContext /*!*/ context, RubyArray self,
                                    [Optional] GeneratorState state, [Optional] Int32 depth)
 {
     return(Generator.ToJson(context, self, state, depth));
 }
Exemple #53
0
 public static void createNativeTabBar(RubyModule /*!*/ self, int barType, RubyArray args)
 {
 }
Exemple #54
0
 public static void destroyTables(RhoDatabase /*!*/ self, RubyArray arInclude, RubyArray arExclude)
 {
 }
Exemple #55
0
            public static RubyArray Execute(RhoDatabase /*!*/ self, MutableString /*!*/ sqlStatement, Boolean isBatch, RubyArray args)
            {
                RubyArray ret = new RubyArray();

                return(ret);
            }
Exemple #56
0
 public static void createNativeToolBar(RubyModule /*!*/ self, int barType, RubyArray args)
 {
     Create(self, barType, args);
 }
Exemple #57
0
        internal static RubyToken ReadEntry(ReadContext context, RubyDecoderOptions options)
        {
            RubyClass  rubyClass;
            int        fieldCount;
            RubyObject objectEntry;

            var type = (RubyType)context.Reader.ReadByte();

            switch (type)
            {
            case RubyType.Nil:
                return(new RubyValue((object)null));

            case RubyType.TypeLink:
                var dataId = (int)ReadNumber(context);
                if (context.Data.Count > dataId)
                {
                    return(context.Data[dataId]);
                }
                else
                {
                    throw new Exception("Failed to locate linked data");
                }

            case RubyType.Array:
                var length     = (int)ReadNumber(context);
                var arrayEntry = new RubyArray
                {
                    Array = new List <RubyToken>(length)
                };
                context.Data.Add(arrayEntry);

                for (var index = 0; index < length; index++)
                {
                    arrayEntry.Array.Add(ReadEntry(context, options));
                }

                return(arrayEntry);

            case RubyType.Object:
                rubyClass   = ReadSymbolDefinition(context);
                fieldCount  = (int)ReadNumber(context);
                objectEntry = new RubyObject
                {
                    RubyClass  = rubyClass,
                    Properties = new Dictionary <string, RubyToken>(fieldCount)
                };
                context.Data.Add(objectEntry);

                for (var fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
                {
                    var keySymbol = ReadSymbolDefinition(context);
                    var value     = ReadEntry(context, options);
                    objectEntry.Properties.Add(keySymbol.Name.TrimStart('@'), value);
                }

                return(objectEntry);

            case RubyType.UserDefined:
                rubyClass = ReadSymbolDefinition(context);
                if (options.UserDecoders != null && options.UserDecoders.TryGetValue(rubyClass.Name, out var decoder))
                {
                    ReadNumber(context);
                    var userDefinedEntry = decoder(context.Reader);
                    userDefinedEntry.RubyClass = rubyClass;
                    context.Data.Add(userDefinedEntry);
                    return(userDefinedEntry);
                }
                else
                {
                    throw new Exception($"User defined type not handled: {rubyClass.Name}");
                }

            case RubyType.Hash:
                fieldCount  = (int)ReadNumber(context);
                objectEntry = new RubyObject
                {
                    RubyClass = new RubyClass {
                        Name = "encoder:Hash"
                    },
                    Properties = new Dictionary <string, RubyToken>(fieldCount)
                };
                context.Data.Add(objectEntry);

                for (var fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++)
                {
                    var key   = ReadEntry(context, options);
                    var value = ReadEntry(context, options);
                    objectEntry.Properties.Add(key.ToString(), value);
                }

                return(objectEntry);

            case RubyType.Number:
                return(new RubyValue(ReadNumber(context)));

            case RubyType.Decimal:
                var rubyFloat = new RubyValue(ReadFloat(context));
                context.Data.Add(rubyFloat);
                return(rubyFloat);

            case RubyType.String:
                var stringEntry = ReadStringValue(context);
                context.Data.Add(stringEntry);
                return(stringEntry);

            case RubyType.True:
                return(new RubyValue(true));

            case RubyType.False:
                return(new RubyValue(false));

            default:
                throw new Exception($"Unknown type: {type}");
            }
        }
Exemple #58
0
 public void On(String pattern, RubyArray values)
 {
     System.Console.WriteLine("Registering pattern: " + pattern);
 }
 public static MutableString /*!*/ TagUri(RubyContext /*!*/ context, RubyArray /*!*/ self)
 {
     return(RubyYaml.GetTagUri(context, self, Tags.Seq, typeof(RubyArray)));
 }
 public PredicateList(RubyArray items)
 {
     _items = items;
     Populate();
 }