KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jruby > Ruby


1 /***** BEGIN LICENSE BLOCK *****
2  * Version: CPL 1.0/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Common Public
5  * License Version 1.0 (the "License"); you may not use this file
6  * except in compliance with the License. You may obtain a copy of
7  * the License at http://www.eclipse.org/legal/cpl-v10.html
8  *
9  * Software distributed under the License is distributed on an "AS
10  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
11  * implied. See the License for the specific language governing
12  * rights and limitations under the License.
13  *
14  * Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
15  * Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
16  * Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
17  * Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
18  * Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
19  * Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
20  * Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
21  * Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
22  * Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
23  * Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
24  * Copyright (C) 2006 Ola Bini <ola@ologix.com>
25  * Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
26  *
27  * Alternatively, the contents of this file may be used under the terms of
28  * either of the GNU General Public License Version 2 or later (the "GPL"),
29  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30  * in which case the provisions of the GPL or the LGPL are applicable instead
31  * of those above. If you wish to allow use of your version of this file only
32  * under the terms of either the GPL or the LGPL, and not to allow others to
33  * use your version of this file under the terms of the CPL, indicate your
34  * decision by deleting the provisions above and replace them with the notice
35  * and other provisions required by the GPL or the LGPL. If you do not delete
36  * the provisions above, a recipient may use your version of this file under
37  * the terms of any one of the CPL, the GPL or the LGPL.
38  ***** END LICENSE BLOCK *****/

39 package org.jruby;
40
41 import java.io.BufferedReader JavaDoc;
42 import java.io.File JavaDoc;
43 import java.io.FileReader JavaDoc;
44 import java.io.IOException JavaDoc;
45 import java.io.InputStream JavaDoc;
46 import java.io.PrintStream JavaDoc;
47 import java.io.Reader JavaDoc;
48 import java.io.StringReader JavaDoc;
49 import java.util.Hashtable JavaDoc;
50 import java.util.List JavaDoc;
51 import java.util.Map JavaDoc;
52 import java.util.Random JavaDoc;
53 import java.util.Stack JavaDoc;
54 import org.jruby.ast.Node;
55 import org.jruby.ast.executable.Script;
56 import org.jruby.ast.executable.YARVCompiledRunner;
57 import org.jruby.common.RubyWarnings;
58 import org.jruby.compiler.NodeCompilerFactory;
59 import org.jruby.compiler.NotCompilableException;
60 import org.jruby.compiler.impl.StandardASMCompiler;
61 import org.jruby.compiler.yarv.StandardYARVCompiler;
62 import org.jruby.evaluator.EvaluationState;
63 import org.jruby.exceptions.JumpException;
64 import org.jruby.exceptions.RaiseException;
65 import org.jruby.internal.runtime.GlobalVariables;
66 import org.jruby.internal.runtime.ThreadService;
67 import org.jruby.internal.runtime.ValueAccessor;
68 import org.jruby.javasupport.Java;
69 import org.jruby.javasupport.JavaSupport;
70 import org.jruby.lexer.yacc.ISourcePosition;
71 import org.jruby.libraries.IConvLibrary;
72 import org.jruby.libraries.JRubyLibrary;
73 import org.jruby.libraries.RbConfigLibrary;
74 import org.jruby.libraries.StringIOLibrary;
75 import org.jruby.libraries.StringScannerLibrary;
76 import org.jruby.libraries.ZlibLibrary;
77 import org.jruby.libraries.YamlLibrary;
78 import org.jruby.libraries.EnumeratorLibrary;
79 import org.jruby.libraries.BigDecimalLibrary;
80 import org.jruby.libraries.DigestLibrary;
81 import org.jruby.libraries.ThreadLibrary;
82 import org.jruby.ext.socket.RubySocket;
83 import org.jruby.ext.Generator;
84 import org.jruby.ext.Readline;
85 import org.jruby.parser.Parser;
86 import org.jruby.runtime.Block;
87 import org.jruby.runtime.CacheMap;
88 import org.jruby.runtime.CallbackFactory;
89 import org.jruby.runtime.DynamicScope;
90 import org.jruby.runtime.GlobalVariable;
91 import org.jruby.runtime.IAccessor;
92 import org.jruby.runtime.MethodSelectorTable;
93 import org.jruby.runtime.ObjectAllocator;
94 import org.jruby.runtime.ObjectSpace;
95 import org.jruby.runtime.ThreadContext;
96 import org.jruby.runtime.builtin.IRubyObject;
97 import org.jruby.runtime.builtin.meta.BindingMetaClass;
98 import org.jruby.runtime.builtin.meta.FileMetaClass;
99 import org.jruby.runtime.builtin.meta.HashMetaClass;
100 import org.jruby.runtime.builtin.meta.IOMetaClass;
101 import org.jruby.runtime.builtin.meta.ModuleMetaClass;
102 import org.jruby.runtime.builtin.meta.ObjectMetaClass;
103 import org.jruby.runtime.builtin.meta.ProcMetaClass;
104 import org.jruby.runtime.builtin.meta.StringMetaClass;
105 import org.jruby.runtime.builtin.meta.SymbolMetaClass;
106 import org.jruby.runtime.builtin.meta.TimeMetaClass;
107 import org.jruby.runtime.load.Library;
108 import org.jruby.runtime.load.LoadService;
109 import org.jruby.util.BuiltinScript;
110 import org.jruby.util.ByteList;
111 import org.jruby.util.JRubyClassLoader;
112 import org.jruby.util.KCode;
113 import org.jruby.util.NormalizedFile;
114 import org.jruby.util.collections.SinglyLinkedList;
115
116 /**
117  * The jruby runtime.
118  */

