Ejemplo n.º 1
0
        public static MutableString FastXs(RubyContext /*!*/ context, MutableString /*!*/ self)
        {
            //TODO: we are assuming that every string is UTF8, but this is wrong
            String        utf8String = Encoding.UTF8.GetString(self.ToByteArray());
            StringBuilder builder    = new StringBuilder((int)(utf8String.Length * 1.5));

            Entities.XML.Escape(builder, utf8String);
            return(MutableString.CreateAscii(builder.ToString()));
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
0
            public static MutableString /*!*/ HexDigest(RubyClass /*!*/ self,
                                                        [NotNull] DigestFactory.Digest /*!*/ digest,
                                                        [NotNull] MutableString /*!*/ key,
                                                        [NotNull] MutableString /*!*/ data)
            {
                byte[] hash = Digest(digest, key, data);

                // TODO (opt):
                return(MutableString.CreateAscii(BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant()));
            }
Ejemplo n.º 4
0
                public static MutableString /*!*/ BlankHexDigest(Digest /*!*/ self)
                {
#if !SILVERLIGHT
                    byte[] blank_data = Encoding.UTF8.GetBytes("");
                    byte[] hash       = new SHA1CryptoServiceProvider().ComputeHash(blank_data);
                    return(MutableString.CreateAscii(BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant()));
#else
                    throw new NotSupportedException();
#endif
                }
Ejemplo n.º 5
0
 public static MutableString Subject(Certificate /*!*/ self)
 {
     if (self.IsEmpty)
     {
         return(null);
     }
     else
     {
         return(MutableString.CreateAscii(OpenSSLFormat(self._certificate.Subject)));
     }
 }
Ejemplo n.º 6
0
 internal static MutableString /*!*/ HostNameToMutableString(RubyContext /*!*/ context, string /*!*/ str)
 {
     if (str.IsAscii())
     {
         return(MutableString.CreateAscii(str));
     }
     else
     {
         return(MutableString.Create(str, context.GetPathEncoding()));
     }
 }
Ejemplo n.º 7
0
 public static MutableString Issuer(Certificate /*!*/ self)
 {
     if (self._certificate.Handle == IntPtr.Zero)
     {
         return(null);
     }
     else
     {
         return(MutableString.CreateAscii(OpenSSLFormat(self._certificate.Issuer)));
     }
 }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        public static void Print(BinaryOpStorage /*!*/ writeStorage, object /*!*/ self, object value)
        {
            Protocols.Write(writeStorage, self, value ?? MutableString.CreateAscii("nil"));

            MutableString delimiter = writeStorage.Context.OutputSeparator;

            if (delimiter != null)
            {
                Protocols.Write(writeStorage, self, delimiter);
            }
        }
Ejemplo 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);
        }
Ejemplo n.º 11
0
        public static MutableString JsonCreate(ConversionStorage <IntegerValue> /*!*/ integerConversion,
                                               RubyClass /*!*/ self, Hash /*!*/ creatable)
        {
            RubyArray           raw    = (RubyArray)creatable[MutableString.CreateAscii("raw")];
            MutableStringStream stream = new MutableStringStream();

            for (int i = 0; i < raw.Count; i++)
            {
                stream.WriteByte(unchecked ((byte)Protocols.CastToUInt32Unchecked(integerConversion, raw[i])));
            }
            return(stream.String);
        }
Ejemplo n.º 12
0
 public static MutableString PublicKey(Certificate /*!*/ self)
 {
     if (self.IsEmpty)
     {
         // TODO: Raise OpenSSL::X509::CertificateError
         return(MutableString.CreateEmpty());
     }
     else
     {
         return(MutableString.CreateAscii(self._certificate.GetPublicKeyString()));
     }
 }
Ejemplo n.º 13
0
        public void InitializeLibrary(RubyScope scope)
        {
            KernelOps.Require(scope, this, MutableString.CreateAscii("json/common"));

            _maxNesting      = scope.RubyContext.CreateAsciiSymbol("max_nesting");
            _allowNan        = scope.RubyContext.CreateAsciiSymbol("allow_nan");
            _jsonCreatable   = scope.RubyContext.CreateAsciiSymbol("json_creatable?");
            _jsonCreate      = scope.RubyContext.CreateAsciiSymbol("json_create");
            _createId        = scope.RubyContext.CreateAsciiSymbol("create_id");
            _createAdditions = scope.RubyContext.CreateAsciiSymbol("create_additions");
            _chr             = scope.RubyContext.CreateAsciiSymbol("chr");
        }
