Example #1
0
 private RubyStackTraceBuilder(RubyContext /*!*/ context)
 {
     _hasFileAccessPermission = DetectFileAccessPermissions();
     _exceptionDetail         = context.Options.ExceptionDetail;
     _encoding = context.GetPathEncoding();
     _trace    = new RubyArray();
 }
Example #2
0
            public object Construct(BaseConstructor ctor, string tag, Node node)
            {
                object result;

                _block.Yield(MutableString.Create(tag, RubyEncoding.GetRubyEncoding(ctor.Encoding)), ctor.ConstructPrimitive(node), out result);
                return(result);
            }
Example #3
0
 public static Exception /*!*/ CreateEncodingCompatibilityError(RubyEncoding /*!*/ encoding1, RubyEncoding /*!*/ encoding2)
 {
     return(new EncodingCompatibilityError(
                FormatMessage("incompatible character encodings: {0}{1} and {2}{3}",
                              encoding1.Name, encoding1.IsKCoding ? " (KCODE)" : null, encoding2.Name, encoding2.IsKCoding ? " (KCODE)" : null
                              )
                ));
 }
Example #4
0
        public static Iconv /*!*/ Initialize(Iconv /*!*/ self,
                                             [DefaultProtocol] MutableString /*!*/ toEncoding, [DefaultProtocol] MutableString /*!*/ fromEncoding)
        {
            self._toEncoding   = RubyEncoding.GetEncodingByRubyName(toEncoding.ConvertToString()).GetEncoder();
            self._fromEncoding = RubyEncoding.GetEncodingByRubyName(fromEncoding.ConvertToString()).GetDecoder();

            return(self);
        }
Example #5
0
 internal StringLiteral(object /*!*/ value, RubyEncoding /*!*/ encoding, SourceSpan location)
     : base(location)
 {
     Debug.Assert(value is string || value is byte[]);
     Debug.Assert(encoding != null);
     _value    = value;
     _encoding = encoding;
 }
Example #6
0
        internal RubyMethodBody(MethodDeclaration /*!*/ ast, MSA.SymbolDocumentInfo document, RubyEncoding /*!*/ encoding)
        {
            Assert.NotNull(ast, encoding);

            _ast      = ast;
            _document = document;
            _encoding = encoding;
        }
Example #7
0
        public SourceUnitTree Parse(SourceUnit /*!*/ sourceUnit, RubyCompilerOptions /*!*/ options, ErrorSink /*!*/ errorSink)
        {
            Assert.NotNull(sourceUnit, options, errorSink);

            ErrorCounter counter = new ErrorCounter(errorSink);

            _tokenizer.ErrorSink     = counter;
            _tokenizer.Compatibility = options.Compatibility;

            _lexicalScopes.Clear();

            EnterScope(CreateTopScope(options.LocalNames));

            using (SourceCodeReader reader = sourceUnit.GetReader()) {
                _sourceUnit = sourceUnit;
                _tokenizer.Initialize(null, reader, sourceUnit, options.InitialLocation);

                // Default encoding when hosted (ignore KCODE, we are reading from Unicode buffer):
                _tokenizer.Encoding = (reader.Encoding != null) ? RubyEncoding.GetRubyEncoding(reader.Encoding) : RubyEncoding.UTF8;
                _tokenizer.AllowNonAsciiIdentifiers = _tokenizer.Encoding != RubyEncoding.Binary;

                try {
                    Parse();
                    LeaveScope();
                } catch (InternalSyntaxError) {
                    _ast = null;
                    _lexicalScopes.Clear();
                } finally {
                    ScriptCodeParseResult props;
                    if (counter.AnyError)
                    {
                        _ast = null;

                        if (_tokenizer.UnterminatedToken)
                        {
                            props = ScriptCodeParseResult.IncompleteToken;
                        }
                        else if (_tokenizer.EndOfFileReached)
                        {
                            props = ScriptCodeParseResult.IncompleteStatement;
                        }
                        else
                        {
                            props = ScriptCodeParseResult.Invalid;
                        }
                    }
                    else
                    {
                        props = ScriptCodeParseResult.Complete;
                    }

                    sourceUnit.CodeProperties = props;
                }

                return(_ast);
            }
        }