119 public final class Ruby {
120     private static String JavaDoc[] BUILTIN_LIBRARIES = {"fcntl", "yaml", "nkf", "yaml/syck" };
121
122     private CacheMap cacheMap = new CacheMap(this);
123     private ThreadService threadService = new ThreadService(this);
124     private Hashtable JavaDoc runtimeInformation;
125     private final MethodSelectorTable selectorTable = new MethodSelectorTable();
126
127     private int stackTraces = 0;
128
129     private ObjectSpace objectSpace = new ObjectSpace();
130
131     private final RubyFixnum[] fixnumCache = new RubyFixnum[256];
132     private final RubySymbol.SymbolTable symbolTable = new RubySymbol.SymbolTable();
133     private Hashtable JavaDoc ioHandlers = new Hashtable JavaDoc();
134     private long randomSeed = 0;
135     private long randomSeedSequence = 0;
136     private Random JavaDoc random = new Random JavaDoc();
137
138     private RubyProc traceFunction;
139     private boolean globalAbortOnExceptionEnabled = false;
140     private boolean doNotReverseLookupEnabled = false;
141     private final boolean objectSpaceEnabled;
142
143     private long globalState = 1;
144
145     /** safe-level:
146             0 - strings from streams/environment/ARGV are tainted (default)
147             1 - no dangerous operation by tainted value
148             2 - process/file operations prohibited
149             3 - all genetated objects are tainted
150             4 - no global (non-tainted) variable modification/no direct output
151     */

152     private int safeLevel = 0;
153
154     // Default classes/objects
155
private IRubyObject nilObject;
156     private RubyBoolean trueObject;
157     private RubyBoolean falseObject;
158     private RubyClass objectClass;
159     private StringMetaClass stringClass;
160     private RubyClass systemCallError = null;
161     private RubyModule errnoModule = null;
162     private IRubyObject topSelf;
163
164     // former java.lang.System concepts now internalized for MVM
165
private String JavaDoc currentDirectory;
166
167     private long startTime = System.currentTimeMillis();
168
169     private RubyInstanceConfig config;
170
171     private InputStream JavaDoc in;
172     private PrintStream JavaDoc out;
173     private PrintStream JavaDoc err;
174
175     private IRubyObject verbose;
176     private IRubyObject debug;
177
178     // Java support
179
private JavaSupport javaSupport;
180     // FIXME: THIS IS WRONG. We need to correct the classloading problems.
181
private static JRubyClassLoader jrubyClassLoader = new JRubyClassLoader(Ruby.class.getClassLoader());
182
183     private Parser parser = new Parser(this);
184
185     private LoadService loadService;
186     private GlobalVariables globalVariables = new GlobalVariables(this);
187     private RubyWarnings warnings = new RubyWarnings(this);
188
189     // Contains a list of all blocks (as Procs) that should be called when
190
// the runtime environment exits.
191
private Stack JavaDoc atExitBlocks = new Stack JavaDoc();
192
193     private RubyModule kernelModule;
194
195     private RubyClass nilClass;
196
197     private RubyClass fixnumClass;
198     
199     private RubyClass arrayClass;
200
201     private IRubyObject tmsStruct;
202
203     private Profile profile;
204
205     private String JavaDoc jrubyHome;
206
207     private KCode kcode = KCode.NONE;
208
209     public int symbolLastId = 0;
210     public int moduleLastId = 0;
211
212     /**
213      * Create and initialize a new jruby Runtime.
214      */

215     private Ruby(RubyInstanceConfig config) {
216         this.config = config;
217         this.in = config.getInput();
218         this.out = config.getOutput();
219         this.err = config.getError();
220         this.objectSpaceEnabled = config.isObjectSpaceEnabled();
221         this.profile = config.getProfile();
222         this.currentDirectory = config.getCurrentDirectory();;
223     }
224
225     /**
226      * Returns a default instance of the JRuby runtime.
227      *
228      * @return the JRuby runtime
229      */

230     public static Ruby getDefaultInstance() {
231         return newInstance(new RubyInstanceConfig());
232     }
233
234     /**
235      * Returns a default instance of the JRuby runtime configured as provided.
236      *
237      * @param config the instance configuration
238      * @return the JRuby runtime
239      */

240     public static Ruby newInstance(RubyInstanceConfig config) {
241         Ruby ruby = new Ruby(config);
242         ruby.init();
243         return ruby;
244     }
245
246     /**
247      * Returns a default instance of the JRuby runtime configured with the given input, output and error streams.
248      *
249      * @param in the custom input stream
250      * @param out the custom output stream
251      * @param err the custom error stream
252      * @return the JRuby runtime
253      */

254     public static Ruby newInstance(InputStream JavaDoc in, PrintStream JavaDoc out, PrintStream JavaDoc err) {
255         RubyInstanceConfig config = new RubyInstanceConfig();
256         config.setInput(in);
257         config.setOutput(out);
258         config.setError(err);
259         return newInstance(config);
260     }
261
262     /**
263      * Evaluates a script and returns a RubyObject.
264      */

265     public IRubyObject evalScript(String JavaDoc script) {
266         return eval(parse(script, "<script>", getCurrentContext().getCurrentScope()));
267     }
268
269     public IRubyObject eval(Node node) {
270         try {
271             ThreadContext tc = getCurrentContext();
272
273             return EvaluationState.eval(this, tc, node, tc.getFrameSelf(), Block.NULL_BLOCK);
274         } catch (JumpException je) {
275             if (je.getJumpType() == JumpException.JumpType.ReturnJump) {
276                 throw newLocalJumpError("unexpected return");
277                 // return (IRubyObject)je.getSecondaryData();
278
} else if(je.getJumpType() == JumpException.JumpType.BreakJump) {
279                 throw newLocalJumpError("unexpected break");
280             }
281
282             throw je;
283         }
284     }
285
286     public IRubyObject compileAndRun(Node node) {
287         try {
288             // do the compile
289
StandardASMCompiler compiler = new StandardASMCompiler(node);
290             NodeCompilerFactory.getCompiler(node).compile(node, compiler);
291
292             Class JavaDoc scriptClass = compiler.loadClass(this);
293
294             Script script = (Script)scriptClass.newInstance();
295             // FIXME: Pass something better for args and block here?
296
return script.run(getCurrentContext(), getTopSelf(), IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
297         } catch (NotCompilableException nce) {
298             System.err.println("Error -- Not compileable: " + nce.getMessage());
299             return null;
300         } catch (JumpException je) {
301             if (je.getJumpType() == JumpException.JumpType.ReturnJump) {
302                 return (IRubyObject) je.getValue();
303             } else {
304                 throw je;
305             }
306         } catch (ClassNotFoundException JavaDoc e) {
307             // TODO Auto-generated catch block
308
e.printStackTrace();
309             return null;
310         } catch (InstantiationException JavaDoc e) {
311             // TODO Auto-generated catch block
312
e.printStackTrace();
313             return null;
314         } catch (IllegalAccessException JavaDoc e) {
315             // TODO Auto-generated catch block
316
e.printStackTrace();
317             return null;
318         }
319     }
320
321     public IRubyObject ycompileAndRun(Node node) {
322         try {
323             StandardYARVCompiler compiler = new StandardYARVCompiler(this);
324             NodeCompilerFactory.getYARVCompiler().compile(node, compiler);
325             org.jruby.lexer.yacc.ISourcePosition p = node.getPosition();
326             if(p == null && node instanceof org.jruby.ast.RootNode) {
327                 p = ((org.jruby.ast.RootNode)node).getBodyNode().getPosition();
328             }
329             return new YARVCompiledRunner(this,compiler.getInstructionSequence("<main>",p.getFile(),"toplevel")).run();
330         } catch (NotCompilableException nce) {
331             System.err.println("Error -- Not compileable: " + nce.getMessage());
332             return null;
333         } catch (JumpException je) {
334             if (je.getJumpType() == JumpException.JumpType.ReturnJump) {
335                 return (IRubyObject) je.getValue();
336             }
337                 
338             throw je;
339         }
340     }
341
342     public RubyClass getObject() {
343         return objectClass;
344     }
345
346     public RubyModule getKernel() {
347         return kernelModule;
348     }
349
350     public RubyClass getString() {
351         return stringClass;
352     }
353
354     public RubyClass getFixnum() {
355         return fixnumClass;
356     }
357
358     public RubyClass getArray() {
359         return arrayClass;
360     }
361
362     public IRubyObject getTmsStruct() {
363         return tmsStruct;
364     }
365
366     /** Returns the "true" instance from the instance pool.
367      * @return The "true" instance.
368      */

369     public RubyBoolean getTrue() {
370         return trueObject;
371     }
372
373     /** Returns the "false" instance from the instance pool.
374      * @return The "false" instance.
375      */

376     public RubyBoolean getFalse() {
377         return falseObject;
378     }
379
380     /** Returns the "nil" singleton instance.
381      * @return "nil"
382      */

383     public IRubyObject getNil() {
384         return nilObject;
385     }
386
387     public RubyClass getNilClass() {
388         return nilClass;
389     }
390
391     public RubyModule getModule(String JavaDoc name) {
392         return (RubyModule) objectClass.getConstantAt(name);
393     }
394
395     /** Returns a class from the instance pool.
396      *
397      * @param name The name of the class.
398      * @return The class.
399      */

400     public RubyClass getClass(String JavaDoc name) {
401         try {
402             return objectClass.getClass(name);
403         } catch (ClassCastException JavaDoc e) {
404             throw newTypeError(name + " is not a Class");
405         }
406     }
407
408     /** Define a new class with name 'name' and super class 'superClass'.
409      *
410      * MRI: rb_define_class / rb_define_class_id
411      *
412      */

413     public RubyClass defineClass(String JavaDoc name, RubyClass superClass, ObjectAllocator allocator) {
414         return defineClassUnder(name, superClass, allocator, objectClass.getCRef());
415     }
416
417     public RubyClass defineClassUnder(String JavaDoc name, RubyClass superClass, ObjectAllocator allocator, SinglyLinkedList parentCRef) {
418         if (superClass == null) {
419             superClass = objectClass;
420         }
421
422         return superClass.newSubClass(name, allocator, parentCRef);
423     }
424
425     /** rb_define_module / rb_define_module_id
426      *
427      */

428     public RubyModule defineModule(String JavaDoc name) {
429         return defineModuleUnder(name, objectClass.getCRef());
430     }
431
432     public RubyModule defineModuleUnder(String JavaDoc name, SinglyLinkedList parentCRef) {
433         RubyModule newModule = RubyModule.newModule(this, name, parentCRef);
434
435         ((RubyModule)parentCRef.getValue()).setConstant(name, newModule);
436
437         return newModule;
438     }
439
440     /**
441      * In the current context, get the named module. If it doesn't exist a
442      * new module is created.
443      */

444     public RubyModule getOrCreateModule(String JavaDoc name) {
445         ThreadContext tc = getCurrentContext();
446         RubyModule module = (RubyModule) tc.getRubyClass().getConstantAt(name);
447
448         if (module == null) {
449             module = defineModule(name);
450         } else if (getSafeLevel() >= 4) {
451             throw newSecurityError("Extending module prohibited.");
452         }
453
454         if (tc.getWrapper() != null) {
455             module.getSingletonClass().includeModule(tc.getWrapper());
456             module.includeModule(tc.getWrapper());
457         }
458         return module;
459     }
460
461
462     /** Getter for property securityLevel.
463      * @return Value of property securityLevel.
464      */

465     public int getSafeLevel() {
466         return this.safeLevel;
467     }
468
469     /** Setter for property securityLevel.
470      * @param safeLevel New value of property securityLevel.
471      */

472     public void setSafeLevel(int safeLevel) {
473         this.safeLevel = safeLevel;
474     }
475
476     public KCode getKCode() {
477         return kcode;
478     }
479
480     public void setKCode(KCode kcode) {
481         this.kcode = kcode;
482     }
483
484     public void secure(int level) {
485         if (level <= safeLevel) {
486             throw newSecurityError("Insecure operation '" + getCurrentContext().getFrameName() + "' at level " + safeLevel);
487         }
488     }
489
490     /**
491      * Retrieve mappings of cached methods to where they have been cached. When a cached
492      * method needs to be invalidated this map can be used to remove all places it has been
493      * cached.
494      *
495      * @return the mappings of where cached methods have been stored
496      */

497     public CacheMap getCacheMap() {
498         return cacheMap;
499     }
500
501     /**
502      * @see org.jruby.Ruby#getRuntimeInformation
503      */

504     public Map JavaDoc getRuntimeInformation() {
505         return runtimeInformation == null ? runtimeInformation = new Hashtable JavaDoc() : runtimeInformation;
506     }
507
508     public MethodSelectorTable getSelectorTable() {
509         return selectorTable;
510     }
511
512     /** rb_define_global_const
513      *
514      */

515     public void defineGlobalConstant(String JavaDoc name, IRubyObject value) {
516         objectClass.defineConstant(name, value);
517     }
518
519     public IRubyObject getTopConstant(String JavaDoc name) {
520         IRubyObject constant = getModule(name);
521         if (constant == null) {
522             constant = getLoadService().autoload(name);
523         }
524         return constant;
525     }
526
527     public boolean isClassDefined(String JavaDoc name) {
528         return getModule(name) != null;
529     }
530
531     /** Getter for property rubyTopSelf.
532      * @return Value of property rubyTopSelf.
533      */

534     public IRubyObject getTopSelf() {
535         return topSelf;
536     }
537
538     public void setCurrentDirectory(String JavaDoc dir) {
539         currentDirectory = dir;
540     }
541
542     public String JavaDoc getCurrentDirectory() {
543         return currentDirectory;
544     }
545
546     /** ruby_init
547      *
548      */

549     // TODO: Figure out real dependencies between vars and reorder/refactor into better methods
550
private void init() {
551         ThreadContext tc = getCurrentContext();
552         nilObject = new RubyNil(this);
553         trueObject = new RubyBoolean(this, true);
554         falseObject = new RubyBoolean(this, false);
555
556         verbose = falseObject;
557         debug = falseObject;
558
559         javaSupport = new JavaSupport(this);
560
561         tc.preInitCoreClasses();
562
563         initCoreClasses();
564
565         initLibraries();
566
567         topSelf = TopSelfFactory.createTopSelf(this);
568
569         tc.preInitBuiltinClasses(objectClass, topSelf);
570
571         RubyGlobal.createGlobals(this);
572
573         initBuiltinClasses();
574
575         getObject().defineConstant("TOPLEVEL_BINDING", newBinding());
576
577         RubyKernel.autoload(topSelf, newSymbol("Java"), newString("java"));
578     }
579
580     private void initLibraries() {
581         loadService = new LoadService(this);
582         registerBuiltin("java.rb", new Library() {
583                 public void load(Ruby runtime) throws IOException JavaDoc {
584                     Java.createJavaModule(runtime);
585                     new BuiltinScript("javasupport").load(runtime);
586                 }
587             });
588         
589         registerBuiltin("socket.rb", new RubySocket.Service());
590         registerBuiltin("rbconfig.rb", new RbConfigLibrary());
591
592         for (int i=0; i<BUILTIN_LIBRARIES.length; i++) {
593             if(profile.allowBuiltin(BUILTIN_LIBRARIES[i])) {
594                 loadService.registerRubyBuiltin(BUILTIN_LIBRARIES[i]);
595             }
596         }
597
598         registerBuiltin("jruby.rb", new JRubyLibrary());
599         registerBuiltin("iconv.rb", new IConvLibrary());
600         registerBuiltin("stringio.rb", new StringIOLibrary());
601         registerBuiltin("strscan.rb", new StringScannerLibrary());
602         registerBuiltin("zlib.rb", new ZlibLibrary());
603         registerBuiltin("yaml_internal.rb", new YamlLibrary());
604         registerBuiltin("enumerator.rb", new EnumeratorLibrary());
605         registerBuiltin("generator_internal.rb", new Generator.Service());
606         registerBuiltin("readline.rb", new Readline.Service());
607         registerBuiltin("thread.so", new ThreadLibrary());
608         registerBuiltin("openssl.so", new Library() {
609                 public void load(Ruby runtime) throws IOException JavaDoc {
610                     runtime.getModule("Kernel").callMethod(runtime.getCurrentContext(),"require",runtime.newString("rubygems"));
611                     runtime.getTopSelf().callMethod(runtime.getCurrentContext(),"gem",runtime.newString("jruby-openssl"));
612                     runtime.getModule("Kernel").callMethod(runtime.getCurrentContext(),"require",runtime.newString("jopenssl"));
613                 }
614             });
615         registerBuiltin("digest.so", new DigestLibrary());
616         registerBuiltin("digest.rb", new DigestLibrary());
617         registerBuiltin("digest/md5.rb", new DigestLibrary.MD5());
618         registerBuiltin("digest/rmd160.rb", new DigestLibrary.RMD160());
619         registerBuiltin("digest/sha1.rb", new DigestLibrary.SHA1());
620         registerBuiltin("digest/sha2.rb", new DigestLibrary.SHA2());
621         registerBuiltin("bigdecimal.rb", new BigDecimalLibrary());
622     }
623
624     private void registerBuiltin(String JavaDoc nm, Library lib) {
625         if(profile.allowBuiltin(nm)) {
626             loadService.registerBuiltin(nm,lib);
627         }
628     }
629
630     private void initCoreClasses() {
631         ObjectMetaClass objectMetaClass = new ObjectMetaClass(this);
632         objectMetaClass.initializeClass();
633
634         objectClass = objectMetaClass;
635         objectClass.setConstant("Object", objectClass);
636         RubyClass moduleClass = new ModuleMetaClass(this, objectClass);
637         objectClass.setConstant("Module", moduleClass);
638         RubyClass classClass = RubyClass.newClassClass(this, moduleClass);
639         objectClass.setConstant("Class", classClass);
640
641         // I don't think the containment is correct here (parent cref)
642
RubyClass metaClass = objectClass.makeMetaClass(classClass, objectMetaClass.getCRef());
643         metaClass = moduleClass.makeMetaClass(metaClass, objectMetaClass.getCRef());
644         metaClass = classClass.makeMetaClass(metaClass, objectMetaClass.getCRef());
645
646         ((ObjectMetaClass) moduleClass).initializeBootstrapClass();
647
648         kernelModule = RubyKernel.createKernelModule(this);
649         objectClass.includeModule(kernelModule);
650
651         RubyClass.createClassClass(classClass);
652
653         nilClass = RubyNil.createNilClass(this);
654
655         // Pre-create the core classes we know we will get referenced by starting up the runtime.
656
RubyBoolean.createFalseClass(this);
657         RubyBoolean.createTrueClass(this);
658         RubyComparable.createComparable(this);
659         RubyEnumerable.createEnumerableModule(this);
660         stringClass = new StringMetaClass(this);
661         stringClass.initializeClass();
662         new SymbolMetaClass(this).initializeClass();
663         if(profile.allowClass("ThreadGroup")) {
664             RubyThreadGroup.createThreadGroupClass(this);
665         }
666         if(profile.allowClass("Thread")) {
667             RubyThread.createThreadClass(this);
668         }
669         if(profile.allowClass("Exception")) {
670             RubyException.createExceptionClass(this);
671         }
672
673         if(profile.allowModule("Precision")) {
674             RubyPrecision.createPrecisionModule(this);
675         }
676
677         if(profile.allowClass("Numeric")) {
678             RubyNumeric.createNumericClass(this);
679         }
680
681         if(profile.allowClass("Integer")) {
682             RubyInteger.createIntegerClass(this);
683         }
684
685         if(profile.allowClass("Fixnum")) {
686             fixnumClass = RubyFixnum.createFixnumClass(this);
687         }
688         new HashMetaClass(this).initializeClass();
689         new IOMetaClass(this).initializeClass();
690
691         if(profile.allowClass("Array")) {
692             arrayClass = RubyArray.createArrayClass(this);
693         }
694
695         RubyClass structClass = null;
696         if(profile.allowClass("Struct")) {
697             structClass = RubyStruct.createStructClass(this);
698         }
699
700         if(profile.allowClass("Tms")) {
701             tmsStruct = RubyStruct.newInstance(structClass,
702                                                new IRubyObject[] {
703                                                    newString("Tms"),
704                                                    newSymbol("utime"),
705                                                    newSymbol("stime"),
706                                                    newSymbol("cutime"),
707                                                    newSymbol("cstime")}, Block.NULL_BLOCK);
708         }
709
710         if(profile.allowClass("Float")) {
711            RubyFloat.createFloatClass(this);
712         }
713
714         if(profile.allowClass("Bignum")) {
715             RubyBignum.createBignumClass(this);
716         }
717         if(profile.allowClass("Binding")) {
718             new BindingMetaClass(this).initializeClass();
719         }
720
721         if(profile.allowModule("Math")) {
722             RubyMath.createMathModule(this); // depends on all numeric types
723
}
724         if(profile.allowClass("Regexp")) {
725             RubyRegexp.createRegexpClass(this);
726         }
727         if(profile.allowClass("Range")) {
728             RubyRange.createRangeClass(this);
729         }
730         if(profile.allowModule("ObjectSpace")) {
731             RubyObjectSpace.createObjectSpaceModule(this);
732         }
733         if(profile.allowModule("GC")) {
734             RubyGC.createGCModule(this);
735         }
736
737         if(profile.allowClass("Proc")) {
738             new ProcMetaClass(this).initializeClass();
739         }
740
741         if(profile.allowClass("Method")) {
742             RubyMethod.createMethodClass(this);
743         }
744
745         if(profile.allowClass("MatchData")) {
746             RubyMatchData.createMatchDataClass(this);
747         }
748         if(profile.allowModule("Marshal")) {
749             RubyMarshal.createMarshalModule(this);
750         }
751
752         if(profile.allowClass("Dir")) {
753             RubyDir.createDirClass(this);
754         }
755
756         if(profile.allowModule("FileTest")) {
757             RubyFileTest.createFileTestModule(this);
758         }
759
760         if(profile.allowClass("File")) {
761             new FileMetaClass(this).initializeClass(); // depends on IO, FileTest
762
}
763
764         if(profile.allowModule("Process")) {
765             RubyProcess.createProcessModule(this);
766         }
767         if(profile.allowClass("Time")) {
768             new TimeMetaClass(this).initializeClass();
769         }
770         if(profile.allowClass("UnboundMethod")) {
771             RubyUnboundMethod.defineUnboundMethodClass(this);
772         }
773
774         RubyClass exceptionClass = getClass("Exception");
775         RubyClass standardError = null;
776         RubyClass runtimeError = null;
777         RubyClass ioError = null;
778         RubyClass scriptError = null;
779         RubyClass nameError = null;
780         RubyClass rangeError = null;
781         if(profile.allowClass("StandardError")) {
782             standardError = defineClass("StandardError", exceptionClass, exceptionClass.getAllocator());
783         }
784         if(profile.allowClass("RuntimeError")) {
785             runtimeError = defineClass("RuntimeError", standardError, standardError.getAllocator());
786         }
787         if(profile.allowClass("IOError")) {
788             ioError = defineClass("IOError", standardError, standardError.getAllocator());
789         }
790         if(profile.allowClass("ScriptError")) {
791             scriptError = defineClass("ScriptError", exceptionClass, exceptionClass.getAllocator());
792         }
793         if(profile.allowClass("NameError")) {
794             nameError = RubyNameError.createNameErrorClass(this, standardError);
795         }
796         if(profile.allowClass("RangeError")) {
797             rangeError = defineClass("RangeError", standardError, standardError.getAllocator());
798         }
799         if(profile.allowClass("SystemExit")) {
800             defineClass("SystemExit", exceptionClass, exceptionClass.getAllocator());
801         }
802         if(profile.allowClass("Fatal")) {
803             defineClass("Fatal", exceptionClass, exceptionClass.getAllocator());
804         }
805         if(profile.allowClass("Interrupt")) {
806             defineClass("Interrupt", exceptionClass, exceptionClass.getAllocator());
807         }
808         if(profile.allowClass("SignalException")) {
809             defineClass("SignalException", exceptionClass, exceptionClass.getAllocator());
810         }
811         if(profile.allowClass("TypeError")) {
812             defineClass("TypeError", standardError, standardError.getAllocator());
813         }
814         if(profile.allowClass("ArgumentError")) {
815             defineClass("ArgumentError", standardError, standardError.getAllocator());
816         }
817         if(profile.allowClass("IndexError")) {
818             defineClass("IndexError", standardError, standardError.getAllocator());
819         }
820         if(profile.allowClass("SyntaxError")) {
821             defineClass("SyntaxError", scriptError, scriptError.getAllocator());
822         }
823         if(profile.allowClass("LoadError")) {
824             defineClass("LoadError", scriptError, scriptError.getAllocator());
825         }
826         if(profile.allowClass("NotImplementedError")) {
827             defineClass("NotImplementedError", scriptError, scriptError.getAllocator());
828         }
829         if(profile.allowClass("NoMethodError")) {
830             defineClass("NoMethodError", nameError, nameError.getAllocator());
831         }
832         if(profile.allowClass("SecurityError")) {
833             defineClass("SecurityError", standardError, standardError.getAllocator());
834         }
835         if(profile.allowClass("NoMemoryError")) {
836             defineClass("NoMemoryError", exceptionClass, exceptionClass.getAllocator());
837         }
838         if(profile.allowClass("RegexpError")) {
839             defineClass("RegexpError", standardError, standardError.getAllocator());
840         }
841         if(profile.allowClass("EOFError")) {
842             defineClass("EOFError", ioError, ioError.getAllocator());
843         }
844         if(profile.allowClass("LocalJumpError")) {
845             defineClass("LocalJumpError", standardError, standardError.getAllocator());
846         }
847         if(profile.allowClass("ThreadError")) {
848             defineClass("ThreadError", standardError, standardError.getAllocator());
849         }
850         if(profile.allowClass("SystemStackError")) {
851             defineClass("SystemStackError", exceptionClass, exceptionClass.getAllocator());
852         }
853         if(profile.allowClass("ZeroDivisionError")) {
854             defineClass("ZeroDivisionError", standardError, standardError.getAllocator());
855         }
856         // FIXME: Actually this somewhere <- fixed
857
if(profile.allowClass("FloatDomainError")) {
858             defineClass("FloatDomainError", rangeError, rangeError.getAllocator());
859         }
860         if(profile.allowClass("NativeException")) {
861             NativeException.createClass(this, runtimeError);
862         }
863         if(profile.allowClass("SystemCallError")) {
864             systemCallError = defineClass("SystemCallError", standardError, standardError.getAllocator());
865         }
866         if(profile.allowModule("Errno")) {
867             errnoModule = defineModule("Errno");
868         }
869
870         initErrnoErrors();
871
872         if(profile.allowClass("Data")) {
873             defineClass("Data", objectClass, objectClass.getAllocator());
874         }
875
876         if(profile.allowModule("Signal")) {
877             RubySignal.createSignal(this);
878         }
879
880         if(profile.allowClass("Continuation")) {
881             RubyContinuation.createContinuation(this);
882         }
883     }
884
885     private void initBuiltinClasses() {
886     }
887
888     /**
889      * Create module Errno's Variables. We have this method since Errno does not have it's
890      * own java class.
891      */

892     private void initErrnoErrors() {
893         createSysErr(IErrno.ENOTEMPTY, "ENOTEMPTY");
894         createSysErr(IErrno.ERANGE, "ERANGE");
895         createSysErr(IErrno.ESPIPE, "ESPIPE");
896         createSysErr(IErrno.ENFILE, "ENFILE");
897         createSysErr(IErrno.EXDEV, "EXDEV");
898         createSysErr(IErrno.ENOMEM, "ENOMEM");
899         createSysErr(IErrno.E2BIG, "E2BIG");
900         createSysErr(IErrno.ENOENT, "ENOENT");
901         createSysErr(IErrno.ENOSYS, "ENOSYS");
902         createSysErr(IErrno.EDOM, "EDOM");
903         createSysErr(IErrno.ENOSPC, "ENOSPC");
904         createSysErr(IErrno.EINVAL, "EINVAL");
905         createSysErr(IErrno.EEXIST, "EEXIST");
906         createSysErr(IErrno.EAGAIN, "EAGAIN");
907         createSysErr(IErrno.ENXIO, "ENXIO");
908         createSysErr(IErrno.EILSEQ, "EILSEQ");
909         createSysErr(IErrno.ENOLCK, "ENOLCK");
910         createSysErr(IErrno.EPIPE, "EPIPE");
911         createSysErr(IErrno.EFBIG, "EFBIG");
912         createSysErr(IErrno.EISDIR, "EISDIR");
913         createSysErr(IErrno.EBUSY, "EBUSY");
914         createSysErr(IErrno.ECHILD, "ECHILD");
915         createSysErr(IErrno.EIO, "EIO");
916         createSysErr(IErrno.EPERM, "EPERM");
917         createSysErr(IErrno.EDEADLOCK, "EDEADLOCK");
918         createSysErr(IErrno.ENAMETOOLONG, "ENAMETOOLONG");
919         createSysErr(IErrno.EMLINK, "EMLINK");
920         createSysErr(IErrno.ENOTTY, "ENOTTY");
921         createSysErr(IErrno.ENOTDIR, "ENOTDIR");
922         createSysErr(IErrno.EFAULT, "EFAULT");
923         createSysErr(IErrno.EBADF, "EBADF");
924         createSysErr(IErrno.EINTR, "EINTR");
925         createSysErr(IErrno.EWOULDBLOCK, "EWOULDBLOCK");
926         createSysErr(IErrno.EDEADLK, "EDEADLK");
927         createSysErr(IErrno.EROFS, "EROFS");
928         createSysErr(IErrno.EMFILE, "EMFILE");
929         createSysErr(IErrno.ENODEV, "ENODEV");
930         createSysErr(IErrno.EACCES, "EACCES");
931         createSysErr(IErrno.ENOEXEC, "ENOEXEC");
932         createSysErr(IErrno.ESRCH, "ESRCH");
933         createSysErr(IErrno.ECONNREFUSED, "ECONNREFUSED");
934         createSysErr(IErrno.ECONNRESET, "ECONNRESET");
935         createSysErr(IErrno.EADDRINUSE, "EADDRINUSE");
936     }
937
938     /**
939      * Creates a system error.
940      * @param i the error code (will probably use a java exception instead)
941      * @param name of the error to define.
942      **/

943     private void createSysErr(int i, String JavaDoc name) {
944         if(profile.allowClass(name)) {
945             errnoModule.defineClassUnder(name, systemCallError, systemCallError.getAllocator()).defineConstant("Errno", newFixnum(i));
946         }
947     }
948
949     /** Getter for property isVerbose.
950      * @return Value of property isVerbose.
951      */

952     public IRubyObject getVerbose() {
953         return verbose;
954     }
955
956     /** Setter for property isVerbose.
957      * @param verbose New value of property isVerbose.
958      */

959     public void setVerbose(IRubyObject verbose) {
960         this.verbose = verbose;
961     }
962
963     /** Getter for property isDebug.
964      * @return Value of property isDebug.
965      */

966     public IRubyObject getDebug() {
967         return debug;
968     }
969
970     /** Setter for property isDebug.
971      * @param debug New value of property isDebug.
972      */

973     public void setDebug(IRubyObject debug) {
974         this.debug = debug;
975     }
976
977     public JavaSupport getJavaSupport() {
978         return javaSupport;
979     }
980
981     public JRubyClassLoader getJRubyClassLoader() {
982         return jrubyClassLoader;
983     }
984
985     /** Defines a global variable
986      */

987     public void defineVariable(final GlobalVariable variable) {
988         globalVariables.define(variable.name(), new IAccessor() {
989             public IRubyObject getValue() {
990                 return variable.get();
991             }
992
993             public IRubyObject setValue(IRubyObject newValue) {
994                 return variable.set(newValue);
995             }
996         });
997     }
998
999     /** defines a readonly global variable
1000     *
1001     */

1002    public void defineReadonlyVariable(String JavaDoc name, IRubyObject value) {
1003        globalVariables.defineReadonly(name, new ValueAccessor(value));
1004    }
1005
1006    public Node parse(Reader JavaDoc content, String JavaDoc file, DynamicScope scope) {
1007        return parser.parse(file, content, scope);
1008    }
1009
1010    public Node parse(String JavaDoc content, String JavaDoc file, DynamicScope scope) {
1011        return parser.parse(file, content, scope);
1012    }
1013
1014    public ThreadService getThreadService() {
1015        return threadService;
1016    }
1017
1018    public ThreadContext getCurrentContext() {
1019        return threadService.getCurrentContext();
1020    }
1021
1022    /**
1023     * Returns the loadService.
1024     * @return ILoadService
1025     */

1026    public LoadService getLoadService() {
1027        return loadService;
1028    }
1029
1030    public RubyWarnings getWarnings() {
1031        return warnings;
1032    }
1033
1034    public PrintStream JavaDoc getErrorStream() {
1035        java.io.OutputStream JavaDoc os = ((RubyIO) getGlobalVariables().get("$stderr")).getOutStream();
1036        if(null != os) {
1037            return new PrintStream JavaDoc(os);
1038        } else {
1039            return new PrintStream JavaDoc(new org.jruby.util.SwallowingOutputStream());
1040        }
1041    }
1042
1043    public InputStream JavaDoc getInputStream() {
1044        return ((RubyIO) getGlobalVariables().get("$stdin")).getInStream();
1045    }
1046
1047    public PrintStream JavaDoc getOutputStream() {
1048        return new PrintStream JavaDoc(((RubyIO) getGlobalVariables().get("$stdout")).getOutStream());
1049    }
1050
1051    public RubyModule getClassFromPath(String JavaDoc path) {
1052        if (path.charAt(0) == '#') {
1053            throw newArgumentError("can't retrieve anonymous class " + path);
1054        }
1055        IRubyObject type = evalScript(path);
1056        if (!(type instanceof RubyModule)) {
1057            throw newTypeError("class path " + path + " does not point class");
1058        }
1059        return (RubyModule) type;
1060    }
1061
1062    /** Prints an error with backtrace to the error stream.
1063     *
1064     * MRI: eval.c - error_print()
1065     *
1066     */

1067    public void printError(RubyException excp) {
1068        if (excp == null || excp.isNil()) {
1069            return;
1070        }
1071
1072        ThreadContext tc = getCurrentContext();
1073        IRubyObject backtrace = excp.callMethod(tc, "backtrace");
1074
1075        PrintStream JavaDoc errorStream = getErrorStream();
1076        if (backtrace.isNil() || !(backtrace instanceof RubyArray)) {
1077            if (tc.getSourceFile() != null) {
1078                errorStream.print(tc.getPosition());
1079            } else {
1080                errorStream.print(tc.getSourceLine());
1081            }
1082        } else if (((RubyArray) backtrace).getLength() == 0) {
1083            printErrorPos(errorStream);
1084        } else {
1085            IRubyObject mesg = ((RubyArray) backtrace).first(IRubyObject.NULL_ARRAY);
1086
1087            if (mesg.isNil()) {
1088                printErrorPos(errorStream);
1089            } else {
1090                errorStream.print(mesg);
1091            }
1092        }
1093
1094        RubyClass type = excp.getMetaClass();
1095        String JavaDoc info = excp.toString();
1096
1097        if (type == getClass("RuntimeError") && (info == null || info.length() == 0)) {
1098            errorStream.print(": unhandled exception\n");
1099        } else {
1100            String JavaDoc path = type.getName();
1101
1102            if (info.length() == 0) {
1103                errorStream.print(": " + path + '\n');
1104            } else {
1105                if (path.startsWith("#")) {
1106                    path = null;
1107                }
1108
1109                String JavaDoc tail = null;
1110                if (info.indexOf("\n") != -1) {
1111                    tail = info.substring(info.indexOf("\n") + 1);
1112                    info = info.substring(0, info.indexOf("\n"));
1113                }
1114
1115                errorStream.print(": " + info);
1116
1117                if (path != null) {
1118                    errorStream.print(" (" + path + ")\n");
1119                }
1120
1121                if (tail != null) {
1122                    errorStream.print(tail + '\n');
1123                }
1124            }
1125        }
1126
1127        excp.printBacktrace(errorStream);
1128    }
1129
1130    private void printErrorPos(PrintStream JavaDoc errorStream) {
1131        ThreadContext tc = getCurrentContext();
1132        if (tc.getSourceFile() != null) {
1133            if (tc.getFrameName() != null) {
1134                errorStream.print(tc.getPosition());
1135                errorStream.print(":in '" + tc.getFrameName() + '\'');
1136            } else if (tc.getSourceLine() != 0) {
1137                errorStream.print(tc.getPosition());
1138            } else {
1139                errorStream.print(tc.getSourceFile());
1140            }
1141        }
1142    }
1143
1144    /** This method compiles and interprets a Ruby script.
1145     *
1146     * It can be used if you want to use JRuby as a Macro language.
1147     *
1148     */

1149    public void loadScript(RubyString scriptName, RubyString source, boolean wrap) {
1150        loadScript(scriptName.toString(), new StringReader JavaDoc(source.toString()), wrap);
1151    }
1152
1153    public void loadScript(String JavaDoc scriptName, Reader JavaDoc source, boolean wrap) {
1154        File JavaDoc f = new File JavaDoc(scriptName);
1155        if(f.exists() && !f.isAbsolute() && !scriptName.startsWith("./")) {
1156            scriptName = "./" + scriptName;
1157        }
1158
1159        IRubyObject self = getTopSelf();
1160
1161        ThreadContext context = getCurrentContext();
1162
1163        RubyModule wrapper = context.getWrapper();
1164
1165        try {
1166            if (!wrap) {
1167                secure(4); /* should alter global state */
1168
1169                context.preNodeEval(null, objectClass, self);
1170            } else {
1171                /* load in anonymous module as toplevel */
1172                context.preNodeEval(RubyModule.newModule(this, null), context.getWrapper(), self);
1173
1174                self = getTopSelf().rbClone();
1175                self.extendObject(context.getRubyClass());
1176            }
1177
1178            Node node = parse(source, scriptName, null);
1179            self.eval(node);
1180        } catch (JumpException je) {
1181            if (je.getJumpType() == JumpException.JumpType.ReturnJump) {
1182                // Make sure this does not bubble out to java caller.
1183
} else {
1184                throw je;
1185            }
1186        } finally {
1187            context.postNodeEval(wrapper);
1188        }
1189    }
1190
1191    public void loadNode(String JavaDoc scriptName, Node node, boolean wrap) {
1192        IRubyObject self = getTopSelf();
1193
1194        ThreadContext context = getCurrentContext();
1195
1196        RubyModule wrapper = context.getWrapper();
1197
1198        try {
1199            if (!wrap) {
1200                secure(4); /* should alter global state */
1201
1202                context.preNodeEval(null, objectClass, self);
1203            } else {
1204
1205                /* load in anonymous module as toplevel */
1206                context.preNodeEval(RubyModule.newModule(this, null), context.getWrapper(), self);
1207
1208                self = getTopSelf().rbClone();
1209                self.extendObject(context.getRubyClass());
1210            }
1211
1212            self.eval(node);
1213        } catch (JumpException je) {
1214            if (je.getJumpType() == JumpException.JumpType.ReturnJump) {
1215                // Make sure this does not bubble out to java caller.
1216
} else {
1217                throw je;
1218            }
1219        } finally {
1220            context.postNodeEval(wrapper);
1221        }
1222    }
1223
1224
1225    /** Loads, compiles and interprets a Ruby file.
1226     * Used by Kernel#require.
1227     *
1228     * @mri rb_load
1229     */

1230    public void loadFile(File JavaDoc file, boolean wrap) {
1231        assert file != null : "No such file to load";
1232        try {
1233            BufferedReader JavaDoc source = new BufferedReader JavaDoc(new FileReader JavaDoc(file));
1234            loadScript(file.getPath().replace(File.separatorChar, '/'), source, wrap);
1235            source.close();
1236        } catch (IOException JavaDoc ioExcptn) {
1237            throw newIOErrorFromException(ioExcptn);
1238        }
1239    }
1240
1241    /** Call the trace function
1242     *
1243     * MRI: eval.c - call_trace_func
1244     *
1245     */

1246    public void callTraceFunction(ThreadContext context, String JavaDoc event, ISourcePosition position,
1247            IRubyObject self, String JavaDoc name, IRubyObject type) {
1248        if (traceFunction == null) return;
1249
1250        if (!context.isWithinTrace()) {
1251            context.setWithinTrace(true);
1252
1253            ISourcePosition savePosition = context.getPosition();
1254            String JavaDoc file = position.getFile();
1255
1256            if (file == null) file = "(ruby)";
1257            if (type == null) type = getFalse();
1258
1259            context.preTrace();
1260            try {
1261                traceFunction.call(new IRubyObject[] { newString(event), newString(file),
1262                        newFixnum(position.getEndLine()),
1263                        name != null ? RubySymbol.newSymbol(this, name) : getNil(),
1264                        self != null ? self : getNil(),
1265                        type });
1266            } finally {
1267                context.postTrace();
1268                context.setPosition(savePosition);
1269                context.setWithinTrace(false);
1270            }
1271        }
1272    }
1273
1274    public RubyProc getTraceFunction() {
1275        return traceFunction;
1276    }
1277
1278    public void setTraceFunction(RubyProc traceFunction) {
1279        this.traceFunction = traceFunction;
1280    }
1281    public GlobalVariables getGlobalVariables() {
1282        return globalVariables;
1283    }
1284
1285    // For JSR 223 support: see http://scripting.java.net/
1286
public void setGlobalVariables(GlobalVariables globalVariables) {
1287        this.globalVariables = globalVariables;
1288    }
1289
1290    public CallbackFactory callbackFactory(Class JavaDoc type) {
1291        return CallbackFactory.createFactory(this, type);
1292    }
1293
1294    /**
1295     * Push block onto exit stack. When runtime environment exits
1296     * these blocks will be evaluated.
1297     *
1298     * @return the element that was pushed onto stack
1299     */

1300    public IRubyObject pushExitBlock(RubyProc proc) {
1301        atExitBlocks.push(proc);
1302        return proc;
1303    }
1304
1305    /**
1306     * Make sure Kernel#at_exit procs get invoked on runtime shutdown.
1307     * This method needs to be explicitly called to work properly.
1308     * I thought about using finalize(), but that did not work and I
1309     * am not sure the runtime will be at a state to run procs by the
1310     * time Ruby is going away. This method can contain any other
1311     * things that need to be cleaned up at shutdown.
1312     */

1313    public void tearDown() {
1314        while (!atExitBlocks.empty()) {
1315            RubyProc proc = (RubyProc) atExitBlocks.pop();
1316
1317            proc.call(IRubyObject.NULL_ARRAY);
1318        }
1319        getObjectSpace().finishFinalizers();
1320    }
1321
1322    // new factory methods ------------------------------------------------------------------------
1323

1324    public RubyArray newArray() {
1325        return RubyArray.newArray(this);
1326    }
1327
1328    public RubyArray newArrayLight() {
1329        return RubyArray.newArrayLight(this);
1330    }
1331
1332    public RubyArray newArray(IRubyObject object) {
1333        return RubyArray.newArray(this, object);
1334    }
1335
1336    public RubyArray newArray(IRubyObject car, IRubyObject cdr) {
1337        return RubyArray.newArray(this, car, cdr);
1338    }
1339
1340    public RubyArray newArray(IRubyObject[] objects) {
1341        return RubyArray.newArray(this, objects);
1342    }
1343    
1344    public RubyArray newArrayNoCopy(IRubyObject[] objects) {
1345        return RubyArray.newArrayNoCopy(this, objects);
1346    }
1347    
1348    public RubyArray newArray(List JavaDoc list) {
1349        return RubyArray.newArray(this, list);
1350    }
1351
1352    public RubyArray newArray(int size) {
1353        return RubyArray.newArray(this, size);
1354    }
1355
1356    public RubyBoolean newBoolean(boolean value) {
1357        return RubyBoolean.newBoolean(this, value);
1358    }
1359
1360    public RubyFileStat newRubyFileStat(String JavaDoc file) {
1361        return (RubyFileStat)getClass("File").getClass("Stat").callMethod(getCurrentContext(),"new",newString(file));
1362    }
1363
1364    public RubyFixnum newFixnum(long value) {
1365        return RubyFixnum.newFixnum(this, value);
1366    }
1367
1368    public RubyFloat newFloat(double value) {
1369        return RubyFloat.newFloat(this, value);
1370    }
1371
1372    public RubyNumeric newNumeric() {
1373        return RubyNumeric.newNumeric(this);
1374    }
1375
1376    public RubyProc newProc(boolean isLambda, Block block) {
1377        if (!isLambda && block.getProcObject() != null) return block.getProcObject();
1378
1379        RubyProc proc = RubyProc.newProc(this, isLambda);
1380
1381        proc.callInit(IRubyObject.NULL_ARRAY, block);
1382
1383        return proc;
1384    }
1385
1386    public RubyBinding newBinding() {
1387        return RubyBinding.newBinding(this);
1388    }
1389
1390    public RubyBinding newBinding(Block block) {
1391        return RubyBinding.newBinding(this, block);
1392    }
1393
1394    public RubyString newString(String JavaDoc string) {
1395        return RubyString.newString(this, string);
1396    }
1397    
1398    public RubyString newString(ByteList byteList) {
1399        return RubyString.newString(this, byteList);
1400    }
1401
1402    public RubySymbol newSymbol(String JavaDoc string) {
1403        return RubySymbol.newSymbol(this, string);
1404    }
1405
1406    public RubyTime newTime(long milliseconds) {
1407        return RubyTime.newTime(this, milliseconds);
1408    }
1409
1410    public RaiseException newArgumentError(String JavaDoc message) {
1411        return newRaiseException(getClass("ArgumentError"), message);
1412    }
1413
1414    public RaiseException newArgumentError(int got, int expected) {
1415        return newRaiseException(getClass("ArgumentError"), "wrong # of arguments(" + got + " for " + expected + ")");
1416    }
1417
1418    public RaiseException newErrnoEBADFError() {
1419        return newRaiseException(getModule("Errno").getClass("EBADF"), "Bad file descriptor");
1420    }
1421
1422    public RaiseException newErrnoECONNREFUSEDError() {
1423        return newRaiseException(getModule("Errno").getClass("ECONNREFUSED"), "Connection refused");
1424    }
1425
1426    public RaiseException newErrnoEADDRINUSEError() {
1427        return newRaiseException(getModule("Errno").getClass("EADDRINUSE"), "Address in use");
1428    }
1429
1430    public RaiseException newErrnoEINVALError() {
1431        return newRaiseException(getModule("Errno").getClass("EINVAL"), "Invalid file");
1432    }
1433
1434    public RaiseException newErrnoENOENTError() {
1435        return newRaiseException(getModule("Errno").getClass("ENOENT"), "File not found");
1436    }
1437
1438    public RaiseException newErrnoESPIPEError() {
1439        return newRaiseException(getModule("Errno").getClass("ESPIPE"), "Illegal seek");
1440    }
1441
1442    public RaiseException newErrnoEBADFError(String JavaDoc message) {
1443        return newRaiseException(getModule("Errno").getClass("EBADF"), message);
1444    }
1445
1446    public RaiseException newErrnoEINVALError(String JavaDoc message) {
1447        return newRaiseException(getModule("Errno").getClass("EINVAL"), message);
1448    }
1449
1450    public RaiseException newErrnoENOENTError(String JavaDoc message) {
1451        return newRaiseException(getModule("Errno").getClass("ENOENT"), message);
1452    }
1453
1454    public RaiseException newErrnoESPIPEError(String JavaDoc message) {
1455        return newRaiseException(getModule("Errno").getClass("ESPIPE"), message);
1456    }
1457
1458    public RaiseException newErrnoEEXISTError(String JavaDoc message) {
1459        return newRaiseException(getModule("Errno").getClass("EEXIST"), message);
1460    }
1461    
1462    public RaiseException newErrnoEDOMError(String JavaDoc message) {
1463        return newRaiseException(getModule("Errno").getClass("EDOM"), "Domain error - " + message);
1464    }
1465
1466    public RaiseException newIndexError(String JavaDoc message) {
1467        return newRaiseException(getClass("IndexError"), message);
1468    }
1469
1470    public RaiseException newSecurityError(String JavaDoc message) {
1471        return newRaiseException(getClass("SecurityError"), message);
1472    }
1473
1474    public RaiseException newSystemCallError(String JavaDoc message) {
1475        return newRaiseException(getClass("SystemCallError"), message);
1476    }
1477
1478    public RaiseException newTypeError(String JavaDoc message) {
1479        return newRaiseException(getClass("TypeError"), message);
1480    }
1481
1482    public RaiseException newThreadError(String JavaDoc message) {
1483        return newRaiseException(getClass("ThreadError"), message);
1484    }
1485
1486    public RaiseException newSyntaxError(String JavaDoc message) {
1487        return newRaiseException(getClass("SyntaxError"), message);
1488    }
1489
1490    public RaiseException newRangeError(String JavaDoc message) {
1491        return newRaiseException(getClass("RangeError"), message);
1492    }
1493
1494    public RaiseException newNotImplementedError(String JavaDoc message) {
1495        return newRaiseException(getClass("NotImplementedError"), message);
1496    }
1497    
1498    public RaiseException newInvalidEncoding(String JavaDoc message) {
1499        return newRaiseException(getClass("Iconv").getClass("InvalidEncoding"), message);
1500    }
1501
1502    public RaiseException newNoMethodError(String JavaDoc message, String JavaDoc name) {
1503        return new RaiseException(new RubyNameError(this, this.getClass("NoMethodError"), message, name), true);
1504    }
1505
1506    public RaiseException newNameError(String JavaDoc message, String JavaDoc name) {
1507        return new RaiseException(new RubyNameError(this, this.getClass("NameError"), message, name), true);
1508    }
1509
1510    public RaiseException newLocalJumpError(String JavaDoc message) {
1511        return newRaiseException(getClass("LocalJumpError"), message);
1512    }
1513
1514    public RaiseException newLoadError(String JavaDoc message) {
1515        return newRaiseException(getClass("LoadError"), message);
1516    }
1517
1518    public RaiseException newFrozenError(String JavaDoc objectType) {
1519        // TODO: Should frozen error have its own distinct class? If not should more share?
1520
return newRaiseException(getClass("TypeError"), "can't modify frozen " + objectType);
1521    }
1522
1523    public RaiseException newSystemStackError(String JavaDoc message) {
1524        return newRaiseException(getClass("SystemStackError"), message);
1525    }
1526
1527    public RaiseException newSystemExit(int status) {
1528        RaiseException re = newRaiseException(getClass("SystemExit"), "");
1529        re.getException().setInstanceVariable("status", newFixnum(status));
1530
1531        return re;
1532    }
1533
1534    public RaiseException newIOError(String JavaDoc message) {
1535        return newRaiseException(getClass("IOError"), message);
1536    }
1537
1538    public RaiseException newStandardError(String JavaDoc message) {
1539        return newRaiseException(getClass("StandardError"), message);
1540    }
1541
1542    public RaiseException newIOErrorFromException(IOException JavaDoc ioe) {
1543        return newRaiseException(getClass("IOError"), ioe.getMessage());
1544    }
1545
1546    public RaiseException newTypeError(IRubyObject receivedObject, RubyClass expectedType) {
1547        return newRaiseException(getClass("TypeError"), "wrong argument type " + receivedObject.getMetaClass() + " (expected " + expectedType);
1548    }
1549
1550    public RaiseException newEOFError() {
1551        return newRaiseException(getClass("EOFError"), "End of file reached");
1552    }
1553
1554    public RaiseException newZeroDivisionError() {
1555        return newRaiseException(getClass("ZeroDivisionError"), "divided by 0");
1556    }
1557
1558    public RaiseException newFloatDomainError(String JavaDoc message){
1559        return newRaiseException(getClass("FloatDomainError"), message);
1560    }
1561
1562    /**
1563     * @param exceptionClass
1564     * @param message
1565     * @return
1566     */

1567    private RaiseException newRaiseException(RubyClass exceptionClass, String JavaDoc message) {
1568        RaiseException re = new RaiseException(this, exceptionClass, message, true);
1569        return re;
1570    }
1571
1572
1573    public RubySymbol.SymbolTable getSymbolTable() {
1574        return symbolTable;
1575    }
1576
1577    public void setStackTraces(int stackTraces) {
1578        this.stackTraces = stackTraces;
1579    }
1580
1581    public int getStackTraces() {
1582        return stackTraces;
1583    }
1584
1585    public void setRandomSeed(long randomSeed) {
1586        this.randomSeed = randomSeed;
1587    }
1588
1589    public long getRandomSeed() {
1590        return randomSeed;
1591    }
1592
1593    public Random JavaDoc getRandom() {
1594        return random;
1595    }
1596
1597    public ObjectSpace getObjectSpace() {
1598        return objectSpace;
1599    }
1600
1601    public Hashtable JavaDoc getIoHandlers() {
1602        return ioHandlers;
1603    }
1604
1605    public RubyFixnum[] getFixnumCache() {
1606        return fixnumCache;
1607    }
1608
1609    public long incrementRandomSeedSequence() {
1610        return randomSeedSequence++;
1611    }
1612
1613    public InputStream JavaDoc getIn() {
1614        return in;
1615    }
1616
1617    public PrintStream JavaDoc getOut() {
1618        return out;
1619    }
1620
1621    public PrintStream JavaDoc getErr() {
1622        return err;
1623    }
1624
1625    public boolean isGlobalAbortOnExceptionEnabled() {
1626        return globalAbortOnExceptionEnabled;
1627    }
1628
1629    public void setGlobalAbortOnExceptionEnabled(boolean enable) {
1630        globalAbortOnExceptionEnabled = enable;
1631    }
1632
1633    public boolean isDoNotReverseLookupEnabled() {
1634        return doNotReverseLookupEnabled;
1635    }
1636
1637    public void setDoNotReverseLookupEnabled(boolean b) {
1638        doNotReverseLookupEnabled = b;
1639    }
1640
1641    private ThreadLocal JavaDoc inspect = new ThreadLocal JavaDoc();
1642    public boolean registerInspecting(Object JavaDoc obj) {
1643        java.util.Map JavaDoc val = (java.util.Map JavaDoc)inspect.get();
1644        if(null == val) {
1645            val = new java.util.IdentityHashMap JavaDoc();
1646            inspect.set(val);
1647        }
1648        if(val.containsKey(obj)) {
1649            return false;
1650        }
1651        val.put(obj, null);
1652        return true;
1653    }
1654
1655    public void unregisterInspecting(Object JavaDoc obj) {
1656        java.util.Map JavaDoc val = (java.util.Map JavaDoc)inspect.get();
1657        val.remove(obj);
1658    }
1659
1660    public boolean isObjectSpaceEnabled() {
1661        return objectSpaceEnabled;
1662    }
1663
1664    public long getStartTime() {
1665        return startTime;
1666    }
1667
1668    public Profile getProfile() {
1669        return profile;
1670    }
1671
1672    public String JavaDoc getJRubyHome() {
1673        if (jrubyHome == null) {
1674            jrubyHome = verifyHome(System.getProperty("jruby.home", System.getProperty("user.home") + "/.jruby"));
1675        }
1676        return jrubyHome;
1677    }
1678    
1679    public void setJRubyHome(String JavaDoc home) {
1680        jrubyHome = verifyHome(home);
1681    }
1682
1683    // We require the home directory to be absolute
1684
private String JavaDoc verifyHome(String JavaDoc home) {
1685        NormalizedFile f = new NormalizedFile(home);
1686        if (!f.isAbsolute()) {
1687            home = f.getAbsolutePath();
1688        }
1689        f.mkdirs();
1690        return home;
1691    }
1692
1693    public RubyInstanceConfig getInstanceConfig() {
1694        return config;
1695    }
1696
1697    /** GET_VM_STATE_VERSION */
1698    public long getGlobalState() {
1699        synchronized(this) {
1700            return globalState;
1701        }
1702    }
1703
1704    /** INC_VM_STATE_VERSION */
1705    public void incGlobalState() {
1706        synchronized(this) {
1707            globalState = (globalState+1) & 0x8fffffff;
1708        }
1709    }
1710}
1711
Popular Tags