Ejemplo n.º 14
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);
        }
Ejemplo n.º 15
0
        private object Rackup()
        {
            Utils.Log("=> Loading Rack application");
            var fullPath = Path.Combine(_appRoot, "config.ru");

            if (File.Exists(fullPath))
            {
                return(IronRubyEngine.ExecuteMethod <RubyArray>(
                           IronRubyEngine.Execute("Rack::Builder"),
                           "parse_file", MutableString.CreateAscii(fullPath))[0]);
            }
            return(null);
        }
Ejemplo n.º 16
0
        public void Dir1()
        {
            RubyClass dir    = Context.GetClass(typeof(RubyDir));
            Pal1      pal    = (Pal1)Context.Platform;
            var       sjis   = RubyEncoding.KCodeSJIS.StrictEncoding.GetBytes("ホ");
            var       toPath = new ConversionStorage <MutableString>(Context);

            // transcode to UTF8 if no KCODE specified
            Context.KCode = null;
            RubyDir.MakeDirectory(toPath, dir, MutableString.CreateBinary(new byte[] { 0xce, 0xa3 }, RubyEncoding.Binary), null);
            Assert(pal.Entries["Σ"]);
            pal.Entries.Clear();

            // transcode to UTF8 if no KCODE specified
            Context.KCode = null;
            RubyDir.MakeDirectory(toPath, dir, MutableString.CreateMutable("ホア", RubyEncoding.KCodeSJIS), null);
            Assert(pal.Entries["α"]);
            Assert(FileTest.IsDirectory(toPath, Context.KernelModule, MutableString.CreateMutable("ホア", RubyEncoding.KCodeSJIS)));
            Assert(FileTest.IsDirectory(toPath, Context.KernelModule, MutableString.CreateMutable("α", RubyEncoding.KCodeUTF8)));
            pal.Entries.Clear();

            // transcode to KCODE if specified
            Context.KCode = RubyEncoding.KCodeUTF8;
            RubyDir.MakeDirectory(toPath, dir, MutableString.CreateBinary(new byte[] { 0xce, 0xa3 }, RubyEncoding.KCodeSJIS), null);
            Assert(pal.Entries["Σ"]);
            pal.Entries.Clear();

            // transcode to KCODE if specified
            Context.KCode = RubyEncoding.KCodeSJIS;
            RubyDir.MakeDirectory(toPath, dir, MutableString.CreateBinary(sjis, RubyEncoding.Binary), null);
            Assert(pal.Entries["ホ"]);
            pal.Entries.Clear();

            // ignore entries whose name cannot be encoded using the current KCODE
            Context.KCode = RubyEncoding.KCodeSJIS;
            AssertExceptionThrown <EncoderFallbackException>(() => RubyEncoding.KCodeSJIS.StrictEncoding.GetBytes("Ԋ"));
            pal.Entries["Ԋ"] = true;
            pal.Entries["ホ"] = true;
            var entries = RubyDir.GetEntries(toPath, dir, MutableString.CreateEmpty());

            Assert(entries.Count == 3);
            foreach (MutableString entry in entries)
            {
                Assert(entry.Encoding == RubyEncoding.KCodeSJIS);
            }

            Assert(((MutableString)entries[0]).Equals(MutableString.CreateAscii(".")));
            Assert(((MutableString)entries[1]).Equals(MutableString.CreateAscii("..")));
            Assert(((MutableString)entries[2]).Equals(MutableString.Create("ホ", RubyEncoding.KCodeSJIS)));
        }