Example #8
0
        public SourceUnitTree Parse(SourceUnit /*!*/ sourceUnit, RubyCompilerOptions /*!*/ options, ErrorSink /*!*/ errorSink)
        {
            Assert.NotNull(sourceUnit, options, errorSink);

            ErrorCounter counter = new ErrorCounter(errorSink);

            _tokenizer.ErrorSink     = counter;
            _tokenizer.Compatibility = options.Compatibility;

            _lexicalScopes.Clear();

            EnterScope(CreateTopScope(options.LocalNames));

            using (SourceCodeReader reader = sourceUnit.GetReader()) {
                _sourceUnit = sourceUnit;
                _tokenizer.Initialize(null, reader, sourceUnit, options.InitialLocation);

                // default encoding when hosted:
                _encoding = reader.Encoding ?? RubyEncoding.GetDefaultHostEncoding(options.Compatibility);

                try {
                    Parse();
                    LeaveScope();
                } catch (InternalSyntaxError) {
                    _ast = null;
                    _lexicalScopes.Clear();
                } finally {
                    ScriptCodeParseResult props;
                    if (counter.AnyError)
                    {
                        _ast = null;

                        if (_tokenizer.UnterminatedToken)
                        {
                            props = ScriptCodeParseResult.IncompleteToken;
                        }
                        else if (_tokenizer.IsEndOfFile)
                        {
                            props = ScriptCodeParseResult.IncompleteStatement;
                        }
                        else
                        {
                            props = ScriptCodeParseResult.Invalid;
                        }
                    }
                    else
                    {
                        props = ScriptCodeParseResult.Complete;
                    }

                    sourceUnit.CodeProperties = props;
                }

                return(_ast);
            }
        }
Example #9
0
 internal static MSA.Expression /*!*/ Transform(object /*!*/ value, RubyEncoding /*!*/ encoding)
 {
     if (value is string)
     {
         return(Methods.CreateMutableStringL.OpCall(AstUtils.Constant(value), encoding.Expression));
     }
     else
     {
         return(Methods.CreateMutableStringB.OpCall(AstUtils.Constant(value), encoding.Expression));
     }
 }
        protected override void AfterParse()
        {
            var existingSearchPaths =
                LanguageOptions.GetSearchPathsOption(LanguageSetup.Options) ??
                LanguageOptions.GetSearchPathsOption(RuntimeSetup.Options);

            if (existingSearchPaths != null)
            {
                _loadPaths.InsertRange(0, existingSearchPaths);
            }

#if !SILVERLIGHT
            try {
                string rubylib = Environment.GetEnvironmentVariable("RUBYLIB");
                if (rubylib != null)
                {
                    _loadPaths.AddRange(GetPaths(rubylib));
                }
            } catch (SecurityException) {
                // nop
            }
#endif
            LanguageSetup.Options["SearchPaths"] = _loadPaths;

            if (!_disableRubyGems)
            {
                _requiredPaths.Insert(0, "gem_prelude.rb");
            }

            LanguageSetup.Options["RequiredPaths"] = _requiredPaths;

            LanguageSetup.Options["DefaultEncoding"] = _defaultEncoding;
            LanguageSetup.Options["LocaleEncoding"]  = _defaultEncoding ??
#if SILVERLIGHT
                                                       RubyEncoding.UTF8;
#else
                                                       RubyEncoding.GetRubyEncoding(Console.InputEncoding);
#endif

#if DEBUG && !SILVERLIGHT
            // Can be set to nl-BE, ja-JP, etc
            string culture = Environment.GetEnvironmentVariable("IR_CULTURE");
            if (culture != null)
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture, false);
            }
#endif
            if (ConsoleOptions.DisplayVersion && ConsoleOptions.Command == null && ConsoleOptions.FileName == null)
            {
                ConsoleOptions.PrintVersion = true;
                ConsoleOptions.Exit         = true;
            }
        }
