Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    **** BEGIN LICENSE BLOCK *****
    * Version: CPL 1.0/GPL 2.0/LGPL 2.1
    *
    * The contents of this file are subject to the Common Public
    * License Version 1.0 (the "License"); you may not use this file
    * except in compliance with the License. You may obtain a copy of
    * the License at http://www.eclipse.org/legal/cpl-v10.html
    *
   * Software distributed under the License is distributed on an "AS
   * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
   * implied. See the License for the specific language governing
   * rights and limitations under the License.
   *
   * Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
   * Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
   * Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
   * Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
   * Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
   * Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
   * Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
   * Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
   * Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
   * Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
   * Copyright (C) 2006 Ola Bini <ola@ologix.com>
   * Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
   *
   * Alternatively, the contents of this file may be used under the terms of
   * either of the GNU General Public License Version 2 or later (the "GPL"),
   * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
   * in which case the provisions of the GPL or the LGPL are applicable instead
   * of those above. If you wish to allow use of your version of this file only
   * under the terms of either the GPL or the LGPL, and not to allow others to
   * use your version of this file under the terms of the CPL, indicate your
   * decision by deleting the provisions above and replace them with the notice
   * and other provisions required by the GPL or the LGPL. If you do not delete
   * the provisions above, a recipient may use your version of this file under
   * the terms of any one of the CPL, the GPL or the LGPL.
   ***** END LICENSE BLOCK *****/
  package org.jruby;
  
  import jnr.posix.POSIX;
 
 import java.io.File;
 import java.util.*;
