Example #1
0
 public static MutableString /*!*/ GetZone(RubyContext /*!*/ context, RubyTime /*!*/ self)
 {
     if (self.Kind == DateTimeKind.Utc)
     {
         return(MutableString.CreateAscii("UTC"));
     }
     else
     {
         var name = RubyTime.GetCurrentZoneName();
         if (name.IsAscii())
         {
             return(MutableString.CreateAscii(name));
         }
         else
         {
             // TODO: what encoding should we use?
             return(MutableString.Create(name, context.GetPathEncoding()));
         }
     }
 }
Example #2
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));
            }
        }
Example #3
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));
            }
        }
        public static object Shift(RubyContext /*!*/ context, object /*!*/ self)
        {
            PlatformAdaptationLayer pal       = context.DomainManager.Platform;
            IDictionary             variables = pal.GetEnvironmentVariables();

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

            foreach (DictionaryEntry entry in pal.GetEnvironmentVariables())
            {
                string key = entry.Key.ToString();
                result.Add(MutableString.Create(key).Freeze());
                result.Add(MutableString.Create(entry.Value.ToString()).Freeze());
                pal.SetEnvironmentVariable(key, null);
                break;
            }
            return(result);
        }
        public static object EachValue(RubyContext /*!*/ context, BlockParam block, object /*!*/ self)
        {
            PlatformAdaptationLayer pal       = context.DomainManager.Platform;
            IDictionary             variables = pal.GetEnvironmentVariables();

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

            foreach (DictionaryEntry entry in variables)
            {
                MutableString value = MutableString.Create(entry.Value.ToString()).Freeze();
                object        result;
                if (block.Yield(value, out result))
                {
                    return(result);
                }
            }
            return(self);
        }
Example #6
0
        public static MutableString /*!*/ ToPrintedString(RubyContext /*!*/ context, object obj)
        {
            IDictionary <object, object> hash;
            List <object> list;
            MutableString str;

            if ((list = obj as List <object>) != null)
            {
                return(IListOps.Join(context, list, Environment.NewLine));
            }
            else if ((hash = obj as IDictionary <object, object>) != null)
            {
                return(IDictionaryOps.ToString(context, hash));
            }
            else if (obj == null)
            {
                return(MutableString.Create("nil"));
            }
            else if (obj is bool)
            {
                return(MutableString.Create((bool)obj ? "true" : "false"));
            }
            else if (obj is double)
            {
                var result = MutableString.Create(obj.ToString());
                if ((double)(int)(double)obj == (double)obj)
                {
                    result.Append(".0");
                }
                return(result);
            }
            else if ((str = obj as MutableString) != null)
            {
                return(str);
            }
            else
            {
                return(RubySites.ToS(context, obj));
            }
        }
Example #7
0
        public static RubyArray /*!*/ GetEntries(object self, [NotNull] MutableString /*!*/ dirname)
        {
            string strDir = dirname.ConvertToString();

            string[] rawEntries = null;

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

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

            ret.Add(MutableString.Create("."));
            ret.Add(MutableString.Create(".."));
            foreach (string entry in rawEntries)
            {
                ret.Add(MutableString.Create(Path.GetFileName(entry)));
            }
            return(ret);
        }
Example #8
0
        public static MutableString /*!*/ DirName(RubyClass /*!*/ self, MutableString /*!*/ path)
        {
            string directoryName = path.ConvertToString();

            if (IsValidPath(path.ConvertToString()))
            {
                directoryName = Path.GetDirectoryName(path.ConvertToString());
                string fileName = Path.GetFileName(path.ConvertToString());
                if (!String.IsNullOrEmpty(fileName))
                {
                    directoryName = StripPathCharacters(path.ConvertToString().Replace(fileName, ""));
                }
            }
            else
            {
                if (directoryName.Length > 1)
                {
                    directoryName = "//";
                }
            }
            return(Glob.CanonicalizePath(MutableString.Create(String.IsNullOrEmpty(directoryName) ? "." : directoryName)));
        }
Example #9
0
        public static object Status(Thread /*!*/ self)
        {
            RubyThreadInfo.RegisterThread(Thread.CurrentThread);
            switch (self.ThreadState)
            {
            case ThreadState.WaitSleepJoin:
                return(MutableString.Create("sleep"));

            case ThreadState.Running:
                return(MutableString.Create("run"));

            case ThreadState.Aborted:
            case ThreadState.AbortRequested:
                return(null);

            case ThreadState.Stopped:
            case ThreadState.StopRequested:
                return(false);

            default:
                throw new ArgumentException("unknown thread status: " + self.ThreadState.ToString());
            }
        }