Example #11
0
        public SourceUnitTree(LexicalScope /*!*/ definedScope, Statements /*!*/ statements, List <FileInitializerStatement> initializers,
                              RubyEncoding /*!*/ encoding, int dataOffset)
            : base(SourceSpan.None)
        {
            Assert.NotNull(definedScope, statements, encoding);

            _definedScope = definedScope;
            _statements   = statements;
            _initializers = initializers;
            _encoding     = encoding;
            _dataOffset   = dataOffset;
        }
        public override void Add(SourceUnit sourceUnit, string message, SourceSpan span, int errorCode, Severity severity)
        {
            if (severity == Severity.Warning && !ReportWarning(_context.Verbose, errorCode))
            {
                return;
            }

            CountError(severity);

            string       path;
            string       codeLine;
            RubyEncoding encoding;
            int          line = span.Start.Line;

            if (sourceUnit != null)
            {
                path = sourceUnit.Path;
                using (SourceCodeReader reader = sourceUnit.GetReader()) {
                    if (line > 0)
                    {
                        try {
                            reader.SeekLine(line);
                            codeLine = reader.ReadLine();
                        } catch (Exception) {
                            codeLine = null;
                        }
                    }
                    else
                    {
                        codeLine = null;
                    }
                    encoding = reader.Encoding != null?RubyEncoding.GetRubyEncoding(reader.Encoding) : RubyEncoding.UTF8;
                }
            }
            else
            {
                path     = null;
                codeLine = null;
                encoding = RubyEncoding.UTF8;
            }

            if (severity == Severity.Error || severity == Severity.FatalError)
            {
                throw new SyntaxError(message, path, line, span.Start.Column, codeLine);
            }
            else
            {
                WriteMessage(
                    MutableString.Create(RubyContext.FormatErrorMessage(message, "warning", path, line, span.Start.Column, null), encoding)
                    );
            }
        }
Example #13
0
        internal override MSA.Expression /*!*/ TransformRead(AstGenerator /*!*/ gen)
        {
#if SILVERLIGHT
            return(Ast.Constant(null, typeof(Encoding)));
#else
            if (gen.Encoding == null)
            {
                return(Ast.Constant(null, typeof(Encoding)));
            }

            return(Methods.CreateEncoding.OpCall(Ast.Constant(RubyEncoding.GetCodePage(gen.Encoding))));
#endif
        }
Example #14
0
        public MutableString /*!*/ GetMutableString(RubyEncoding /*!*/ encoding)
        {
            string str = _value as string;

            if (str != null)
            {
                return(MutableString.Create(str, encoding));
            }
            else
            {
                return(MutableString.CreateBinary((byte[])_value, encoding));
            }
        }
Example #15
0
        public RubyConstructor(RubyGlobalScope /*!*/ scope, NodeProvider /*!*/ nodeProvider)
            : base(nodeProvider, scope)
        {
            _encoding = RubyEncoding.GetRubyEncoding(nodeProvider.Encoding);

            _newSite = CallSite <Func <CallSite, RubyModule, object, object, object, object> > .Create(
                RubyCallAction.Make(scope.Context, "new", RubyCallSignature.WithImplicitSelf(3))
                );

            _yamlInitializeSite = CallSite <Func <CallSite, object, object, Hash, object> > .Create(
                RubyCallAction.Make(scope.Context, "yaml_initialize", RubyCallSignature.WithImplicitSelf(3))
                );
        }
        private static RubyEncoding GetKCoding(IDictionary <string, object> /*!*/ options, string /*!*/ name, RubyEncoding defaultValue)
        {
            object value;

            if (options != null && options.TryGetValue(name, out value))
            {
                RubyEncoding rubyEncoding = value as RubyEncoding;
                if (rubyEncoding != null && rubyEncoding.IsKCoding)
                {
                    return(rubyEncoding);
                }

                throw new ArgumentException(String.Format("Invalid value for option {0}. Specify one of RubyEncoding.KCode* encodings.", name));
            }
            return(defaultValue);
        }