Ejemplo n.º 17
0
        public void LibraryLoader1()
        {
            Context.DefineGlobalVariable("lib_name", MutableString.CreateAscii(typeof(TestLibraryInitializer1).AssemblyQualifiedName));

            AssertOutput(delegate() {
                CompilerTest(@"
require($lib_name)
puts TEST_LIBRARY
puts object_monkey
");
            }, @"
hello from library
This is monkey!
");
        }
Ejemplo n.º 18
0
 public static MutableString ToJson(Double self, GeneratorState state)
 {
     if (Double.IsInfinity(self) || Double.IsNaN(self))
     {
         if (state != null && state.AllowNaN == false)
         {
             Helpers.ThrowGenerateException(String.Format("{0} not allowed in JSON", self));
         }
         return(MutableString.CreateAscii(self.ToString(NumberFormatInfo.InvariantInfo)));
     }
     else
     {
         return(MutableString.CreateAscii(self.ToString(NumberFormatInfo.InvariantInfo)));
     }
 }
Ejemplo n.º 19
0
        public static void Print(BinaryOpStorage /*!*/ writeStorage, object self, params object[] /*!*/ args)
        {
            // MRI: StringIO#print is different from PrintOps.Print - it doesn't output delimiter after each arg.
            MutableString delimiter = writeStorage.Context.OutputSeparator;

            foreach (object arg in args)
            {
                Protocols.Write(writeStorage, self, arg ?? MutableString.CreateAscii("nil"));
            }

            if (delimiter != null)
            {
                Protocols.Write(writeStorage, self, delimiter);
            }
        }
Ejemplo n.º 20
0
        public void ToIntToStrConversion1()
        {
            Context.DefineGlobalVariable("protocol_tester", MutableString.CreateAscii(typeof(DefaultProtocolTester).AssemblyQualifiedName));

            Engine.Execute(StrIntDeclarations);

            AssertOutput(delegate() {
                CompilerTest(@"
p Tests.to_int_to_str(123)
p Tests.to_int_to_str('xxx')
p Tests.to_int_to_str(A.new)
p Tests.to_int_to_str(B.new)
p Tests.to_int_to_str(C.new)
p Tests.to_int_to_str(E.new) rescue puts $!
");
            }, @"
[123, nil]
[0, ""xxx""]
[0, ""A""]
[1, nil]
[2, nil]
to_int
to_str
can't convert E into String
");

            AssertOutput(delegate() {
                CompilerTest(@"
p Tests.to_str_to_int(123)
p Tests.to_str_to_int('xxx')
p Tests.to_str_to_int(A.new)
p Tests.to_str_to_int(B.new)
p Tests.to_str_to_int(C.new)
p Tests.to_str_to_int(E.new) rescue puts $!
");
            }, @"
[nil, 123]
[""xxx"", 0]
[""A"", 0]
[nil, 1]
[""C"", 0]
to_str
to_int
can't convert E into Fixnum
");
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
0
        public void LibraryLoader2()
        {
            Context.DefineGlobalVariable("lib_name", MutableString.CreateAscii(typeof(TestLibraryInitializer2).AssemblyQualifiedName));

            TestOutput(@"
module LibModule
  def self.foo
    'foo'
  end
end
require($lib_name)
puts LibModule.foo
puts LibModule.bar
", @"
foo
bar
");
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
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);
        }
Ejemplo n.º 25
0
        public void Dir2()
        {
            RubyClass dir  = Context.GetClass(typeof(RubyDir));
            Pal1      pal  = (Pal1)Context.Platform;
            var       sjis = RubyEncoding.KCodeSJIS.StrictEncoding.GetBytes("ホ");

            // use the string encoding if given
            RubyDir.MakeDirectory(dir, MutableString.CreateBinary(sjis, RubyEncoding.KCodeSJIS.RealEncoding), null);
            Assert(pal.Entries["ホ"]);

            // IO system returns UTF8 encoded strings:
            var entries = RubyDir.GetEntries(dir, MutableString.CreateEmpty());

            Assert(entries.Count == 3);
            Assert(((MutableString)entries[0]).Equals(MutableString.CreateAscii(".")));
            Assert(((MutableString)entries[1]).Equals(MutableString.CreateAscii("..")));
            Assert(((MutableString)entries[2]).Equals(MutableString.Create("ホ", RubyEncoding.UTF8)));

            pal.Entries.Clear();
        }
Ejemplo n.º 26
0
        public void ObjectOperations1()
        {
            var cls = Engine.Execute(@"
class C
  def foo *a
    p a
  end
  self
end
");
            var obj = Engine.Operations.CreateInstance(cls) as RubyObject;

            Assert(obj != null && obj.ImmediateClass.Name == "C");

            obj = Engine.Operations.InvokeMember(cls, "new") as RubyObject;
            Assert(obj != null && obj.ImmediateClass.Name == "C");

            var foo = Engine.Operations.GetMember(obj, "foo") as RubyMethod;

            Assert(foo != null && foo.Name == "foo" && foo.Target == obj);

            AssertOutput(() => Engine.Operations.Invoke(foo, 1, 2), "[1, 2]");
            AssertOutput(() => Engine.Operations.InvokeMember(obj, "foo", 1, 2), "[1, 2]");

            var str = Engine.Operations.ConvertTo <string>(MutableString.CreateAscii("foo"));

            Assert(str == "foo");

            str = Engine.Operations.ConvertTo <string>(Engine.Execute <object>("class C; def to_str; 'bar'; end; new; end"));
            Assert(str == "bar");

            var b = Engine.Operations.ConvertTo <byte>(Engine.Execute <object>("class C; def to_int; 123; end; new; end"));

            Assert(b == 123);

            var lambda = Engine.Operations.ConvertTo <Func <int, int> >(Engine.Execute <object>("lambda { |x| x * 2 }"));

            Assert(lambda(10) == 20);

            Assert((int)Engine.CreateOperations().InvokeMember(null, "to_i") == 0);
        }
Ejemplo n.º 27
0
        public static MutableString /*!*/ ToString(BigDecimal /*!*/ self, [DefaultProtocol][NotNull] MutableString /*!*/ format)
        {
            string posSign    = "";
            int    separateAt = 0;

            Match m                = Regex.Match(format.ConvertToString(), @"^(?<posSign>[+ ])?(?<separateAt>\d+)?(?<floatFormat>[fF])?", RegexOptions.ExplicitCapture);
            Group posSignGroup     = m.Groups["posSign"];
            Group separateAtGroup  = m.Groups["separateAt"];
            Group floatFormatGroup = m.Groups["floatFormat"];

            if (posSignGroup.Success)
            {
                posSign = m.Groups["posSign"].Value;
            }
            if (separateAtGroup.Success)
            {
                separateAt = Int32.Parse(m.Groups["separateAt"].Value, CultureInfo.InvariantCulture);
            }
            bool floatFormat = floatFormatGroup.Success;

            return(MutableString.CreateAscii(self.ToString(separateAt, posSign, floatFormat)));
        }
Ejemplo n.º 28
0
        private static Hash CreateDefaultTagMapping(RubyContext /*!*/ context)
        {
            Hash taggedClasses = new Hash(context.EqualityComparer);

            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:array"), context.GetClass(typeof(RubyArray)));
            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:exception"), context.GetClass(typeof(Exception)));
            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:hash"), context.GetClass(typeof(Hash)));
            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:object"), context.GetClass(typeof(object)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.RubyRange), context.GetClass(typeof(Range)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.RubyRegexp), context.GetClass(typeof(RubyRegex)));
            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:string"), context.GetClass(typeof(MutableString)));
            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:struct"), context.GetClass(typeof(RubyStruct)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.RubySymbol), context.GetClass(typeof(RubySymbol)));
            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:symbol"), context.GetClass(typeof(RubySymbol)));
            taggedClasses.Add(MutableString.CreateAscii("tag:ruby.yaml.org,2002:time"), context.GetClass(typeof(RubyTime)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.Binary), context.GetClass(typeof(MutableString)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.Float), context.GetClass(typeof(Double)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.Int), context.GetClass(typeof(Integer)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.Map), context.GetClass(typeof(Hash)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.Seq), context.GetClass(typeof(RubyArray)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.Str), context.GetClass(typeof(MutableString)));
            taggedClasses.Add(MutableString.CreateAscii(Tags.Timestamp), context.GetClass(typeof(RubyTime)));

            taggedClasses.Add(MutableString.CreateAscii(Tags.False), context.FalseClass);
            taggedClasses.Add(MutableString.CreateAscii(Tags.True), context.TrueClass);
            taggedClasses.Add(MutableString.CreateAscii(Tags.Null), context.NilClass);

            //if (ctor.GlobalScope.Context.TryGetModule(ctor.GlobalScope, "Date", out module)) {
            //    taggedClasses.Add(MutableString.CreateAscii(Tags.TimestampYmd), context.NilClass);
            //}

            //taggedClasses.Add(MutableString.CreateAscii("tag:yaml.org,2002:timestamp#ymd'"), );
            //Currently not supported
            //taggedClasses.Add(MutableString.CreateAscii("tag:yaml.org,2002:omap"), ec.GetClass(typeof()));
            //taggedClasses.Add(MutableString.CreateAscii("tag:yaml.org,2002:pairs"),//    ec.GetClass(typeof()));
            //taggedClasses.Add(MutableString.CreateAscii("tag:yaml.org,2002:set"),//    ec.GetClass(typeof()));
            return(taggedClasses);
        }
Ejemplo n.º 29
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);
        }
Ejemplo n.º 30
0
 public static MutableString /*!*/ Name(Digest /*!*/ self)
 {
     return(MutableString.CreateAscii(self._algorithm.HashName));
 }