The Ruby object represents the top-level of a JRuby "instance" in a given VM. JRuby supports spawning multiple instances in the same JVM. Generally, objects created under these instances are tied to a given runtime, for such details as identity and type, because multiple Ruby instances means there are multiple instances of each class. This means that in multi-runtime mode (or really, multi-VM mode, where each JRuby instance is a ruby "VM"), objects generally can't be transported across runtimes without marshaling. This class roots everything that makes the JRuby runtime function, and provides a number of utility methods for constructing global types and accessing global runtime structures.
 
 public final class Ruby {
    
    
The logger used to log relevant bits.
 
     private static final Logger LOG = LoggerFactory.getLogger("Ruby");

    
Create and initialize a new JRuby runtime. The properties of the specified RubyInstanceConfig will be used to determine various JRuby runtime characteristics.

Parameters:
config The configuration to use for the new instance
See also:
RubyInstanceConfig
 
     private Ruby(RubyInstanceConfig config) {
         this.             = config;
         this.              = config.getCompatVersion().is1_9();
         this.              = config.getCompatVersion().is2_0();
         this. = ;
         this.      = new ThreadService(this);
         if(config.isSamplingEnabled()) {
             org.jruby.util.SimpleSampler.registerThreadContext(.getCurrentContext());
         }
         
         if (config.getCompileMode() == . ||
                 config.getCompileMode() == .) {
             this. = new IRStaticScopeFactory(this);
         } else {
             this. = new StaticScopeFactory(this);
         }
 
         this.                 = config.getInput();
         this.                = config.getOutput();
         this.                = config.getError();
         this. = config.isObjectSpaceEnabled();
         this.     = config.isSiphashEnabled();
         this.            = config.getProfile();
         this.   = config.getCurrentDirectory();
         this.              = config.getKCode();
         this.        = BeanManagerFactory.create(thisconfig.isManagementEnabled());
         this.        = new JITCompiler(this);
         this.        = new ParserStats(this);
         
         Random myRandom;
         try {
             myRandom = new SecureRandom();
         } catch (Throwable t) {
             .debug("unable to instantiate SecureRandom, falling back on Random"t);
             myRandom = new Random();
         }
         this. = myRandom;
         this. = this..nextLong();
         this. = this..nextLong();
         
         this..register(new Config(this));
         this..register();
         this..register(new ClassCache(this));
         this..register(new org.jruby.management.Runtime(this));
 
         this. = new RuntimeCache();
         .initMethodCache(. * MethodNames.values().length - 1);
         
          = OptoFactory.newConstantInvalidator();
 
         if (config.isObjectSpaceEnabled()) {
              = ;
         } else {
              = ;
         }
     }
    
    
Returns a new instance of the JRuby runtime configured with defaults.

Returns:
the JRuby runtime
See also:
RubyInstanceConfig
 
     public static Ruby newInstance() {
         return newInstance(new RubyInstanceConfig());
     }

    
Returns a new instance of the JRuby runtime configured as specified.

Parameters:
config The instance configuration
Returns:
The JRuby runtime
See also:
RubyInstanceConfig
 
     public static Ruby newInstance(RubyInstanceConfig config) {
         Ruby ruby = new Ruby(config);
         ruby.init();
         setGlobalRuntimeFirstTimeOnly(ruby);
         return ruby;
     }

    
Returns a new instance of the JRuby runtime configured with the given input, output and error streams and otherwise default configuration (except where specified system properties alter defaults).

Parameters:
in the custom input stream
out the custom output stream
err the custom error stream
Returns:
the JRuby runtime
See also:
RubyInstanceConfig
 
     public static Ruby newInstance(InputStream inPrintStream outPrintStream err) {
         RubyInstanceConfig config = new RubyInstanceConfig();
         config.setInput(in);
         config.setOutput(out);
         config.setError(err);
         return newInstance(config);
     }

    
Tests whether globalRuntime has been instantiated or not. This method is used by singleton model of org.jruby.embed.ScriptingContainer to decide what RubyInstanceConfig should be used. When a global runtime is not there, RubyInstanceConfig of AbstractContextProvider will be used to enact configurations set by a user. When a global runtime is already instantiated, RubyInstanceConfig of the global runtime should be used in ScriptingContaiener.

Returns:
true if a global runtime is instantiated, false for other.
 
     public static boolean isGlobalRuntimeReady() {
         return  != null;
     }

    
Set the global runtime to the given runtime only if it has no been set.

Parameters:
runtime the runtime to use for global runtime
 
     private static synchronized void setGlobalRuntimeFirstTimeOnly(Ruby runtime) {
         if ( == null) {
              = runtime;
         }
     }

    
Get the global runtime.

Returns:
the global runtime
 
     public static synchronized Ruby getGlobalRuntime() {
         if ( == null) {
             newInstance();
         }
         return ;
     }
    
    
Convenience method for java integrators who may need to switch the notion of "global" runtime. Use JRuby.runtime.use_as_global_runtime from Ruby code to activate the current runtime as the global one.
 
     public void useAsGlobalRuntime() {
         synchronized(Ruby.class) {
              = null;
             setGlobalRuntimeFirstTimeOnly(this);
         }
     }

    
Get the thread-local runtime for the current thread, or null if unset.

Returns:
the thread-local runtime, or null if unset
 
     public static Ruby getThreadLocalRuntime() {
         return .get();
     }
    
    
Set the thread-local runtime to the given runtime. Note that static threadlocals like this one can leak resources across (for example) application redeploys. If you use this, it is your responsibility to clean it up appropriately.

Parameters:
ruby the new runtime for thread-local
 
     public static void setThreadLocalRuntime(Ruby ruby) {
         .set(ruby);
     }
    
    
Evaluates a script under the current scope (perhaps the top-level scope) and returns the result (generally the last value calculated). This version goes straight into the interpreter, bypassing compilation and runtime preparation typical to normal script runs.

Parameters:
script The scriptlet to run
Returns:
The result of the eval
 
     public IRubyObject evalScriptlet(String script) {
         ThreadContext context = getCurrentContext();
         DynamicScope currentScope = context.getCurrentScope();
         ManyVarsDynamicScope newScope = new ManyVarsDynamicScope(getStaticScopeFactory().newEvalScope(currentScope.getStaticScope()), currentScope);
 
         return evalScriptlet(scriptnewScope);
     }

    
Evaluates a script under the current scope (perhaps the top-level scope) and returns the result (generally the last value calculated). This version goes straight into the interpreter, bypassing compilation and runtime preparation typical to normal script runs. This version accepts a scope to use, so you can eval many times against the same scope.

Parameters:
script The scriptlet to run
scope The scope to execute against (ManyVarsDynamicScope is recommended, so it can grow as needed)
Returns:
The result of the eval
 
     public IRubyObject evalScriptlet(String scriptDynamicScope scope) {
         ThreadContext context = getCurrentContext();
         Node node = parseEval(script"<script>"scope, 0);
 
         try {
             context.preEvalScriptlet(scope);
             return ASTInterpreter.INTERPRET_ROOT(thiscontextnodecontext.getFrameSelf(), .);
         } catch (JumpException.ReturnJump rj) {
             throw newLocalJumpError(.., (IRubyObject)rj.getValue(), "unexpected return");
         } catch (JumpException.BreakJump bj) {
             throw newLocalJumpError(.., (IRubyObject)bj.getValue(), "unexpected break");
         } catch (JumpException.RedoJump rj) {
             throw newLocalJumpError(.., (IRubyObject)rj.getValue(), "unexpected redo");
         } finally {
             context.postEvalScriptlet();
         }
     }
    
    
Parse and execute the specified script This differs from the other methods in that it accepts a string-based script and parses and runs it as though it were loaded at a command-line. This is the preferred way to start up a new script when calling directly into the Ruby object (which is generally *dis*couraged.

Parameters:
script The contents of the script to run as a normal, root script
Returns:
The last value of the script
 
     public IRubyObject executeScript(String scriptString filename) {
         byte[] bytes = script.getBytes();
 
         Node node = parseInline(new ByteArrayInputStream(bytes), filenamenull);
         ThreadContext context = getCurrentContext();
         
         String oldFile = context.getFile();
         int oldLine = context.getLine();
         try {
             context.setFileAndLine(node.getPosition());
             return runInterpreter(node);
         } finally {
             context.setFileAndLine(oldFileoldLine);
         }
     }
    
    
Run the script contained in the specified input stream, using the specified filename as the name of the script being executed. The stream will be read fully before being parsed and executed. The given filename will be used for the ruby $PROGRAM_NAME and $0 global variables in this runtime. This method is intended to be called once per runtime, generally from Main or from main-like top-level entry points. As part of executing the script loaded from the input stream, various RubyInstanceConfig properties will be used to determine whether to compile the script before execution or run with various wrappers (for looping, printing, and so on, see jruby -help).

Parameters:
inputStream The InputStream from which to read the script contents
filename The filename to use when parsing, and for $PROGRAM_NAME and $0 ruby global variables.
 
     public void runFromMain(InputStream inputStreamString filename) {
         IAccessor d = new ValueAccessor(newString(filename));
         getGlobalVariables().define("$PROGRAM_NAME"d);
         getGlobalVariables().define("$0"d);
 
         for (Iterator i = .getOptionGlobals().entrySet().iterator(); i.hasNext();) {
             Map.Entry entry = (Map.Entryi.next();
             Object value = entry.getValue();
             IRubyObject varvalue;
             if (value != null) {
                 varvalue = newString(value.toString());
             } else {
                 varvalue = getTrue();
             }
             getGlobalVariables().set("$" + entry.getKey().toString(), varvalue);
         }
 
         if (filename.endsWith(".class")) {
             // we are presumably running a precompiled class; load directly
             Script script = CompiledScriptLoader.loadScriptFromFile(thisinputStreamfilename);
             if (script == null) {
                 throw new MainExitException(1, "error: .class file specified is not a compiled JRuby script");
             }
             script.setFilename(filename);
             runScript(script);
             return;
         }
         
         Node scriptNode = parseFromMain(inputStreamfilename);
 
         // done with the stream, shut it down
         try {inputStream.close();} catch (IOException ioe) {}
 
         ThreadContext context = getCurrentContext();
 
         String oldFile = context.getFile();
         int oldLine = context.getLine();
         try {
             context.setFileAndLine(scriptNode.getPosition());
 
             if (.isAssumePrinting() || .isAssumeLoop()) {
                 runWithGetsLoop(scriptNode.isAssumePrinting(), .isProcessLineEnds(),
                         .isSplit());
             } else {
                 runNormally(scriptNode);
             }
         } finally {
             context.setFileAndLine(oldFileoldLine);
         }
     }

    
Parse the script contained in the given input stream, using the given filename as the name of the script, and return the root Node. This is used to verify that the script syntax is valid, for jruby -c. The current scope (generally the top-level scope) is used as the parent scope for parsing.

Parameters:
inputStream The input stream from which to read the script
filename The filename to use for parsing
Returns:
The root node of the parsed script
 
     public Node parseFromMain(InputStream inputStreamString filename) {
         if (.isInlineScript()) {
             return parseInline(inputStreamfilenamegetCurrentContext().getCurrentScope());
         } else {
             return parseFileFromMain(inputStreamfilenamegetCurrentContext().getCurrentScope());
         }
     }

    
Run the given script with a "while gets; end" loop wrapped around it. This is primarily used for the -n command-line flag, to allow writing a short script that processes input lines using the specified code.

Parameters:
scriptNode The root node of the script to execute
printing Whether $_ should be printed after each loop (as in the -p command-line flag)
processLineEnds Whether line endings should be processed by setting $\ to $/ and chop!ing every line read
split Whether to split each line read using String#split bytecode before executing.
Returns:
The result of executing the specified script
 
     @Deprecated
     public IRubyObject runWithGetsLoop(Node scriptNodeboolean printingboolean processLineEndsboolean splitboolean unused) {
         return runWithGetsLoop(scriptNodeprintingprocessLineEndssplit);
     }
    
    
Run the given script with a "while gets; end" loop wrapped around it. This is primarily used for the -n command-line flag, to allow writing a short script that processes input lines using the specified code.

Parameters:
scriptNode The root node of the script to execute
printing Whether $_ should be printed after each loop (as in the -p command-line flag)
processLineEnds Whether line endings should be processed by setting $\ to $/ and chop!ing every line read
split Whether to split each line read using String#split bytecode before executing.
Returns:
The result of executing the specified script
 
     public IRubyObject runWithGetsLoop(Node scriptNodeboolean printingboolean processLineEndsboolean split) {
         ThreadContext context = getCurrentContext();
         
         Script script = null;
         boolean compile = getInstanceConfig().getCompileMode().shouldPrecompileCLI();
         if (compile) {
             script = tryCompile(scriptNode);
             if (compile && script == null) {
                 // terminate; tryCompile will have printed out an error and we're done
                 return getNil();
             }
         }
         
         if (processLineEnds) {
             getGlobalVariables().set("$\\"getGlobalVariables().get("$/"));
         }
 
         // we do preand post load outside the "body" versions to pre-prepare
         // and pre-push the dynamic scope we need for lastline
         RuntimeHelpers.preLoad(context, ((RootNode)scriptNode).getStaticScope().getVariables());
 
         try {
             while (RubyKernel.gets(contextgetTopSelf(), .).isTrue()) {
                 loop: while (true) { // Used for the 'redo' command
                     try {
                         if (processLineEnds) {
                             getGlobalVariables().get("$_").callMethod(context"chop!");
                         }
 
                         if (split) {
                             getGlobalVariables().set("$F"getGlobalVariables().get("$_").callMethod(context"split"));
                         }
 
                         if (script != null) {
                             runScriptBody(script);
                         } else {
                             runInterpreterBody(scriptNode);
                         }
 
                         if (printing) RubyKernel.print(contextgetKernel(), new IRubyObject[] {getGlobalVariables().get("$_")});
                         break loop;
                     } catch (JumpException.RedoJump rj) {
                         // do nothing, this iteration restarts
                     } catch (JumpException.NextJump nj) {
                         // recheck condition
                         break loop;
                     } catch (JumpException.BreakJump bj) {
                         // end loop
                         return (IRubyObjectbj.getValue();
                     }
                 }
             }
         } finally {
             RuntimeHelpers.postLoad(context);
         }
         
         return getNil();
     }

    
Run the specified script without any of the loop-processing wrapper code.

Parameters:
scriptNode The root node of the script to be executed bytecode before execution
Returns:
The result of executing the script
 
     @Deprecated
     public IRubyObject runNormally(Node scriptNodeboolean unused) {
         return runNormally(scriptNode);
     }
    
    
Run the specified script without any of the loop-processing wrapper code.

Parameters:
scriptNode The root node of the script to be executed bytecode before execution
Returns:
The result of executing the script
 
     public IRubyObject runNormally(Node scriptNode) {
         Script script = null;
         boolean compile = getInstanceConfig().getCompileMode().shouldPrecompileCLI();
         if (compile || .isShowBytecode()) {
             script = tryCompile(scriptNodenullnew JRubyClassLoader(getJRubyClassLoader()), .isShowBytecode());
         }
 
         if (script != null) {
             if (.isShowBytecode()) {
                 return getNil();
             }
 
             return runScript(script);
         } else {
             failForcedCompile(scriptNode);
             
             return runInterpreter(scriptNode);
         }
     }

    
Try to compile the code associated with the given Node, returning an instance of the successfully-compiled Script or null if the script could not be compiled.

Parameters:
node The node to attempt to compiled
Returns:
an instance of the successfully-compiled Script, or null.
 
     public Script tryCompile(Node node) {
         return tryCompile(nodenullnew JRubyClassLoader(getJRubyClassLoader()), false);
     }

    
Try to compile the code associated with the given Node, returning an instance of the successfully-compiled Script or null if the script could not be compiled. This version accepts an ASTInspector instance assumed to have appropriate flags set for compile optimizations, such as to turn on heap-based local variables to share an existing scope.

Parameters:
node The node to attempt to compiled
inspector The ASTInspector to use for making optimization decisions
Returns:
an instance of the successfully-compiled Script, or null.
 
     public Script tryCompile(Node nodeASTInspector inspector) {
         return tryCompile(nodenullnew JRubyClassLoader(getJRubyClassLoader()), inspectorfalse);
     }
 
     private void failForcedCompile(Node scriptNodethrows RaiseException {
         if (.getCompileMode().shouldPrecompileAll()) {
             throw newRuntimeError("could not compile and compile mode is 'force': " + scriptNode.getPosition().getFile());
         }
     }
 
     private void handeCompileError(Node nodeThrowable t) {
         if (.isJitLoggingVerbose() || .isDebug()) {
             .error("warning: could not compile: {}; full trace follows"node.getPosition().getFile());
             .error(t.getMessage(), t);
         }
     }
 
     private Script tryCompile(Node nodeString cachedClassNameJRubyClassLoader classLoaderboolean dump) {
         if (.getCompileMode() == .) {
             final IRScope scope = IRBuilder.createIRBuilder(getIRManager(), is1_9()).buildRoot((RootNodenode);
             final Class compiled = JVMVisitor.compile(thisscopeclassLoader);
             final StaticScope staticScope = scope.getStaticScope();
             staticScope.setModule(getTopSelf().getMetaClass());
             return new AbstractScript() {
                 public IRubyObject __file__(ThreadContext contextIRubyObject selfIRubyObject[] argsBlock block) {
                     try {
                         return (IRubyObject)compiled.getMethod("__script__0"ThreadContext.classStaticScope.classIRubyObject.classBlock.class).invoke(nullgetCurrentContext(), scope.getStaticScope(), getTopSelf(), block);
                     } catch (InvocationTargetException ite) {
                         if (ite.getCause() instanceof JumpException) {
                             throw (JumpException)ite.getCause();
                         } else {
                             throw new RuntimeException(ite);
                         }
                     } catch (Exception e) {
                         throw new RuntimeException(e);
                     }
                 }
 
                 public IRubyObject load(ThreadContext contextIRubyObject selfboolean wrap) {
                     try {
                         RuntimeHelpers.preLoadCommon(contextstaticScopefalse);
                         return __file__(contextself..);
                     } finally {
                         RuntimeHelpers.postLoad(context);
                     }
                 }
             };
         }
         ASTInspector inspector = new ASTInspector();
         inspector.inspect(node);
 
         return tryCompile(nodecachedClassNameclassLoaderinspectordump);
     }
 
     private Script tryCompile(Node nodeString cachedClassNameJRubyClassLoader classLoaderASTInspector inspectorboolean dump) {
         Script script = null;
         try {
             String filename = node.getPosition().getFile();
             String classname = JavaNameMangler.mangledFilenameForStartupClasspath(filename);
 
             StandardASMCompiler asmCompiler = null;
             if (. != null && cachedClassName != null) {
                 asmCompiler = new StandardASMCompiler(cachedClassName.replace('.''/'), filename);
             } else {
                 asmCompiler = new StandardASMCompiler(classnamefilename);
             }
             ASTCompiler compiler = .newCompiler();
             if (dump) {
                 compiler.compileRoot(nodeasmCompilerinspectorfalsefalse);
                 asmCompiler.dumpClass(.);
             } else {
                 compiler.compileRoot(nodeasmCompilerinspectortruefalse);
             }
 
             if (. != null && cachedClassName != null) {
                 // save script off to disk
                 String pathName = cachedClassName.replace('.''/');
                 JITCompiler.saveToCodeCache(thisasmCompiler.getClassByteArray(), "ruby/jit"new File(.pathName + ".class"));
             }
             script = (Script)asmCompiler.loadClass(classLoader).newInstance();
 
             if (.isJitLogging()) {
                 .info("compiled: " + node.getPosition().getFile());
             }
         } catch (Throwable t) {
             handeCompileError(nodet);
         }
         
         return script;
     }
     
     public IRubyObject runScript(Script script) {
         return runScript(scriptfalse);
     }
     
     public IRubyObject runScript(Script scriptboolean wrap) {
         ThreadContext context = getCurrentContext();
         
         try {
             return script.load(contextgetTopSelf(), wrap);
         } catch (JumpException.ReturnJump rj) {
             return (IRubyObjectrj.getValue();
         }
     }

    
This is used for the "gets" loop, and we bypass 'load' to use an already-prepared, already-pushed scope for the script body.
 
     public IRubyObject runScriptBody(Script script) {
         ThreadContext context = getCurrentContext();
 
         try {
             return script.__file__(contextgetTopSelf(), .);
         } catch (JumpException.ReturnJump rj) {
             return (IRubyObjectrj.getValue();
         }
     }
 
     public IRubyObject runInterpreter(ThreadContext contextNode rootNodeIRubyObject self) {
         assert rootNode != null : "scriptNode is not null";
 
         try {
             if (getInstanceConfig().getCompileMode() == .) {
                 return Interpreter.interpret(thisrootNodeself);
             } else {
                 return ASTInterpreter.INTERPRET_ROOT(thiscontextrootNodegetTopSelf(), .);
             }
         } catch (JumpException.ReturnJump rj) {
             return (IRubyObjectrj.getValue();
         }
     }
     
     public IRubyObject runInterpreter(Node scriptNode) {
         return runInterpreter(getCurrentContext(), scriptNodegetTopSelf());
     }

    
This is used for the "gets" loop, and we bypass 'load' to use an already-prepared, already-pushed scope for the script body.
 
     public IRubyObject runInterpreterBody(Node scriptNode) {
         assert scriptNode != null : "scriptNode is not null";
         assert scriptNode instanceof RootNode : "scriptNode is not a RootNode";
 
         return runInterpreter(((RootNodescriptNode).getBodyNode());
     }
 
     public Parser getParser() {
         return ;
     }
     
     public BeanManager getBeanManager() {
         return ;
     }
     
     public JITCompiler getJITCompiler() {
         return ;
     }

    

Deprecated:
use .newInstance()
 
     public static Ruby getDefaultInstance() {
         return newInstance();
     }
     
     @Deprecated
     public static Ruby getCurrentInstance() {
         return null;
     }
     
     @Deprecated
     public static void setCurrentInstance(Ruby runtime) {
     }
     
     public int allocSymbolId() {
         return .incrementAndGet();
     }
     public int allocModuleId() {
         return .incrementAndGet();
     }
     public void addModule(RubyModule module) {
         synchronized () {
             .add(module);
         }
     }
     public void eachModule(Function1<ObjectIRubyObjectfunc) {
         synchronized () {
             for (RubyModule module : ) {
                 func.apply(module);
             }
         }
     }

    
Retrieve the module with the given name from the Object namespace.

Parameters:
name The name of the module
Returns:
The module or null if not found
 
     public RubyModule getModule(String name) {
         return (RubyModule.getConstantAt(name);
     }
 
     @Deprecated
     public RubyModule fastGetModule(String internedName) {
         return getModule(internedName);
     }

    
Retrieve the class with the given name from the Object namespace.

Parameters:
name The name of the class
Returns:
The class
 
     public RubyClass getClass(String name) {
         return .getClass(name);
     }

    
Retrieve the class with the given name from the Object namespace. The module name must be an interned string, but this method will be faster than the non-interned version.

Parameters:
internedName the name of the class; must be an interned String!
Returns:
 
     @Deprecated
     public RubyClass fastGetClass(String internedName) {
         return getClass(internedName);
     }

    
Define a new class under the Object namespace. Roughly equivalent to rb_define_class in MRI.

Parameters:
name The name for the new class
superClass The super class for the new class
allocator An ObjectAllocator instance that can construct instances of the new class.
Returns:
The new class
 
     public RubyClass defineClass(String nameRubyClass superClassObjectAllocator allocator) {
         return defineClassUnder(namesuperClassallocator);
     }

    
A variation of defineClass that allows passing in an array of subplementary call sites for improving dynamic invocation performance.

Parameters:
name The name for the new class
superClass The super class for the new class
allocator An ObjectAllocator instance that can construct instances of the new class.
Returns:
The new class
 
     public RubyClass defineClass(String nameRubyClass superClassObjectAllocator allocatorCallSite[] callSites) {
         return defineClassUnder(namesuperClassallocatorcallSites);
     }

    
Define a new class with the given name under the given module or class namespace. Roughly equivalent to rb_define_class_under in MRI. If the name specified is already bound, its value will be returned if: * It is a class * No new superclass is being defined

Parameters:
name The name for the new class
superClass The super class for the new class
allocator An ObjectAllocator instance that can construct instances of the new class.
parent The namespace under which to define the new class
Returns:
The new class
 
     public RubyClass defineClassUnder(String nameRubyClass superClassObjectAllocator allocatorRubyModule parent) {
         return defineClassUnder(namesuperClassallocatorparentnull);
     }

    
A variation of defineClassUnder that allows passing in an array of supplementary call sites to improve dynamic invocation.

Parameters:
name The name for the new class
superClass The super class for the new class
allocator An ObjectAllocator instance that can construct instances of the new class.
parent The namespace under which to define the new class
callSites The array of call sites to add
Returns:
The new class
 
     public RubyClass defineClassUnder(String nameRubyClass superClassObjectAllocator allocatorRubyModule parentCallSite[] callSites) {
         IRubyObject classObj = parent.getConstantAt(name);
 
         if (classObj != null) {
             if (!(classObj instanceof RubyClass)) throw newTypeError(name + " is not a class");
             RubyClass klazz = (RubyClass)classObj;
             if (klazz.getSuperClass().getRealClass() != superClass) {
                 throw newNameError(name + " is already defined"name);
             }
             // If we define a class in Ruby, but later want to allow it to be defined in Java,
             // the allocator needs to be updated
             if (klazz.getAllocator() != allocator) {
                 klazz.setAllocator(allocator);
             }
             return klazz;
         }
         
         boolean parentIsObject = parent == ;
 
         if (superClass == null) {
             String className = parentIsObject ? name : parent.getName() + "::" + name;  
             .warn(."no super class for `" + className + "', Object assumed");
             
             superClass = ;
         }
 
         return RubyClass.newClass(thissuperClassnameallocatorparent, !parentIsObjectcallSites);
     }

    
Define a new module under the Object namespace. Roughly equivalent to rb_define_module in MRI.

Parameters:
name The name of the new module
Returns:
The new module
    public RubyModule defineModule(String name) {
        return defineModuleUnder(name);
    }

    
Define a new module with the given name under the given module or class namespace. Roughly equivalent to rb_define_module_under in MRI.

Parameters:
name The name of the new module
parent The class or module namespace under which to define the module
Returns:
The new module
    public RubyModule defineModuleUnder(String nameRubyModule parent) {
        IRubyObject moduleObj = parent.getConstantAt(name);
        
        boolean parentIsObject = parent == ;
        if (moduleObj != null ) {
            if (moduleObj.isModule()) return (RubyModule)moduleObj;
            
            if (parentIsObject) {
                throw newTypeError(moduleObj.getMetaClass().getName() + " is not a module");
            } else {
                throw newTypeError(parent.getName() + "::" + moduleObj.getMetaClass().getName() + " is not a module");
            }
        }
        return RubyModule.newModule(thisnameparent, !parentIsObject);
    }

    
From Object, retrieve the named module. If it doesn't exist a new module is created.

Parameters:
name The name of the module
Returns:
The existing or new module
    public RubyModule getOrCreateModule(String name) {
        IRubyObject module = .getConstantAt(name);
        if (module == null) {
            module = defineModule(name);
        } else if (!module.isModule()) {
            throw newTypeError(name + " is not a Module");
        }
        return (RubyModulemodule;
    }
    public KCode getKCode() {
        return ;
    }
    public void setKCode(KCode kcode) {
        this. = kcode;
    }

    
rb_define_global_const
    public void defineGlobalConstant(String nameIRubyObject value) {
        .defineConstant(namevalue);
    }
    public boolean isClassDefined(String name) {
        return getModule(name) != null;
    }

    
This method is called immediately after constructing the Ruby instance. The main thread is prepared for execution, all core classes and libraries are initialized, and any libraries required on the command line are loaded.
    private void init() {
        // Construct key services
         = .createLoadService(this);
         = POSIXFactory.getPOSIX(new JRubyPOSIXHandler(this), .isNativeEnabled());
         = new JavaSupport(this);
        // HACK HACK HACK (jansi (part of jline) + classloader + windows == stacktrace barf)
        if (.) System.setProperty("jline.terminal""none");
         = new ThreadPoolExecutor(
                .,
                .,
                .,
                .,
                new SynchronousQueue<Runnable>(),
                new DaemonThreadFactory("JRubyWorker"));
        
        // initialize the root of the class hierarchy completely
        initRoot();
        // Set up the main thread in thread service
        // Get the main threadcontext (gets constructed for us)
        ThreadContext tc = getCurrentContext();
        // Construct the top-level execution frame and scope for the main thread
        tc.prepareTopLevel();
        // Initialize all the core classes
        bootstrap();
        // set up defined messages
        initDefinedMessages();
        
         = new IRManager();
        
        // Initialize the "dummy" class used as a marker
         = new RubyClass(this);
        .freeze(tc);
        
        // Create global constants and variables
        RubyGlobal.createGlobals(tcthis);
        // Prepare LoadService and load path
        // initialize builtin libraries
        initBuiltins();
        // load JRuby internals, which loads Java support
        if (!.) {
            .require("jruby");
        }
        // out of base boot mode
         = false;
        
        // init Ruby-based kernel
        initRubyKernel();
        
        if(.isProfiling()) {
            // additional twiddling for profiled mode
            getLoadService().require("jruby/profiler/shutdown_hook");
            // recache core methods, since they'll have profiling wrappers now
            .invalidateCacheDescendants(); // to avoid already-cached methods
            RubyKernel.recacheBuiltinMethods(this);
            RubyBasicObject.recacheBuiltinMethods(this);
        }
        if (.getLoadGemfile()) {
            .loadFromClassLoader(getClassLoader(), "jruby/bundler/startup.rb"false);
        }
        // Require in all libraries specified on command line
        for (String scriptName : .getRequiredLibraries()) {
            if () {
                .callMethod(getCurrentContext(), "require", RubyString.newString(thisscriptName));
            } else {
                .require(scriptName);
            }
        }
    }
    private void bootstrap() {
        initCore();
        initExceptions();
    }
    private void initDefinedMessages() {
        for (DefinedMessage definedMessage : DefinedMessage.values()) {
            RubyString str = RubyString.newString(this, ByteList.create(definedMessage.getText()));
            str.setFrozen(true);
            .put(definedMessagestr);
        }
    }
    private void initRoot() {
        boolean oneNine = is1_9();
        // Bootstrap the top of the hierarchy
        if (oneNine) {
             = RubyClass.createBootstrapClass(this"BasicObject"null.);
             = RubyClass.createBootstrapClass(this"Object".);
        } else {
             = RubyClass.createBootstrapClass(this"Object"null.);
        }
         = RubyClass.createBootstrapClass(this"Module".);
         = RubyClass.createBootstrapClass(this"Class".);
        if (oneNine.setMetaClass();
        RubyClass metaClass;
        if (oneNinemetaClass = .makeMetaClass();
        metaClass = .makeMetaClass();
        metaClass = .makeMetaClass(metaClass);
        metaClass = .makeMetaClass(metaClass);
        if (oneNine) RubyBasicObject.createBasicObjectClass(this);
        RubyObject.createObjectClass(this);
        RubyModule.createModuleClass(this);
        RubyClass.createClassClass(this);
        
        // set constants now that they're initialized
        if (oneNine.setConstant("BasicObject");
        .setConstant("Object");
        .setConstant("Class");
        .setConstant("Module");
        // Initialize Kernel and include into Object
        RubyKernel.createKernelModule(this);
        // Object is ready, create top self
         = TopSelfFactory.createTopSelf(this);
        
        // Pre-create all the core classes potentially referenced during startup
        RubyNil.createNilClass(this);
        RubyBoolean.createFalseClass(this);
        RubyBoolean.createTrueClass(this);
         = new RubyNil(this);
        for (int i=0; i<i++) [i] = ;
         = new IRubyObject[] {};
         = new RubyBoolean(thisfalse);
         = new RubyBoolean(thistrue);
    }
    private void initCore() {
        if (.allowClass("Data")) {
        }
        RubyComparable.createComparable(this);
        RubyEnumerable.createEnumerableModule(this);
        RubyString.createStringClass(this);
         = new EncodingService(this);
        RubySymbol.createSymbolClass(this);
        
         = newSymbol("__recursive_key__");
        if (.allowClass("ThreadGroup")) {
            RubyThreadGroup.createThreadGroupClass(this);
        }
        if (.allowClass("Thread")) {
            RubyThread.createThreadClass(this);
        }
        if (.allowClass("Exception")) {
            RubyException.createExceptionClass(this);
        }
        if (!is1_9()) {
            if (.allowModule("Precision")) {
                RubyPrecision.createPrecisionModule(this);
            }
        }
        if (.allowClass("Numeric")) {
            RubyNumeric.createNumericClass(this);
        }
        if (.allowClass("Integer")) {
            RubyInteger.createIntegerClass(this);
        }
        if (.allowClass("Fixnum")) {
            RubyFixnum.createFixnumClass(this);
        }
        if (is1_9()) {
            if (.allowClass("Complex")) {
                RubyComplex.createComplexClass(this);
            }
            if (.allowClass("Rational")) {
                RubyRational.createRationalClass(this);
            }
        }
        if (.allowClass("Hash")) {
            RubyHash.createHashClass(this);
        }
        if (.allowClass("Array")) {
            RubyArray.createArrayClass(this);
        }
        if (.allowClass("Float")) {
            RubyFloat.createFloatClass(this);
        }
        if (.allowClass("Bignum")) {
            RubyBignum.createBignumClass(this);
            // RubyRandom depends on Bignum existence.
            if (is1_9()) {
                RubyRandom.