Example #17
0
 private GZipReader(RubyClass /*!*/ cls, object io, IDictionary options)
     : base(cls, io, CompressionMode.Decompress)
 {
     if (options != null)
     {
         foreach (var key in options.Keys)
         {
             switch (cls.Context.Operations.ImplicitConvertTo <RubySymbol>(key).String.ToString())
             {
             case "external_encoding":
                 _encoding = cls.Context.Operations.ImplicitConvertTo <RubyEncoding>(options[key]);
                 break;
             }
         }
     }
 }
Example #18
0
 internal override MSA.Expression /*!*/ TransformRead(AstGenerator /*!*/ gen)
 {
     if (IsAscii || gen.Encoding == BinaryEncoding.Instance)
     {
         return(Methods.CreateMutableStringB.OpCall(Ast.Constant(_value)));
     }
     else if (IsUTF8 || gen.Encoding == BinaryEncoding.UTF8)
     {
         return(Methods.CreateMutableStringU.OpCall(Ast.Constant(_value)));
     }
     else
     {
         return(Methods.CreateMutableStringE.OpCall(
                    Ast.Constant(_value), Ast.Constant(RubyEncoding.GetCodePage(gen.Encoding))
                    ));
     }
 }
Example #19
0
        public RubyOptions(IDictionary <string, object> /*!*/ options)
            : base(options)
        {
            _arguments        = GetStringCollectionOption(options, "Arguments") ?? EmptyStringCollection;
            _argumentEncoding = GetOption(options, "ArgumentEncoding", RubyEncoding.Default);

            _mainFile              = GetOption(options, "MainFile", (string)null);
            _verbosity             = GetOption(options, "Verbosity", 1);
            _debugVariable         = GetOption(options, "DebugVariable", false);
            _enableTracing         = GetOption(options, "EnableTracing", false);
            _savePath              = GetOption(options, "SavePath", (string)null);
            _loadFromDisk          = GetOption(options, "LoadFromDisk", false);
            _profile               = GetOption(options, "Profile", false);
            _noAssemblyResolveHook = GetOption(options, "NoAssemblyResolveHook", false);
            _requirePaths          = GetStringCollectionOption(options, "RequiredPaths", ';', ',');
            _hasSearchPaths        = GetOption <object>(options, "SearchPaths", null) != null;
            _libraryPaths          = GetStringCollectionOption(options, "LibraryPaths", ';', ',') ?? new ReadOnlyCollection <string>(new[] { "." });
        }
Example #20
0
        internal AstGenerator(RubyContext /*!*/ context, RubyCompilerOptions /*!*/ options, MSA.SymbolDocumentInfo document, RubyEncoding /*!*/ encoding,
                              bool printInteractiveResult)
        {
            Assert.NotNull(context, options, encoding);
            _context                = context;
            _compilerOptions        = options;
            _debugMode              = context.DomainManager.Configuration.DebugMode;
            _traceEnabled           = context.RubyOptions.EnableTracing;
            _document               = document;
            _sequencePointClearance = (document != null) ? Ast.ClearDebugInfo(document) : null;
            _encoding               = encoding;
            _encodingConstant       = Ast.Constant(encoding);
            _profiler               = context.RubyOptions.Profile ? Profiler.Instance : null;
            _savingToDisk           = context.RubyOptions.SavePath != null;
            _printInteractiveResult = printInteractiveResult;
#if !SILVERLIGHT
            _debugCompiler = Snippets.Shared.SaveSnippets;
#endif
        }
            // Returns false if the literal can't be concatenated due to incompatible encodings.
            public bool Add(StringLiteral /*!*/ literal)
            {
                var concatEncoding = MutableString.GetCompatibleEncoding(_encoding, literal.Encoding);

                if (concatEncoding == null)
                {
                    return(false);
                }

                var str = literal.Value as string;

                if (str != null)
                {
                    if (_isBinary)
                    {
                        _length += literal.Encoding.Encoding.GetByteCount(str);
                    }
                    else
                    {
                        _length += str.Length;
                    }
                }
                else
                {
                    var bytes = (byte[])literal.Value;
                    if (!_isBinary)
                    {
                        _length = 0;
                        foreach (object item in this)
                        {
                            Debug.Assert(item is string);
                            _length += _encoding.Encoding.GetByteCount((string)item);
                        }
                        _isBinary = true;
                    }

                    _length += bytes.Length;
                }

                _encoding = concatEncoding;
                base.Add(literal.Value);
                return(true);
            }