Example #10
0
 public static MutableString Inspect(RubyContext /*!*/ context, IDictionary <object, object> /*!*/ self)
 {
     using (IDisposable handle = RubyUtils.InfiniteInspectTracker.TrackObject(self)) {
         if (handle == null)
         {
             return(MutableString.Create("{...}"));
         }
         MutableString str = MutableString.CreateMutable();
         str.Append('{');
         foreach (KeyValuePair <object, object> pair in self)
         {
             if (str.Length != 1)
             {
                 str.Append(", ");
             }
             str.Append(RubySites.Inspect(context, BaseSymbolDictionary.ObjToNull(pair.Key)));
             str.Append("=>");
             str.Append(RubySites.Inspect(context, pair.Value));
         }
         str.Append('}');
         return(str);
     }
 }
Example #11
0
        public static RubyArray /*!*/ GetDefinedConstants(RubyModule /*!*/ self)
        {
            var visited = new Dictionary <string, bool>();
            var result  = new RubyArray();

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

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

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

            return(result);
        }
Example #12
0
        public MutableString /*!*/ Format()
        {
            _index   = 0;
            _buf     = new StringBuilder();
            _tainted = false;
            int modIndex;

            while ((modIndex = _format.IndexOf('%', _index)) != -1)
            {
                _buf.Append(_format, _index, modIndex - _index);
                _index = modIndex + 1;
                DoFormatCode();
            }
            _buf.Append(_format, _index, _format.Length - _index);

            MutableString result = MutableString.Create(_buf.ToString());

            if (_tainted)
            {
                KernelOps.Taint(_context, result);
            }

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

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

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

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

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

            return(result);
        }
Example #14
0
 public static MutableString /*!*/ GetPath(RubyFile /*!*/ self)
 {
     return(MutableString.Create(self.Path));
 }
Example #15
0
        // Expand directory path - these cases exist:
        //
        // 1. Empty string or nil means return current directory
        // 2. ~ with non-existent HOME directory throws exception
        // 3. ~, ~/ or ~\ which expands to HOME
        // 4. ~foo is left unexpanded
        // 5. Expand to full path if path is a relative path
        //
        // No attempt is made to determine whether the path is valid or not
        // Returned path is always canonicalized to forward slashes

        private static MutableString /*!*/ ExpandPath(RubyContext /*!*/ context, MutableString /*!*/ path)
        {
            PlatformAdaptationLayer pal = context.DomainManager.Platform;
            int length = path.Length;

            try {
                if (path == null || length == 0)
                {
                    return(Glob.CanonicalizePath(MutableString.Create(Directory.GetCurrentDirectory())));
                }

                if (length == 1 && path.GetChar(0) == '~')
                {
                    return(Glob.CanonicalizePath(MutableString.Create(Path.GetFullPath(pal.GetEnvironmentVariable("HOME")))));
                }

                if (path.GetChar(0) == '~' && (path.GetChar(1) == Path.DirectorySeparatorChar || path.GetChar(1) == Path.AltDirectorySeparatorChar))
                {
                    string homeDirectory = pal.GetEnvironmentVariable("HOME");
                    return(Glob.CanonicalizePath(length < 3 ? MutableString.Create(homeDirectory) : MutableString.Create(Path.Combine(homeDirectory, path.GetSlice(2).ConvertToString()))));
                }
                else
                {
                    return(Glob.CanonicalizePath(MutableString.Create(Path.GetFullPath(path.ConvertToString()))));
                }
            } catch (Exception e) {
                // Re-throw exception as a reasonable Ruby exception
                throw new Errno.InvalidError(path.ConvertToString(), e);
            }
        }
Example #16
0
 public static MutableString /*!*/ GetExtension(RubyClass /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ path)
 {
     return(MutableString.Create(Path.GetExtension(path.ConvertToString())).TaintBy(path));
 }
Example #17
0
 public override MutableString /*!*/ GetPattern()
 {
     return(MutableString.Create(_pattern));
 }
Example #18
0
            public static MutableString FileType(FileSystemInfo /*!*/ self)
            {
                string result = IsFile(self) ? "file" : "directory";

                return(MutableString.Create(result));
            }
Example #19
0
 public static object ToString(object self)
 {
     return(MutableString.Create(self.ToString()));
 }
Example #20
0
 public static MutableString /*!*/ GetZone(DateTime /*!*/ self)
 {
     // TODO:
     return(MutableString.Create("UTC"));
 }
Example #21
0
 public static MutableString /*!*/ ToString(bool self)
 {
     Debug.Assert(self == false);
     return(MutableString.Create("false"));
 }
