/
Ruby.java
4103 lines (3472 loc) · 143 KB
/
Ruby.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
**** 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 org.jruby.util.func.Function1;
import java.io.ByteArrayInputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.jcodings.Encoding;
import org.joda.time.DateTimeZone;
import org.jruby.ast.Node;
import org.jruby.ast.executable.Script;
import org.jruby.common.RubyWarnings;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.compiler.ASTCompiler;
import org.jruby.compiler.ASTInspector;
import org.jruby.compiler.JITCompiler;
import org.jruby.compiler.impl.StandardASMCompiler;
import org.jruby.compiler.NotCompilableException;
import org.jruby.exceptions.JumpException;
import org.jruby.exceptions.MainExitException;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.JRubyPOSIXHandler;
import org.jruby.ext.LateLoadingLibrary;
import org.jruby.ext.posix.POSIX;
import org.jruby.ext.posix.POSIXFactory;
import org.jruby.internal.runtime.GlobalVariables;
import org.jruby.internal.runtime.ThreadService;
import org.jruby.internal.runtime.ValueAccessor;
import org.jruby.javasupport.JavaSupport;
import org.jruby.management.ClassCache;
import org.jruby.management.Config;
import org.jruby.management.ParserStats;
import org.jruby.parser.EvalStaticScope;
import org.jruby.parser.Parser;
import org.jruby.parser.ParserConfiguration;
import org.jruby.runtime.Binding;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.DynamicScope;
import org.jruby.runtime.EventHook;
import org.jruby.runtime.GlobalVariable;
import org.jruby.runtime.IAccessor;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ObjectSpace;
import org.jruby.runtime.RubyEvent;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.encoding.EncodingService;
import org.jruby.runtime.load.CompiledScriptLoader;
import org.jruby.runtime.load.Library;
import org.jruby.runtime.load.LoadService;
import org.jruby.runtime.profile.IProfileData;
import org.jruby.runtime.scope.ManyVarsDynamicScope;
import org.jruby.util.BuiltinScript;
import org.jruby.util.ByteList;
import org.jruby.util.IOInputStream;
import org.jruby.util.IOOutputStream;
import org.jruby.util.JRubyClassLoader;
import org.jruby.util.JavaNameMangler;
import org.jruby.util.KCode;
import org.jruby.util.SafePropertyAccessor;
import org.jruby.util.collections.WeakHashSet;
import org.jruby.util.io.ChannelDescriptor;
import com.kenai.constantine.Constant;
import com.kenai.constantine.ConstantSet;
import com.kenai.constantine.platform.Errno;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.EnumSet;
import java.util.concurrent.atomic.AtomicLong;
import org.jruby.RubyInstanceConfig.CompileMode;
import org.jruby.ast.RootNode;
import org.jruby.ast.executable.RuntimeCache;
import org.jruby.evaluator.ASTInterpreter;
import org.jruby.exceptions.Unrescuable;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.interpreter.Interpreter;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.management.BeanManager;
import org.jruby.management.BeanManagerFactory;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.threading.DaemonThreadFactory;
import org.jruby.util.io.SelectorPool;
/**
* 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 {
/**
* Returns a new instance of the JRuby runtime configured with defaults.
*
* @return the JRuby runtime
* @see org.jruby.RubyInstanceConfig
*/
public static Ruby newInstance() {
return newInstance(new RubyInstanceConfig());
}
/**
* Returns a new instance of the JRuby runtime configured as specified.
*
* @param config The instance configuration
* @return The JRuby runtime
* @see org.jruby.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).
*
* @param in the custom input stream
* @param out the custom output stream
* @param err the custom error stream
* @return the JRuby runtime
* @see org.jruby.RubyInstanceConfig
*/
public static Ruby newInstance(InputStream in, PrintStream out, PrintStream err) {
RubyInstanceConfig config = new RubyInstanceConfig();
config.setInput(in);
config.setOutput(out);
config.setError(err);
return newInstance(config);
}
private static Ruby globalRuntime;
/**
* 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.
*
* @return true if a global runtime is instantiated, false for other.
*
*/
public static boolean isGlobalRuntimeReady() {
return globalRuntime != null;
}
private static synchronized void setGlobalRuntimeFirstTimeOnly(Ruby runtime) {
if (globalRuntime == null) {
globalRuntime = runtime;
}
}
public static synchronized Ruby getGlobalRuntime() {
if (globalRuntime == null) {
newInstance();
}
return globalRuntime;
}
/**
* Convenience method for java integrators who may need to switch the notion
* of "global" runtime. Use <tt>JRuby.runtime.use_as_global_runtime</tt>
* from Ruby code to activate the current runtime as the global one.
*/
public void useAsGlobalRuntime() {
synchronized(Ruby.class) {
globalRuntime = null;
setGlobalRuntimeFirstTimeOnly(this);
}
}
/**
* Create and initialize a new JRuby runtime. The properties of the
* specified RubyInstanceConfig will be used to determine various JRuby
* runtime characteristics.
*
* @param config The configuration to use for the new instance
* @see org.jruby.RubyInstanceConfig
*/
private Ruby(RubyInstanceConfig config) {
this.config = config;
this.is1_9 = config.getCompatVersion() == CompatVersion.RUBY1_9;
this.doNotReverseLookupEnabled = is1_9;
this.threadService = new ThreadService(this);
if(config.isSamplingEnabled()) {
org.jruby.util.SimpleSampler.registerThreadContext(threadService.getCurrentContext());
}
this.in = config.getInput();
this.out = config.getOutput();
this.err = config.getError();
this.objectSpaceEnabled = config.isObjectSpaceEnabled();
this.profile = config.getProfile();
this.currentDirectory = config.getCurrentDirectory();
this.kcode = config.getKCode();
this.beanManager = BeanManagerFactory.create(this, config.isManagementEnabled());
this.jitCompiler = new JITCompiler(this);
this.parserStats = new ParserStats(this);
this.beanManager.register(new Config(this));
this.beanManager.register(parserStats);
this.beanManager.register(new ClassCache(this));
this.runtimeCache = new RuntimeCache();
runtimeCache.initMethodCache(ClassIndex.MAX_CLASSES * MethodIndex.MAX_METHODS);
}
/**
* 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.
*
* @param 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(new EvalStaticScope(currentScope.getStaticScope()), currentScope);
return evalScriptlet(script, newScope);
}
/**
* 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.
*
* @param script The scriptlet to run
* @param 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 script, DynamicScope scope) {
ThreadContext context = getCurrentContext();
Node node = parseEval(script, "<script>", scope, 0);
try {
context.preEvalScriptlet(scope);
return ASTInterpreter.INTERPRET_ROOT(this, context, node, context.getFrameSelf(), Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
throw newLocalJumpError(RubyLocalJumpError.Reason.RETURN, (IRubyObject)rj.getValue(), "unexpected return");
} catch (JumpException.BreakJump bj) {
throw newLocalJumpError(RubyLocalJumpError.Reason.BREAK, (IRubyObject)bj.getValue(), "unexpected break");
} catch (JumpException.RedoJump rj) {
throw newLocalJumpError(RubyLocalJumpError.Reason.REDO, (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.
*
* @param script The contents of the script to run as a normal, root script
* @return The last value of the script
*/
public IRubyObject executeScript(String script, String filename) {
byte[] bytes = script.getBytes();
Node node = parseInline(new ByteArrayInputStream(bytes), filename, null);
ThreadContext context = getCurrentContext();
String oldFile = context.getFile();
int oldLine = context.getLine();
try {
context.setFileAndLine(node.getPosition());
return runInterpreter(node);
} finally {
context.setFileAndLine(oldFile, oldLine);
}
}
/**
* 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).
*
* @param inputStream The InputStream from which to read the script contents
* @param filename The filename to use when parsing, and for $PROGRAM_NAME
* and $0 ruby global variables.
*/
public void runFromMain(InputStream inputStream, String filename) {
IAccessor d = new ValueAccessor(newString(filename));
getGlobalVariables().define("$PROGRAM_NAME", d);
getGlobalVariables().define("$0", d);
for (Iterator i = config.getOptionGlobals().entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.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(this, inputStream, filename);
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(inputStream, filename);
// 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 (config.isAssumePrinting() || config.isAssumeLoop()) {
runWithGetsLoop(scriptNode, config.isAssumePrinting(), config.isProcessLineEnds(),
config.isSplit());
} else {
runNormally(scriptNode);
}
} finally {
context.setFileAndLine(oldFile, oldLine);
if (config.isProfilingEntireRun()) {
IProfileData profileData = (IProfileData) context.getProfileData();
config.makeDefaultProfilePrinter(profileData).printProfile(System.out);
}
}
}
/**
* 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.
*
* @param inputStream The input stream from which to read the script
* @param filename The filename to use for parsing
* @returns The root node of the parsed script
*/
public Node parseFromMain(InputStream inputStream, String filename) {
if (config.isInlineScript()) {
return parseInline(inputStream, filename, getCurrentContext().getCurrentScope());
} else {
return parseFile(inputStream, filename, getCurrentContext().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.
*
* @param scriptNode The root node of the script to execute
* @param printing Whether $_ should be printed after each loop (as in the
* -p command-line flag)
* @param processLineEnds Whether line endings should be processed by
* setting $\ to $/ and <code>chop!</code>ing every line read
* @param split Whether to split each line read using <code>String#split</code>
* bytecode before executing.
* @return The result of executing the specified script
*/
@Deprecated
public IRubyObject runWithGetsLoop(Node scriptNode, boolean printing, boolean processLineEnds, boolean split, boolean unused) {
return runWithGetsLoop(scriptNode, printing, processLineEnds, split);
}
/**
* 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.
*
* @param scriptNode The root node of the script to execute
* @param printing Whether $_ should be printed after each loop (as in the
* -p command-line flag)
* @param processLineEnds Whether line endings should be processed by
* setting $\ to $/ and <code>chop!</code>ing every line read
* @param split Whether to split each line read using <code>String#split</code>
* bytecode before executing.
* @return The result of executing the specified script
*/
public IRubyObject runWithGetsLoop(Node scriptNode, boolean printing, boolean processLineEnds, boolean 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(context, getTopSelf(), IRubyObject.NULL_ARRAY).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(context, getKernel(), 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 (IRubyObject) bj.getValue();
}
}
}
} finally {
RuntimeHelpers.postLoad(context);
}
return getNil();
}
/**
* Run the specified script without any of the loop-processing wrapper
* code.
*
* @param scriptNode The root node of the script to be executed
* bytecode before execution
* @return The result of executing the script
*/
@Deprecated
public IRubyObject runNormally(Node scriptNode, boolean unused) {
return runNormally(scriptNode);
}
/**
* Run the specified script without any of the loop-processing wrapper
* code.
*
* @param scriptNode The root node of the script to be executed
* bytecode before execution
* @return The result of executing the script
*/
public IRubyObject runNormally(Node scriptNode) {
Script script = null;
boolean compile = getInstanceConfig().getCompileMode().shouldPrecompileCLI();
boolean forceCompile = getInstanceConfig().getCompileMode().shouldPrecompileAll();
if (compile) {
script = tryCompile(scriptNode, null, new JRubyClassLoader(getJRubyClassLoader()), config.isShowBytecode());
if (forceCompile && script == null) {
return getNil();
}
}
if (config.isShowBytecode()) {
if (script == null) {
// try to force compile the script again, in case we are in a -X-C or dynopt mode
script = tryCompile(scriptNode, null, new JRubyClassLoader(getJRubyClassLoader()), config.isShowBytecode());
}
// if still null, print error and return
if (script == null) {
System.err.print("error: bytecode printing only works with JVM bytecode");
}
return nilObject;
} else {
if (script != null) {
return runScript(script);
} else {
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.
*
* @param node The node to attempt to compiled
* @return an instance of the successfully-compiled Script, or null.
*/
public Script tryCompile(Node node) {
return tryCompile(node, null, new 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.
*
* @param node The node to attempt to compiled
* @param inspector The ASTInspector to use for making optimization decisions
* @return an instance of the successfully-compiled Script, or null.
*/
public Script tryCompile(Node node, ASTInspector inspector) {
return tryCompile(node, null, new JRubyClassLoader(getJRubyClassLoader()), inspector, false);
}
private Script tryCompile(Node node, String cachedClassName, JRubyClassLoader classLoader, boolean dump) {
ASTInspector inspector = new ASTInspector();
inspector.inspect(node);
return tryCompile(node, cachedClassName, classLoader, inspector, dump);
}
private Script tryCompile(Node node, String cachedClassName, JRubyClassLoader classLoader, ASTInspector inspector, boolean dump) {
Script script = null;
try {
String filename = node.getPosition().getFile();
String classname = JavaNameMangler.mangledFilenameForStartupClasspath(filename);
StandardASMCompiler asmCompiler = null;
if (RubyInstanceConfig.JIT_CODE_CACHE != null && cachedClassName != null) {
asmCompiler = new StandardASMCompiler(cachedClassName.replace('.', '/'), filename);
} else {
asmCompiler = new StandardASMCompiler(classname, filename);
}
ASTCompiler compiler = config.newCompiler();
if (dump) {
compiler.compileRoot(node, asmCompiler, inspector, false, false);
asmCompiler.dumpClass(System.out);
} else {
compiler.compileRoot(node, asmCompiler, inspector, true, false);
}
if (RubyInstanceConfig.JIT_CODE_CACHE != null && cachedClassName != null) {
// save script off to disk
String pathName = cachedClassName.replace('.', '/');
JITCompiler.saveToCodeCache(this, asmCompiler.getClassByteArray(), "ruby/jit", new File(RubyInstanceConfig.JIT_CODE_CACHE, pathName + ".class"));
}
script = (Script)asmCompiler.loadClass(classLoader).newInstance();
if (config.isJitLogging()) {
System.err.println("compiled: " + node.getPosition().getFile());
}
} catch (NotCompilableException nce) {
if (config.isJitLoggingVerbose() || config.isDebug()) {
System.err.println("warning: not compileable: " + nce.getMessage());
nce.printStackTrace();
} else {
System.err.println("warning: could not compile; pass -d or -J-Djruby.jit.logging.verbose=true for more details");
}
} catch (ClassNotFoundException e) {
if (config.isJitLoggingVerbose() || config.isDebug()) {
System.err.println("warning: not compileable: " + e.getMessage());
e.printStackTrace();
} else {
System.err.println("warning: could not compile; pass -d or -J-Djruby.jit.logging.verbose=true for more details");
}
} catch (InstantiationException e) {
if (config.isJitLoggingVerbose() || config.isDebug()) {
System.err.println("warning: not compilable: " + e.getMessage());
e.printStackTrace();
} else {
System.err.println("warning: could not compile; pass -d or -J-Djruby.jit.logging.verbose=true for more details");
}
} catch (IllegalAccessException e) {
if (config.isJitLoggingVerbose() || config.isDebug()) {
System.err.println("warning: not compilable: " + e.getMessage());
e.printStackTrace();
} else {
System.err.println("warning: could not compile; pass -d or -J-Djruby.jit.logging.verbose=true for more details");
}
} catch (Throwable t) {
if (config.isJitLoggingVerbose() || config.isDebug()) {
System.err.println("warning: could not compile: " + node.getPosition().getFile() + " because of: \"" + t.getMessage() + "\"");
t.printStackTrace();
} else {
System.err.println("warning: could not compile; pass -d or -J-Djruby.jit.logging.verbose=true for more details");
}
}
return script;
}
public IRubyObject runScript(Script script) {
ThreadContext context = getCurrentContext();
try {
return script.load(context, getTopSelf(), IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
return (IRubyObject) rj.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__(context, getTopSelf(), Block.NULL_BLOCK);
} catch (JumpException.ReturnJump rj) {
return (IRubyObject) rj.getValue();
}
}
public IRubyObject runInterpreter(ThreadContext context, Node rootNode, IRubyObject self) {
assert rootNode != null : "scriptNode is not null";
try {
if (getInstanceConfig().getCompileMode() == CompileMode.OFFIR) {
return Interpreter.interpret(this, rootNode, self);
} else {
return ASTInterpreter.INTERPRET_ROOT(this, context, rootNode, getTopSelf(), Block.NULL_BLOCK);
}
} catch (JumpException.ReturnJump rj) {
return (IRubyObject) rj.getValue();
}
}
public IRubyObject runInterpreter(Node scriptNode) {
return runInterpreter(getCurrentContext(), scriptNode, getTopSelf());
}
/**
* 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(((RootNode) scriptNode).getBodyNode());
}
public Parser getParser() {
return parser;
}
public BeanManager getBeanManager() {
return beanManager;
}
public JITCompiler getJITCompiler() {
return jitCompiler;
}
/**
* @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 symbolLastId.incrementAndGet();
}
public int allocModuleId() {
return moduleLastId.incrementAndGet();
}
public void addModule(RubyModule module) {
synchronized (allModules) {
allModules.add(module);
}
}
public void eachModule(Function1<Object, IRubyObject> func) {
synchronized (allModules) {
for (RubyModule module : allModules) {
func.apply(module);
}
}
}
/**
* Retrieve the module with the given name from the Object namespace.
*
* @param name The name of the module
* @return The module or null if not found
*/
public RubyModule getModule(String name) {
return (RubyModule) objectClass.getConstantAt(name);
}
/**
* Retrieve the module 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.
*
* @param internedName The name of the module; <em>must</em> be an interned String
* @return The module or null if not found
*/
public RubyModule fastGetModule(String internedName) {
return (RubyModule) objectClass.fastGetConstantAt(internedName);
}
/**
* Retrieve the class with the given name from the Object namespace.
*
* @param name The name of the class
* @return The class
*/
public RubyClass getClass(String name) {
return objectClass.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.
*
* @param internedName the name of the class; <em>must</em> be an interned String!
* @return
*/
public RubyClass fastGetClass(String internedName) {
return objectClass.fastGetClass(internedName);
}
/**
* Define a new class under the Object namespace. Roughly equivalent to
* rb_define_class in MRI.
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @return The new class
*/
public RubyClass defineClass(String name, RubyClass superClass, ObjectAllocator allocator) {
return defineClassUnder(name, superClass, allocator, objectClass);
}
/**
* A variation of defineClass that allows passing in an array of subplementary
* call sites for improving dynamic invocation performance.
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @return The new class
*/
public RubyClass defineClass(String name, RubyClass superClass, ObjectAllocator allocator, CallSite[] callSites) {
return defineClassUnder(name, superClass, allocator, objectClass, callSites);
}
/**
* 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
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @param parent The namespace under which to define the new class
* @return The new class
*/
public RubyClass defineClassUnder(String name, RubyClass superClass, ObjectAllocator allocator, RubyModule parent) {
return defineClassUnder(name, superClass, allocator, parent, null);
}
/**
* A variation of defineClassUnder that allows passing in an array of
* supplementary call sites to improve dynamic invocation.
*
* @param name The name for the new class
* @param superClass The super class for the new class
* @param allocator An ObjectAllocator instance that can construct
* instances of the new class.
* @param parent The namespace under which to define the new class
* @param callSites The array of call sites to add
* @return The new class
*/
public RubyClass defineClassUnder(String name, RubyClass superClass, ObjectAllocator allocator, RubyModule parent, CallSite[] 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 == objectClass;
if (superClass == null) {
String className = parentIsObject ? name : parent.getName() + "::" + name;
warnings.warn(ID.NO_SUPER_CLASS, "no super class for `" + className + "', Object assumed", className);
superClass = objectClass;
}
return RubyClass.newClass(this, superClass, name, allocator, parent, !parentIsObject, callSites);
}
/**
* Define a new module under the Object namespace. Roughly equivalent to
* rb_define_module in MRI.
*
* @param name The name of the new module
* @returns The new module
*/
public RubyModule defineModule(String name) {
return defineModuleUnder(name, objectClass);
}
/**
* Define a new module with the given name under the given module or
* class namespace. Roughly equivalent to rb_define_module_under in MRI.
*
* @param name The name of the new module
* @param parent The class or module namespace under which to define the
* module
* @returns The new module
*/
public RubyModule defineModuleUnder(String name, RubyModule parent) {
IRubyObject moduleObj = parent.getConstantAt(name);
boolean parentIsObject = parent == objectClass;
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(this, name, parent, !parentIsObject);
}
/**
* From Object, retrieve the named module. If it doesn't exist a
* new module is created.
*
* @param name The name of the module
* @returns The existing or new module
*/
public RubyModule getOrCreateModule(String name) {
IRubyObject module = objectClass.getConstantAt(name);
if (module == null) {
module = defineModule(name);
} else if (getSafeLevel() >= 4) {
throw newSecurityError("Extending module prohibited.");
} else if (!module.isModule()) {
throw newTypeError(name + " is not a Module");
}
return (RubyModule) module;
}
/**
* Retrieve the current safe level.
*
* @see org.jruby.Ruby#setSaveLevel
*/
public int getSafeLevel() {
return this.safeLevel;
}
/**
* Set the current safe level:
*