Example #22
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;
            }
        }
Example #23
0
        public static Iconv /*!*/ Initialize(Iconv /*!*/ self,
                                             [DefaultProtocol, NotNull] MutableString /*!*/ toEncoding, [DefaultProtocol, NotNull] MutableString /*!*/ fromEncoding)
        {
            self._toEncodingString = toEncoding.ConvertToString().ToUpperInvariant();

            try {
                self._toEncoding = RubyEncoding.GetEncodingByRubyName(self._toEncodingString).GetEncoder();
            } catch (ArgumentException e) {
                throw new InvalidEncoding(self._toEncodingString, e);
            }

            try {
                self._fromEncoding = RubyEncoding.GetEncodingByRubyName(fromEncoding.ConvertToString()).GetDecoder();
            } catch (ArgumentException e) {
                throw new InvalidEncoding(fromEncoding.ConvertToString(), e);
            }

            self.ResetByteOrderMark();

            return(self);
        }
Example #24
0
        private void Encoding1()
        {
            foreach (var name in preambleEncodingNames)
            {
                var encoding = RubyEncoding.GetEncodingByRubyName(name);
                Assert(encoding != null);

                // the encoding must be an identity on ASCII characters:
                Assert(RubyEncoding.IsAsciiIdentity(encoding));
            }

            foreach (var info in Encoding.GetEncodings())
            {
                var encoding = info.GetEncoding();

                // doesn't blow up (the method checks itself):
                RubyEncoding.IsAsciiIdentity(encoding);

                //Console.WriteLine("case " + info.CodePage + ": // " + encoding.EncodingName);
            }
        }