Example #22
0
 public static MutableString /*!*/ GetCurrentDirectory(object self)
 {
     return(MutableString.Create(NormalizePathSeparators(Directory.GetCurrentDirectory())));
 }
Example #23
0
 public static MutableString /*!*/ GetName(RubyContext /*!*/ context, TypeGroup /*!*/ self)
 {
     return(MutableString.Create(self.Name, context.GetIdentifierEncoding()));
 }
Example #24
0
 private static MutableString /*!*/ FrozenString(RubyContext /*!*/ context, object value)
 {
     return(MutableString.Create((string)value ?? "", context.GetPathEncoding()).Freeze());
 }
Example #25
0
 public static MutableString Inspect(object self)
 {
     return(MutableString.Create("nil"));
 }
Example #26
0
        public static MutableString Mangle(RubyClass /*!*/ self, [DefaultProtocol] string /*!*/ clrName)
        {
            var ruby = RubyUtils.TryMangleName(clrName);

            return(ruby != null?MutableString.Create(ruby, self.Context.GetIdentifierEncoding()) : null);
        }
Example #27
0
 public static MutableString /*!*/ ToString(object self)
 {
     Debug.Assert(self == null);
     return(MutableString.Create(String.Empty));
 }
Example #28
0
 public static MutableString /*!*/ GetRubyName(RubyContext /*!*/ context, ClrName /*!*/ self)
 {
     return(MutableString.Create(self.MangledName, context.GetIdentifierEncoding()));
 }
Example #29
0
 public static MutableString /*!*/ ToString(DateTime self)
 {
     return(MutableString.Create(self.ToString("ddd MMM dd HH:mm:ss K yyyy")));
 }
Example #30
0
        public static MutableString /*!*/ FormatTime(DateTime self, [DefaultProtocol, NotNull] MutableString /*!*/ format)
        {
            bool          inEscape = false;
            StringBuilder builder  = new StringBuilder();

            foreach (char c in format.ToString())
            {
                if (c == '%' && !inEscape)
                {
                    inEscape = true;
                    continue;
                }
                if (inEscape)
                {
                    string   thisFormat = null;
                    DateTime firstDay;
                    int      week;
                    switch (c)
                    {
                    case 'a':
                        thisFormat = "ddd";
                        break;

                    case 'A':
                        thisFormat = "dddd";
                        break;

                    case 'b':
                        thisFormat = "MMM";
                        break;

                    case 'B':
                        thisFormat = "MMMM";
                        break;

                    case 'c':
                        thisFormat = "g";
                        break;

                    case 'd':
                        thisFormat = "dd";
                        break;

                    case 'H':
                        thisFormat = "HH";
                        break;

                    case 'I':
                        thisFormat = "hh";
                        break;

                    case 'j':
                        builder.AppendFormat("{0:000}", self.DayOfYear);
                        break;

                    case 'm':
                        thisFormat = "MM";
                        break;

                    case 'M':
                        thisFormat = "mm";
                        break;

                    case 'p':
                        thisFormat = "tt";
                        break;

                    case 'S':
                        thisFormat = "ss";
                        break;

                    case 'U':
                        firstDay = self.AddDays(1 - self.DayOfYear);
                        DateTime firstSunday = firstDay.AddDays((7 - (int)firstDay.DayOfWeek) % 7);
                        week = 1 + (int)Math.Floor((self - firstSunday).Days / 7.0);
                        builder.AppendFormat("{0:00}", week);
                        break;

                    case 'W':
                        firstDay = self.AddDays(1 - self.DayOfYear);
                        DateTime firstMonday = firstDay.AddDays((8 - (int)firstDay.DayOfWeek) % 7);
                        week = 1 + (int)Math.Floor((self - firstMonday).Days / 7.0);
                        builder.AppendFormat("{0:00}", week);
                        break;

                    case 'w':
                        builder.Append((int)self.DayOfWeek);
                        break;

                    case 'x':
                        thisFormat = "d";
                        break;

                    case 'X':
                        thisFormat = "t";
                        break;

                    case 'y':
                        thisFormat = "yy";
                        break;

                    case 'Y':
                        thisFormat = "yyyy";
                        break;

                    case 'Z':
                        thisFormat = "%K";
                        break;

                    default:
                        builder.Append(c);
                        break;
                    }
                    if (thisFormat != null)
                    {
                        builder.Append(self.ToString(thisFormat));
                    }
                    inEscape = false;
                }
                else
                {
                    builder.Append(c);
                }
            }

            return(MutableString.Create(builder.ToString()));
        }