Example #25
0
        internal static MSA.Expression /*!*/ TransformConcatentation(AstGenerator /*!*/ gen, List <Expression> /*!*/ parts,
                                                                     Func <string, MethodInfo> /*!*/ opFactory, MSA.Expression additionalArg)
        {
            var opSuffix = new StringBuilder(Math.Min(parts.Count, 4));

            List <MSA.Expression> merged = ConcatLiteralsAndTransform(gen, parts, opSuffix);

            if (merged.Count <= RubyOps.MakeStringParamCount)
            {
                if (merged.Count == 0)
                {
                    merged.Add(Ast.Constant(String.Empty));
                    opSuffix.Append(RubyOps.SuffixBinary);
                }

                if (opSuffix.IndexOf(RubyOps.SuffixEncoded) != -1)
                {
                    merged.Add(Ast.Constant(RubyEncoding.GetCodePage(gen.Encoding)));
                }

                if (additionalArg != null)
                {
                    merged.Add(additionalArg);
                }

                return(opFactory(opSuffix.ToString()).OpCall(merged));
            }
            else
            {
                var paramArray = Ast.NewArrayInit(typeof(object), merged);
                var codePage   = Ast.Constant(RubyEncoding.GetCodePage(gen.Encoding));

                return((additionalArg != null) ?
                       opFactory("N").OpCall(paramArray, codePage, additionalArg) :
                       opFactory("N").OpCall(paramArray, codePage));
            }
        }
 public MSA.Expression /*!*/ CreateExpression(AstGenerator /*!*/ gen, byte[] /*!*/ literal, RubyEncoding /*!*/ encoding)
 {
     return(Ast.Constant(gen.Context.CreateSymbol(literal, encoding)));
 }
 public LiteralConcatenation(RubyEncoding /*!*/ sourceEncoding)
 {
     Assert.NotNull(sourceEncoding);
     _encoding = sourceEncoding;
 }
        public override void SetValue(RubyContext /*!*/ context, RubyScope scope, string /*!*/ name, object value)
        {
            switch (_id)
            {
            // regex:
            case GlobalVariableId.MatchData:
                if (scope == null)
                {
                    throw ReadOnlyError(name);
                }

                scope.GetInnerMostClosureScope().CurrentMatch = (value != null) ? RequireType <MatchData>(value, name, "MatchData") : null;
                return;

            case GlobalVariableId.MatchLastGroup:
            case GlobalVariableId.PreMatch:
            case GlobalVariableId.PostMatch:
            case GlobalVariableId.EntireMatch:
                throw ReadOnlyError(name);


            // exceptions:
            case GlobalVariableId.CurrentException:
                context.SetCurrentException(value);
                return;

            case GlobalVariableId.CurrentExceptionBacktrace:
                context.SetCurrentExceptionBacktrace(value);
                return;


            // input:
            case GlobalVariableId.LastInputLine:
                if (scope == null)
                {
                    throw ReadOnlyError(name);
                }
                scope.GetInnerMostClosureScope().LastInputLine = value;
                return;

            case GlobalVariableId.LastInputLineNumber:
                context.InputProvider.LastInputLineNumber = RequireType <int>(value, name, "Fixnum");
                return;

            case GlobalVariableId.CommandLineArguments:
            case GlobalVariableId.InputFileName:
                throw ReadOnlyError(name);

            // output:
            case GlobalVariableId.OutputStream:
                context.StandardOutput = RequireWriteProtocol(context, value, name);
                return;

            case GlobalVariableId.ErrorOutputStream:
                context.StandardErrorOutput = RequireWriteProtocol(context, value, name);
                break;

            case GlobalVariableId.InputStream:
                context.StandardInput = value;
                return;

            // separators:
            case GlobalVariableId.InputContent:
                throw ReadOnlyError(name);

            case GlobalVariableId.InputSeparator:
                context.InputSeparator = (value != null) ? RequireType <MutableString>(value, name, "String") : null;
                return;

            case GlobalVariableId.OutputSeparator:
                context.OutputSeparator = (value != null) ? RequireType <MutableString>(value, name, "String") : null;
                return;

            case GlobalVariableId.StringSeparator:
                // type not enforced:
                context.StringSeparator = value;
                return;

            case GlobalVariableId.ItemSeparator:
                context.ItemSeparator = (value != null) ? RequireType <MutableString>(value, name, "String") : null;
                return;


            // loader:
            case GlobalVariableId.LoadedFiles:
            case GlobalVariableId.LoadPath:
                throw ReadOnlyError(name);


            // misc:
            case GlobalVariableId.SafeLevel:
                context.SetSafeLevel(RequireType <int>(value, name, "Fixnum"));
                return;

            case GlobalVariableId.Verbose:
                context.Verbose = value;
                return;

            case GlobalVariableId.CommandLineProgramPath:
                context.CommandLineProgramPath = (value != null) ? RequireType <MutableString>(value, name, "String") : null;
                return;

            case GlobalVariableId.KCode:
                if (context.RubyOptions.Compatibility < RubyCompatibility.Ruby19)
                {
                    // MRI calls to_str; we don't do that, it's inconsistent with other globals.
                    // If some app depends on this behavior, it will fail gracefully:
                    context.KCode = RubyEncoding.GetKCodingByNameInitial(RequireType <MutableString>(value, name, "String").GetFirstChar());
                    Utils.Log(String.Format("Set to {0}", context.KCode), "KCODE");
                    return;
                }

                context.ReportWarning("variable $KCODE is no longer effective");
                return;

            case GlobalVariableId.ChildProcessExitStatus:
                throw ReadOnlyError(name);

            default:
                throw Assert.Unreachable;
            }
        }
        /// <exception cref="Exception">On error.</exception>
        protected override void ParseArgument(string arg)
        {
            ContractUtils.RequiresNotNull(arg, "arg");

            string mainFileFromPath = null;

            if (arg.StartsWith("-e", StringComparison.Ordinal))
            {
                string command;
                if (arg == "-e")
                {
                    command = PopNextArg();
                }
                else
                {
                    command = arg.Substring(2);
                }

                LanguageSetup.Options["MainFile"] = "-e";
                if (CommonConsoleOptions.Command == null)
                {
                    CommonConsoleOptions.Command = String.Empty;
                }
                else
                {
                    CommonConsoleOptions.Command += "\n";
                }
                CommonConsoleOptions.Command += command;
                return;
            }

            if (arg.StartsWith("-S", StringComparison.Ordinal))
            {
                mainFileFromPath = arg == "-S" ? PopNextArg() : arg.Substring(2);
            }

            if (arg.StartsWith("-I", StringComparison.Ordinal))
            {
                string includePaths;
                if (arg == "-I")
                {
                    includePaths = PopNextArg();
                }
                else
                {
                    includePaths = arg.Substring(2);
                }

                _loadPaths.AddRange(GetPaths(includePaths));
                return;
            }

            if (arg.StartsWith("-K", StringComparison.Ordinal))
            {
                _defaultEncoding = arg.Length >= 3 ? RubyEncoding.GetEncodingByNameInitial(arg[2]) : null;
                return;
            }

            if (arg.StartsWith("-r", StringComparison.Ordinal))
            {
                _requiredPaths.Add((arg == "-r") ? PopNextArg() : arg.Substring(2));
                return;
            }

            if (arg.StartsWith("-C", StringComparison.Ordinal))
            {
                ConsoleOptions.ChangeDirectory = arg.Substring(2);
                return;
            }

            if (arg.StartsWith("-0", StringComparison.Ordinal) ||
                arg.StartsWith("-C", StringComparison.Ordinal) ||
                arg.StartsWith("-F", StringComparison.Ordinal) ||
                arg.StartsWith("-i", StringComparison.Ordinal) ||
                arg.StartsWith("-T", StringComparison.Ordinal) ||
                arg.StartsWith("-x", StringComparison.Ordinal))
            {
                throw new InvalidOptionException(String.Format("Option `{0}' not supported", arg));
            }

            int    colon = arg.IndexOf(':');
            string optionName, optionValue;

            if (colon >= 0)
            {
                optionName  = arg.Substring(0, colon);
                optionValue = arg.Substring(colon + 1);
            }
            else
            {
                optionName  = arg;
                optionValue = null;
            }

            switch (optionName)
            {
                #region Ruby options

            case "-a":
            case "-c":
            case "--copyright":
            case "-l":
            case "-n":
            case "-p":
            case "-s":
                throw new InvalidOptionException(String.Format("Option `{0}' not supported", optionName));

            case "-d":
                LanguageSetup.Options["DebugVariable"] = true;     // $DEBUG = true
                break;

            case "--version":
                ConsoleOptions.PrintVersion = true;
                ConsoleOptions.Exit         = true;
                break;

            case "-v":
                ConsoleOptions.DisplayVersion = true;
                goto case "-W2";

            case "-W0":
                LanguageSetup.Options["Verbosity"] = 0;     // $VERBOSE = nil
                break;

            case "-W1":
                LanguageSetup.Options["Verbosity"] = 1;     // $VERBOSE = false
                break;

            case "-w":
            case "-W2":
                LanguageSetup.Options["Verbosity"] = 2;     // $VERBOSE = true
                break;

                #endregion

#if DEBUG && !SILVERLIGHT
            case "-DT*":
                SetTraceFilter(String.Empty, false);
                break;

            case "-DT":
                SetTraceFilter(PopNextArg(), false);
                break;

            case "-ET*":
                SetTraceFilter(String.Empty, true);
                break;

            case "-ET":
                SetTraceFilter(PopNextArg(), true);
                break;

            case "-ER":
                RubyOptions.ShowRules = true;
                break;

            case "-save":
                LanguageSetup.Options["SavePath"] = optionValue ?? AppDomain.CurrentDomain.BaseDirectory;
                break;

            case "-load":
                LanguageSetup.Options["LoadFromDisk"] = ScriptingRuntimeHelpers.True;
                break;

            case "-useThreadAbortForSyncRaise":
                RubyOptions.UseThreadAbortForSyncRaise = true;
                break;

            case "-compileRegexps":
                RubyOptions.CompileRegexps = true;
                break;
#endif
            case "-trace":
                LanguageSetup.Options["EnableTracing"] = ScriptingRuntimeHelpers.True;
                break;

            case "-profile":
                LanguageSetup.Options["Profile"] = ScriptingRuntimeHelpers.True;
                break;

            case "-1.8.6":
            case "-1.8.7":
            case "-1.9":
            case "-2.0":
                throw new InvalidOptionException(String.Format("Option `{0}' is no longer supported. The compatible Ruby version is 1.9.", optionName));

            case "--disable-gems":
                _disableRubyGems = true;
                break;

            case "-X":
                switch (optionValue)
                {
                case "AutoIndent":
                case "TabCompletion":
                case "ColorfulConsole":
                    throw new InvalidOptionException(String.Format("Option `{0}' not supported", optionName));
                }
                goto default;

            default:
                base.ParseArgument(arg);

                if (ConsoleOptions.FileName != null)
                {
                    if (mainFileFromPath != null)
                    {
                        ConsoleOptions.FileName = FindMainFileFromPath(mainFileFromPath);
                    }

                    if (ConsoleOptions.Command == null)
                    {
                        SetupOptionsForMainFile();
                    }
                    else
                    {
                        SetupOptionsForCommand();
                    }
                }
                break;
            }
        }
Example #30
0
        private bool LoadFromPath(Scope globalScope, object self, string /*!*/ path, RubyEncoding /*!*/ pathEncoding, LoadFlags flags, out object loaded)
        {
            Assert.NotNull(pathEncoding, path);

            string[] sourceFileExtensions;
            if ((flags & LoadFlags.AnyLanguage) != 0)
            {
                sourceFileExtensions = DomainManager.Configuration.GetFileExtensions();
            }
            else
            {
                sourceFileExtensions = DomainManager.Configuration.GetFileExtensions(_context);
            }

            IList <ResolvedFile> files = FindFile(path, (flags & LoadFlags.AppendExtensions) != 0, sourceFileExtensions);

            if (files.Count == 0)
            {
                // MRI: doesn't throw an exception if the path is in $" (performs resolution first though):
                if (AlreadyLoaded(path, null, flags, sourceFileExtensions))
                {
                    loaded = null;
                    return(false);
                }
                throw RubyExceptions.CreateLoadError(String.Format("no such file to load -- {0}", path));
            }

            ResolvedFile file = files.First();

            string pathWithExtension = path;

            if (file.AppendedExtension != null)
            {
                pathWithExtension += file.AppendedExtension;
            }

            if (AlreadyLoaded(path, files, flags) || _unfinishedFiles.Contains(file.Path))
            {
                if ((flags & LoadFlags.ResolveLoaded) != 0)
                {
                    if (file.SourceUnit != null)
                    {
                        Scope loadedScope;
                        if (!LoadedScripts.TryGetValue(file.Path, out loadedScope))
                        {
                            throw RubyExceptions.CreateLoadError(String.Format("no such file to load -- {0}", file.Path));
                        }
                        loaded = loadedScope;
                    }
                    else
                    {
                        loaded = Platform.LoadAssemblyFromPath(file.Path);
                    }
                }
                else
                {
                    loaded = null;
                }
                return(false);
            }

            try {
                // save path as is, no canonicalization nor combination with an extension or directory:
                _unfinishedFiles.Push(file.Path);

                if (file.SourceUnit != null)
                {
                    AddScriptLines(file.SourceUnit);

                    ScriptCode compiledCode;
                    if (file.SourceUnit.LanguageContext == _context)
                    {
                        compiledCode = CompileRubySource(file.SourceUnit, flags);
                    }
                    else
                    {
                        compiledCode = file.SourceUnit.Compile();
                    }
                    loaded = Execute(globalScope, compiledCode);
                }
                else
                {
                    Debug.Assert(file.Path != null);
                    try {
                        Assembly assembly = Platform.LoadAssemblyFromPath(file.Path);
                        DomainManager.LoadAssembly(assembly);
                        loaded = assembly;
                    } catch (Exception e) {
                        throw RubyExceptions.CreateLoadError(e);
                    }
                }

                FileLoaded(MutableString.Create(file.Path, pathEncoding), flags);
            } finally {
                _unfinishedFiles.Pop();
            }

            return(true);
        }