-
Notifications
You must be signed in to change notification settings - Fork 915
/
IRRuntimeHelpers.java
2617 lines (2155 loc) · 111 KB
/
IRRuntimeHelpers.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
package org.jruby.ir.runtime;
import com.headius.invokebinder.Signature;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import org.jcodings.Encoding;
import org.jruby.EvalType;
import org.jruby.MetaClass;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBasicObject;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyComplex;
import org.jruby.RubyEncoding;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyInstanceConfig;
import org.jruby.RubyMatchData;
import org.jruby.RubyMethod;
import org.jruby.RubyModule;
import org.jruby.RubyNil;
import org.jruby.RubyProc;
import org.jruby.RubyRational;
import org.jruby.RubyRegexp;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.common.IRubyWarnings;
import org.jruby.exceptions.RaiseException;
import org.jruby.exceptions.Unrescuable;
import org.jruby.ext.coverage.CoverageData;
import org.jruby.internal.runtime.methods.CompiledIRMethod;
import org.jruby.internal.runtime.methods.CompiledIRNoProtocolMethod;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.internal.runtime.methods.InterpretedIRMetaClassBody;
import org.jruby.internal.runtime.methods.InterpretedIRMethod;
import org.jruby.internal.runtime.methods.MixedModeIRMethod;
import org.jruby.ir.IRScope;
import org.jruby.ir.IRScopeType;
import org.jruby.ir.IRScriptBody;
import org.jruby.ir.Interp;
import org.jruby.ir.JIT;
import org.jruby.ir.operands.IRException;
import org.jruby.ir.operands.Operand;
import org.jruby.ir.operands.Splat;
import org.jruby.ir.persistence.IRReader;
import org.jruby.ir.persistence.IRReaderStream;
import org.jruby.java.invokers.InstanceMethodInvoker;
import org.jruby.java.invokers.RubyToJavaInvoker;
import org.jruby.java.proxies.JavaProxy;
import org.jruby.javasupport.JavaMethod;
import org.jruby.javasupport.proxy.JavaProxyClass;
import org.jruby.javasupport.proxy.JavaProxyMethod;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Binding;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockBody;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.CallType;
import org.jruby.runtime.DynamicScope;
import org.jruby.runtime.Frame;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.IRBlockBody;
import org.jruby.runtime.JavaSites.IRRuntimeHelpersSites;
import org.jruby.runtime.RubyEvent;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.TraceEventManager;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.backtrace.RubyStackTraceElement;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callsite.CacheEntry;
import org.jruby.runtime.callsite.CachingCallSite;
import org.jruby.runtime.callsite.FunctionalCachingCallSite;
import org.jruby.runtime.callsite.MonomorphicCallSite;
import org.jruby.runtime.callsite.ProfilingCachingCallSite;
import org.jruby.runtime.callsite.RefinedCachingCallSite;
import org.jruby.runtime.callsite.VariableCachingCallSite;
import org.jruby.runtime.ivars.VariableAccessor;
import org.jruby.util.ArraySupport;
import org.jruby.util.ByteList;
import org.jruby.util.RegexpOptions;
import org.jruby.util.TypeConverter;
import org.jruby.util.cli.Options;
import org.jruby.util.log.Logger;
import org.jruby.util.log.LoggerFactory;
import org.objectweb.asm.Type;
import static org.jruby.ir.operands.UndefinedValue.UNDEFINED;
import static org.jruby.runtime.Block.Type.LAMBDA;
import static org.jruby.runtime.ThreadContext.*;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.ids;
import static org.jruby.runtime.Arity.UNLIMITED_ARGUMENTS;
public class IRRuntimeHelpers {
private static final Logger LOG = LoggerFactory.getLogger(IRRuntimeHelpers.class);
public static boolean inProfileMode() {
return RubyInstanceConfig.IR_PROFILE;
}
public static boolean isDebug() {
return RubyInstanceConfig.IR_DEBUG;
}
public static boolean inNonMethodBodyLambda(StaticScope scope, Block.Type blockType) {
// SSS FIXME: Hack! AST interpreter and JIT compiler marks a proc's static scope as
// an argument scope if it is used to define a method's body via :define_method.
// Since that is exactly what we want to figure out here, am just using that flag here.
// But, this is ugly (as is the original hack in the current runtime). What is really
// needed is a new block type -- a block that is used to define a method body.
return blockType == LAMBDA && !scope.isArgumentScope();
}
public static boolean inMethod(Block.Type blockType) {
return blockType == null;
}
public static boolean inLambda(Block.Type blockType) {
return blockType == LAMBDA;
}
public static boolean inProc(Block.Type blockType) {
return blockType == Block.Type.PROC;
}
// FIXME: ENEBO: If we inline this instr then dynScope will be for the inlined dynscope and that scope could be many things.
// CheckForLJEInstr.clone should convert this as appropriate based on what it is being inlined into.
@Interp @JIT
public static void checkForLJE(ThreadContext context, DynamicScope currentScope, boolean definedWithinMethod, Block block) {
if (inLambda(block.type)) return; // break/return in lambda is unconditionally a return.
DynamicScope returnToScope = getContainingReturnToScope(currentScope);
if (returnToScope == null || !context.scopeExistsOnCallStack(returnToScope)) {
throw IRException.RETURN_LocalJumpError.getException(context.runtime);
}
}
/*
* Closures cannot statically determine whether they are a proc or a lambda. So we look at the live stack
* to see if we are within one.
*
* Note: as a result of this all lambdas which contain returns in nested scopes (or itself) can never eliminate
* its binding.
*/
private static DynamicScope getContainingLambda(DynamicScope dynamicScope) {
for (DynamicScope scope = dynamicScope; scope != null && scope.getStaticScope().isBlockScope(); scope = scope.getParentScope()) {
// we are within a lambda but not a define_method (which seemingly advertises itself as a lambda).
if (scope.isLambda() && !scope.getStaticScope().isArgumentScope()) return scope;
}
return null;
}
// Create a jump for a non-local return which will return from nearest lambda (which may be itself) or method.
@JIT @Interp
public static IRubyObject initiateNonLocalReturn(DynamicScope currentScope, Block block, IRubyObject returnValue) {
if (block != null && inLambda(block.type)) throw new IRWrappedLambdaReturnValue(returnValue);
DynamicScope returnToScope = getContainingLambda(currentScope);
if (returnToScope == null) returnToScope = getContainingReturnToScope(currentScope);
assert returnToScope != null: "accidental return scope";
throw IRReturnJump.create(currentScope.getStaticScope(), returnToScope, returnValue);
}
// Finds static scope of where we want to *return* to.
private static DynamicScope getContainingReturnToScope(DynamicScope returnLocationScope) {
for (DynamicScope current = returnLocationScope; current != null; current = current.getParentScope()) {
if (current.isReturnTarget()) return current;
}
return null;
}
@JIT
public static IRubyObject handleNonlocalReturn(DynamicScope currentScope, Object rjExc) throws RuntimeException {
if (!(rjExc instanceof IRReturnJump)) {
Helpers.throwException((Throwable)rjExc);
return null; // Unreachable
} else {
IRReturnJump rj = (IRReturnJump)rjExc;
// If we are in the method scope we are supposed to return from, stop p<ropagating.
if (rj.isReturnToScope(currentScope)) {
if (isDebug()) System.out.println("---> Non-local Return reached target in scope: " + currentScope);
return (IRubyObject) rj.returnValue;
}
// If not, Just pass it along!
throw rj;
}
}
// Is the current dynamicScope we pass in representing a closure (or eval which is impld internally as closure)?
private static IRScopeType ensureScopeIsClosure(ThreadContext context, DynamicScope dynamicScope) {
IRScopeType scopeType = dynamicScope.getStaticScope().getScopeType();
// Error -- breaks can only be initiated in closures
if (!scopeType.isClosureType()) throw IRException.BREAK_LocalJumpError.getException(context.runtime);
return scopeType;
}
// FIXME: When we recompile lambdas we can eliminate this binary code path and we can emit as a NONLOCALRETURN directly.
@JIT
public static IRubyObject initiateBreak(ThreadContext context, DynamicScope dynScope, IRubyObject breakValue, Block block) throws RuntimeException {
// Wrap the return value in an exception object and push it through the break exception
// paths so that ensures are run, frames/scopes are popped from runtime stacks, etc.
if (inLambda(block.type)) throw new IRWrappedLambdaReturnValue(breakValue, true);
IRScopeType scopeType = ensureScopeIsClosure(context, dynScope);
DynamicScope parentScope = dynScope.getParentScope();
if (block.isEscaped()) {
throw Helpers.newLocalJumpErrorForBreak(context.runtime, breakValue);
}
// Raise a break jump so we can bubble back down the stack to the appropriate place to break from.
throw IRBreakJump.create(parentScope, breakValue, scopeType.isEval()); // weirdly evals are impld as closures...yes yes.
}
// Are we within the scope where we want to return the value we are passing down the stack?
private static boolean inReturnToScope(Block.Type blockType, IRReturnJump exception, DynamicScope currentScope) {
return (inMethod(blockType) || inLambda(blockType)) && exception.isReturnToScope(currentScope);
}
@JIT
public static IRubyObject handleBreakAndReturnsInLambdas(ThreadContext context, DynamicScope dynScope, Object exc, Block block) throws RuntimeException {
if (exc instanceof IRWrappedLambdaReturnValue) {
// Wrap the return value in an exception object and push it through the nonlocal return exception
// paths so that ensures are run, frames/scopes are popped from runtime stacks, etc.
return ((IRWrappedLambdaReturnValue) exc).returnValue;
} else if (exc instanceof IRReturnJump && dynScope != null && inReturnToScope(block.type, (IRReturnJump) exc, dynScope)) {
if (isDebug()) System.out.println("---> Non-local Return reached target in scope: " + dynScope);
return (IRubyObject) ((IRReturnJump) exc).returnValue;
} else {
// Propagate the exception
context.setSavedExceptionInLambda((Throwable) exc);
return null;
}
}
@JIT
public static IRubyObject returnOrRethrowSavedException(ThreadContext context, IRubyObject value) {
// This rethrows the exception saved in handleBreakAndReturnsInLambda
// after additional code to pop frames, bindings, etc. are done.
Throwable exc = context.getSavedExceptionInLambda();
if (exc != null) {
// IMPORTANT: always clear!
context.setSavedExceptionInLambda(null);
Helpers.throwException(exc);
}
// otherwise, return value
return value;
}
@JIT
public static IRubyObject handlePropagatedBreak(ThreadContext context, DynamicScope dynScope, Object bjExc) {
if (!(bjExc instanceof IRBreakJump)) {
Helpers.throwException((Throwable)bjExc);
return null; // Unreachable
}
IRBreakJump bj = (IRBreakJump)bjExc;
if (bj.breakInEval) {
// If the break was in an eval, we pretend as if it was in the containing scope.
ensureScopeIsClosure(context, dynScope);
bj.breakInEval = false;
throw bj;
} else if (bj.scopeToReturnTo == dynScope) {
// Done!! Hurray!
if (isDebug()) System.out.println("---> Break reached target in scope: " + dynScope);
return bj.breakValue;
/* ---------------------------------------------------------------
* SSS FIXME: Puzzled .. Why is this not needed?
} else if (!context.scopeExistsOnCallStack(bj.scopeToReturnTo.getStaticScope())) {
throw IRException.BREAK_LocalJumpError.getException(context.runtime);
* --------------------------------------------------------------- */
} else {
// Propagate
throw bj;
}
}
// Used by JIT
public static IRubyObject undefMethod(ThreadContext context, Object nameArg, DynamicScope currDynScope, IRubyObject self) {
RubyModule module = IRRuntimeHelpers.findInstanceMethodContainer(context, currDynScope, self);
String name = (nameArg instanceof String) ?
(String) nameArg : nameArg.toString();
if (module == null) {
throw context.runtime.newTypeError("No class to undef method '" + name + "'.");
}
module.undef(context, name);
return context.nil;
}
@JIT
public static double unboxFloat(IRubyObject val) {
if (val instanceof RubyFloat) {
return ((RubyFloat)val).getValue();
} else {
return ((RubyFixnum)val).getDoubleValue();
}
}
@JIT
public static long unboxFixnum(IRubyObject val) {
if (val instanceof RubyFloat) {
return (long)((RubyFloat)val).getValue();
} else {
return ((RubyFixnum)val).getLongValue();
}
}
public static boolean flt(double v1, double v2) {
return v1 < v2;
}
public static boolean fgt(double v1, double v2) {
return v1 > v2;
}
public static boolean feq(double v1, double v2) {
return v1 == v2;
}
public static boolean ilt(long v1, long v2) {
return v1 < v2;
}
public static boolean igt(long v1, long v2) {
return v1 > v2;
}
public static boolean ieq(long v1, long v2) {
return v1 == v2;
}
public static Object unwrapRubyException(Object excObj) {
// Unrescuable:
// IRBreakJump, IRReturnJump, ThreadKill, RubyContinuation, MainExitException, etc.
// These cannot be rescued -- only run ensure blocks
if (excObj instanceof Unrescuable) {
Helpers.throwException((Throwable)excObj);
}
// Ruby exceptions, errors, and other java exceptions.
// These can be rescued -- run rescue blocks
return (excObj instanceof RaiseException) ? ((RaiseException) excObj).getException() : excObj;
}
private static boolean isJavaExceptionHandled(ThreadContext context, IRubyObject excType, Object excObj, boolean arrayCheck) {
if (!(excObj instanceof Throwable)) {
return false;
}
final Ruby runtime = context.runtime;
final Throwable ex = (Throwable) excObj;
if (excType instanceof RubyArray) {
RubyArray testTypes = (RubyArray)excType;
for (int i = 0, n = testTypes.getLength(); i < n; i++) {
IRubyObject testType = testTypes.eltInternal(i);
if (IRRuntimeHelpers.isJavaExceptionHandled(context, testType, ex, true)) {
IRubyObject exception;
if (n == 1) {
exception = wrapJavaException(context, testType, ex);
} else { // wrap as normal JI object
exception = Helpers.wrapJavaException(runtime, ex);
}
runtime.getGlobalVariables().set("$!", exception);
return true;
}
}
}
else {
IRubyObject exception = wrapJavaException(context, excType, ex);
if (Helpers.checkJavaException(exception, ex, excType, context)) {
runtime.getGlobalVariables().set("$!", exception);
return true;
}
}
return false;
}
private static IRubyObject wrapJavaException(final ThreadContext context, final IRubyObject excType, final Throwable throwable) {
final Ruby runtime = context.runtime;
if (excType == runtime.getNativeException()) {
return wrapWithNativeException(context, throwable, runtime);
}
return Helpers.wrapJavaException(runtime, throwable); // wrap as normal JI object
}
@SuppressWarnings("deprecation")
private static IRubyObject wrapWithNativeException(ThreadContext context, Throwable throwable, Ruby runtime) {
// wrap Throwable in a NativeException object
org.jruby.NativeException exception = new org.jruby.NativeException(runtime, runtime.getNativeException(), throwable);
exception.prepareIntegratedBacktrace(context, throwable.getStackTrace());
return exception;
}
private static boolean isRubyExceptionHandled(ThreadContext context, IRubyObject excType, Object excObj) {
if (excType instanceof RubyArray) {
RubyArray testTypes = (RubyArray)excType;
for (int i = 0, n = testTypes.getLength(); i < n; i++) {
IRubyObject testType = testTypes.eltInternal(i);
if (IRRuntimeHelpers.isRubyExceptionHandled(context, testType, excObj)) {
context.runtime.getGlobalVariables().set("$!", (IRubyObject)excObj);
return true;
}
}
} else if (excObj instanceof IRubyObject) {
// SSS FIXME: Should this check be "runtime.getModule().isInstance(excType)"??
if (!(excType instanceof RubyModule)) {
throw context.runtime.newTypeError("class or module required for rescue clause. Found: " + excType);
}
if (excType.callMethod(context, "===", (IRubyObject)excObj).isTrue()) {
context.runtime.getGlobalVariables().set("$!", (IRubyObject)excObj);
return true;
}
}
return false;
}
public static IRubyObject isExceptionHandled(ThreadContext context, IRubyObject excType, Object excObj) {
// SSS FIXME: JIT should do an explicit unwrap in code just like in interpreter mode.
// This is called once for each RescueEQQ instr and unwrapping each time is unnecessary.
// This is not a performance issue, but more a question of where this belongs.
// It seems more logical to (a) recv-exc (b) unwrap-exc (c) do all the rescue-eqq checks.
//
// Unwrap Ruby exceptions
excObj = unwrapRubyException(excObj);
boolean ret = IRRuntimeHelpers.isRubyExceptionHandled(context, excType, excObj)
|| IRRuntimeHelpers.isJavaExceptionHandled(context, excType, excObj, false);
return RubyBoolean.newBoolean(context, ret);
}
// partially: vm_insnhelper.c - vm_check_match + check_match
public static IRubyObject isEQQ(ThreadContext context, IRubyObject receiver, IRubyObject value, CallSite callSite, boolean splattedValue) {
boolean isUndefValue = value == UNDEFINED;
if (splattedValue && receiver instanceof RubyArray) { // multiple value when
RubyArray testVals = (RubyArray) receiver;
for (int i = 0, n = testVals.getLength(); i < n; i++) {
IRubyObject v = testVals.eltInternal(i);
IRubyObject eqqVal = isUndefValue ? v : callSite.call(context, v, v, value);
if (eqqVal.isTrue()) return eqqVal;
}
return context.fals;
}
if (isUndefValue) return receiver; // no arg case single when
return callSite.call(context, receiver, receiver, value); // single when
}
public static IRubyObject newProc(Ruby runtime, Block block) {
return (block == Block.NULL_BLOCK) ? runtime.getNil() : runtime.newProc(Block.Type.PROC, block);
}
@JIT
public static IRubyObject newProc(ThreadContext context, Block block) {
Ruby runtime = context.runtime;
return (block == Block.NULL_BLOCK) ? runtime.getNil() : runtime.newProc(Block.Type.PROC, block);
}
@JIT
public static RubyProc newLambdaProc(ThreadContext context, Block block) {
Ruby runtime = context.runtime;
return runtime.newProc(LAMBDA, block);
}
@JIT
public static IRubyObject yield(ThreadContext context, Block b, IRubyObject yieldVal, boolean unwrapArray) {
return (unwrapArray && (yieldVal instanceof RubyArray)) ? b.yieldArray(context, yieldVal, null) : b.yield(context, yieldVal);
}
@JIT
public static IRubyObject yieldSpecific(ThreadContext context, Block b) {
return b.yieldSpecific(context);
}
@JIT
public static IRubyObject yieldValues(ThreadContext context, Block blk, IRubyObject[] args) {
return blk.yieldValues(context, args);
}
// .call for PROC
public static IRubyObject[] convertValueIntoArgArray(ThreadContext context, IRubyObject value, org.jruby.runtime.Signature signature) {
switch (signature.arityValue()) {
case -1:
return signature.opt() > 1 && value instanceof RubyArray ?
((RubyArray) value).toJavaArray() :
new IRubyObject[] { value };
case 0:
case 1:
return signature.rest() == org.jruby.runtime.Signature.Rest.ANON ?
IRBlockBody.toAry(context, value) :
new IRubyObject[] { value };
}
return IRBlockBody.toAry(context, value);
}
// NORMAL yield paths passed through yieldSpecific and call (for when block is passed through -- some internal weirdness on our part).
public static IRubyObject[] convertValueIntoArgArray(ThreadContext context, RubyArray array, org.jruby.runtime.Signature signature) {
switch (signature.arityValue()) {
case -1:
return array.toJavaArray();
case 0:
case 1:
return new IRubyObject[] { array };
}
return singleBlockArgToArray(Helpers.aryToAry(context, array.size() == 1 ? array.eltInternal(0) : array));
}
@JIT
public static Block getBlockFromObject(ThreadContext context, Object value) {
Block block;
if (value instanceof Block) {
block = (Block) value;
} else if (value instanceof RubyProc) {
block = ((RubyProc) value).getBlock();
} else if (value instanceof RubyMethod) {
block = ((RubyProc) ((RubyMethod) value).to_proc(context)).getBlock();
} else if (value instanceof RubySymbol) {
block = ((RubyProc) ((RubySymbol) value).to_proc(context)).getBlock();
} else if ((value instanceof IRubyObject) && ((IRubyObject)value).isNil()) {
block = Block.NULL_BLOCK;
} else if (value instanceof IRubyObject) {
block = ((RubyProc) TypeConverter.convertToType((IRubyObject) value, context.runtime.getProc(), "to_proc", true)).getBlock();
} else {
throw new RuntimeException("Unhandled case in CallInstr:prepareBlock. Got block arg: " + value);
}
return block;
}
@JIT
public static Block getRefinedBlockFromObject(ThreadContext context, StaticScope scope, Object value) {
Block block;
if (value instanceof Block) {
block = (Block) value;
} else if (value instanceof RubyProc) {
block = ((RubyProc) value).getBlock();
} else if (value instanceof RubyMethod) {
block = ((RubyProc) ((RubyMethod) value).to_proc(context)).getBlock();
} else if (value instanceof RubySymbol) {
block = ((RubyProc) ((RubySymbol) value).toRefinedProc(context, scope)).getBlock();
} else if ((value instanceof IRubyObject) && ((IRubyObject)value).isNil()) {
block = Block.NULL_BLOCK;
} else if (value instanceof IRubyObject) {
block = ((RubyProc) TypeConverter.convertToType((IRubyObject) value, context.runtime.getProc(), "to_proc", true)).getBlock();
} else {
throw new RuntimeException("Unhandled case in CallInstr:prepareBlock. Got block arg: " + value);
}
return block;
}
/*
* Specific arity methods made during the JIT only accept the arguments they accept. One strange case with
* Ruby 3 keywords is any method can recieve an extra argument for keyword arguments. For specific arity we do
* no accept keyword args but any method can pass them anyways. We have instructions for processing keywords
* but in specific arity methods we check arity mismatches in an args[] signature and it will complain if it
* sees that extra kwarg....and it should...unless it happens to be empty (**{}). In that case we silently ignore
* that empty arg.
*
* As of 9.4.0.0 the design is such that in Ruby we bifurcate and check for empty kwargs and do not pass them.
* For ruby2_keyword methods we do not do this (or we would have to put this same if conditional for every call
* in Ruby along with a dynamic check looking to see if it is this kind of method -- which would be before our
* actual callsite). So this special logic here literally only exists for ruby2_keyword arg methods which receive and
* pass splatted values (where last one might be an empty kwarg hash).
*
* Note: we probably need this logic baked into every callsite in the system as this would cause a hit in the case
* of keywords but it is much simpler than having all kwargs parameter calls emit an if statement looking for
* emptiness in the kwarg. Also all native methods will complain for this case if you call with an empty kwarg.
*/
public static void checkAritySpecificArgs(ThreadContext context, StaticScope scope, Object[] args,
int required, int opt, boolean rest, int restKey, Block block) {
int argsLength = args.length;
if ((block == null || block.type.checkArity) && (argsLength < required || (!rest && argsLength > (required + opt)))) {
if (argsLength > (required + opt) && args[argsLength - 1] instanceof RubyHash) {
RubyHash last = (RubyHash) args[argsLength - 1];
if (last.isRuby2KeywordHash() && last.isEmpty()) return;
}
//System.out.println("C: " + context.getFile() + ":" + context.getLine());
Arity.raiseArgumentError(context.runtime, argsLength, required, rest ? UNLIMITED_ARGUMENTS : (required + opt));
}
}
public static void checkArity(ThreadContext context, StaticScope scope, Object[] args, Object keywords,
int required, int opt, boolean rest, int restKey, Block block) {
int argsLength = args.length - (keywords != UNDEFINED ? 1: 0);
if ((block == null || block.type.checkArity) && (argsLength < required || (!rest && argsLength > (required + opt)))) {
//System.out.println("C: " + context.getFile() + ":" + context.getLine());
Arity.raiseArgumentError(context.runtime, argsLength, required, rest ? UNLIMITED_ARGUMENTS : (required + opt));
}
if (restKey == -1 && keywords != UNDEFINED) checkForExtraUnwantedKeywordArgs(context, scope, (RubyHash) keywords);
}
/**
* If the ir.print property is enabled and we are not booting, or the ir.print.all property is enabled and we are
* booting, return true to indicate IR should be printed.
*
* @param runtime the current runtime
* @return whether to print IR
*/
public static boolean shouldPrintIR(final Ruby runtime) {
boolean booting = runtime.isBooting();
boolean print = Options.IR_PRINT.load();
boolean printAll = Options.IR_PRINT_ALL.load();
return (!booting && print) || (booting && printAll);
}
/**
* Update coverage data for the given file and zero-based line number.
*
* @param context
* @param filename
* @param line
*/
public static void updateCoverage(ThreadContext context, String filename, int line) {
CoverageData data = context.runtime.getCoverageData();
if (data.isRunning()) data.coverLine(filename, line);
}
@JIT @Interp
public static IRubyObject hashCheck(ThreadContext context, IRubyObject hash) {
return TypeConverter.checkHashType(context.runtime, hash);
}
public static IRubyObject isHashEmpty(ThreadContext context, IRubyObject hash) {
// ARGSPUSH ended up realizing we have an empty kwargs already and stripped off the empty value (meaning
// any call need not worry about subtracting a kwargs argument.
if ((context.callInfo & CALL_KEYWORD_EMPTY) != 0) return context.fals;
hash = TypeConverter.checkHashType(context.runtime, hash);
boolean isEmpty = hash instanceof RubyHash && ((RubyHash) hash).size() == 0;
if (isEmpty) context.callInfo |= CALL_KEYWORD_EMPTY;
return isEmpty ? context.tru : context.fals;
}
public static IRubyObject undefined() {
return UNDEFINED;
}
// specific arity methods in JIT will only be fixed arity meaning no kwargs and no rest args.
// this logic is the same as recieveKeywords but we know it will never be a keyword argument (jit
// will save %undefined as the keyword value).
// Due to jruby/jruby#8119 and the potential for ruby2_keywords flags to change after JIT, jitted code will always
// call on this path and pass in the live value of ruby2_keywords from the scope.
@JIT
public static IRubyObject receiveSpecificArityKeywords(ThreadContext context, IRubyObject last, boolean ruby2Keywords) {
if (!(last instanceof RubyHash)) {
ThreadContext.clearCallInfo(context);
return last;
}
return ruby2Keywords ?
receiveSpecificArityRuby2HashKeywords(context, last) :
receiveSpecificArityHashKeywords(context, last);
}
private static IRubyObject receiveSpecificArityHashKeywords(ThreadContext context, IRubyObject last) {
int callInfo = ThreadContext.resetCallInfo(context);
boolean isKwarg = (callInfo & CALL_KEYWORD) != 0;
return receiverSpecificArityKwargsCommon(context, last, callInfo, isKwarg);
}
private static IRubyObject receiveSpecificArityRuby2HashKeywords(ThreadContext context, IRubyObject last) {
int callInfo = ThreadContext.resetCallInfo(context);
boolean isKwarg = (callInfo & CALL_KEYWORD) != 0;
// ruby2_keywords only get unmarked if it enters a method which accepts keywords.
// This means methods which don't just keep that marked hash around in case it is passed
// onto another method which accepts keywords.
if (isKwarg) {
// a ruby2_keywords method which happens to receive a keyword. Mark hash as ruby2_keyword
// So it can be used similarly to an ordinary hash passed in this way.
RubyHash hash = (RubyHash) last;
hash = hash.dupFast(context);
hash.setRuby2KeywordHash(true);
return hash;
}
return receiverSpecificArityKwargsCommon(context, last, callInfo, isKwarg);
}
private static IRubyObject receiverSpecificArityKwargsCommon(ThreadContext context, IRubyObject last, int callInfo, boolean isKwarg) {
// ruby2_keywords only get unmarked if it enters a method which accepts keywords.
// This means methods which don't just keep that marked hash around in case it is passed
// onto another method which accepts keywords.
if ((callInfo & CALL_KEYWORD_REST) != 0) {
// This is kwrest passed to a method which does not accept kwargs
// We pass empty kwrest through so kwrest does not try and slurp it up as normal argument.
// This complicates check_arity but empty ** is special case.
RubyHash hash = (RubyHash) last;
return hash;
} else if (!isKwarg) {
// This is just an ordinary hash as last argument
return last;
} else {
RubyHash hash = (RubyHash) last;
return hash.dupFast(context);
}
}
/**
* Simplified receiveKeywords when:
* <li>receiver is not a ruby2_keywords method</li>
* <li>receiver does not accept keywords</li>
* <li>there's no rest argument</li>
*
* @param context
* @param args
* @return the prepared kwargs hash, or UNDEFINED as a sigil for no kwargs
*/
@JIT
public static IRubyObject receiveNormalKeywordsNoRestNoKeywords(ThreadContext context, IRubyObject[] args) {
int callInfo = ThreadContext.resetCallInfo(context);
if (shouldHandleKwargs(args, callInfo) && (callInfo & CALL_SPLATS) != 0) {
return receiveKeywordsWithSplatsNoRestNoKeywords(context, args);
}
return UNDEFINED;
}
/**
* Handle incoming keyword arguments given the receiver's rest arg, keyword acceptance, and need for ruby2_keywords.
*
* We return as undefined and not null when no kwarg since null gets auto-converted to nil because
* temp vars do this to work around no explicit initialization of temp values (e.g. they might start as null).
*
* @param context
* @param args
* @param hasRestArgs
* @param acceptsKeywords
* @param ruby2_keywords_method
* @return
*/
@Interp
public static IRubyObject receiveKeywords(ThreadContext context, IRubyObject[] args, boolean hasRestArgs,
boolean acceptsKeywords, boolean ruby2_keywords_method) {
int callInfo = ThreadContext.resetCallInfo(context);
if (shouldHandleKwargs(args, callInfo)) {
return receiveKeywordsHash(context, args, hasRestArgs, acceptsKeywords, ruby2_keywords_method, callInfo);
}
return UNDEFINED;
}
private static IRubyObject receiveKeywordsWithSplatsNoRestNoKeywords(ThreadContext context, IRubyObject[] args) {
RubyHash hash = (RubyHash) args[args.length - 1];
if (hash.isRuby2KeywordHash()) {
if (hash.isEmpty()) {
// case where we somehow (hash.clear) a marked ruby2_keyword. We pass it as keyword even in non-keyword
// accepting methods so it is subtracted from the arity count. Normally empty keyword arguments are not
// passed along but ruby2_keyword is a strange case since it is mutable by users.
return hash;
}
clearTrailingHashRuby2Keywords(context, args, hash);
}
return UNDEFINED;
}
private static void clearTrailingHashRuby2Keywords(ThreadContext context, IRubyObject[] args, RubyHash hash) {
RubyHash newHash = hash.dupFast(context);
newHash.setRuby2KeywordHash(false);
args[args.length - 1] = newHash;
}
private static boolean shouldHandleKwargs(IRubyObject[] args, int callInfo) {
return (callInfo & CALL_KEYWORD_EMPTY) == 0 && args.length >= 1 && args[args.length - 1] instanceof RubyHash;
}
private static IRubyObject receiveKeywordsHash(ThreadContext context, IRubyObject[] args, boolean hasRestArgs, boolean acceptsKeywords, boolean ruby2_keywords_method, int callInfo) {
RubyHash hash = (RubyHash) args[args.length - 1];
// We record before funging last arg because we may unmark and replace last arg.
boolean ruby2_keywords_hash = hash.isRuby2KeywordHash();
// ruby2_keywords only get unmarked if it enters a method which accepts keywords.
// This means methods which don't just keep that marked hash around in case it is passed
// onto another method which accepts keywords.
if (ruby2_keywords_hash && acceptsKeywords) {
if (!hash.isEmpty()) hash = hash.dupFast(context);
if (!ruby2_keywords_method) hash.setRuby2KeywordHash(false);
return hash;
}
boolean callSplats = (callInfo & CALL_SPLATS) != 0;
boolean callSplatsWithRuby2KeywordsHash = callSplats && ruby2_keywords_hash;
// if we're splatting a ruby2_keywords hash
// AND the hash is non-empty
// AND keywords are accepted OR there's no rest args,
// clear the ruby2_keywords flag from the hash
if (callSplatsWithRuby2KeywordsHash
&& !hash.isEmpty()
&& (acceptsKeywords || !hasRestArgs)) {
clearTrailingHashRuby2Keywords(context, args, hash);
}
boolean callKeyword = (callInfo & CALL_KEYWORD) != 0;
// If method wants ruby2 keywords and call has keywords, convert to ruby2_keywords hash
if (ruby2_keywords_method && callKeyword) {
setTrailingHashRuby2Keywords(context, args, hash);
} else {
// If splat call with ruby2_keywords hash that's not empty, just return it
if (callSplatsWithRuby2KeywordsHash && hash.isEmpty()) {
return hash;
}
// If ordinary hash as last argument, dup and return it
if (callKeyword && acceptsKeywords && !hash.isEmpty()) {
return hash.dupFast(context);
}
}
// All other situations no-op
return UNDEFINED;
}
private static void setTrailingHashRuby2Keywords(ThreadContext context, IRubyObject[] args, RubyHash hash) {
hash = hash.dupFast(context);
hash.setRuby2KeywordHash(true);
args[args.length - 1] = hash;
}
/**
* Methods like Kernel#send if it receives a key-splatted value at a send site (send :foo, **h)
* it will dup h.
*/
public static IRubyObject dupIfKeywordRestAtCallsite(ThreadContext context, IRubyObject arg) {
int callInfo = context.callInfo;
if ((callInfo & CALL_KEYWORD_EMPTY) == 0 && (callInfo & CALL_KEYWORD_REST) != 0) {
arg = arg.dup();
context.callInfo = callInfo;
}
return arg;
}
@JIT @Interp
public static void setCallInfo(ThreadContext context, int flags) {
// FIXME: This may propagate empty more than the current call? empty might need to be stuff elsewhere to prevent this.
context.callInfo = (context.callInfo & CALL_KEYWORD_EMPTY) | flags;
}
public static void checkForExtraUnwantedKeywordArgs(ThreadContext context, final StaticScope scope, RubyHash keywordArgs) {
// we do an inexpensive non-gathering scan first to see if there's a bad keyword
try {
keywordArgs.visitAll(context, CheckUnwantedKeywordsVisitor, scope);
} catch (InvalidKeyException ike) {
// there's a bad keyword; perform more expensive scan to gather all bad names
GatherUnwantedKeywordsVisitor visitor = new GatherUnwantedKeywordsVisitor();
keywordArgs.visitAll(context, visitor, scope);
visitor.raiseIfError(context);
}
}
@JIT
public static DynamicScope prepareScriptScope(ThreadContext context, StaticScope scope) {
IRScope irScope = scope.getIRScope();
if (irScope != null && irScope.isScriptScope() && !irScope.hasFlipFlops()) {
DynamicScope tlbScope = ((IRScriptBody) irScope).getScriptDynamicScope();
if (tlbScope != null) {
context.preScopedBody(tlbScope);
return tlbScope;
}
}
DynamicScope dynScope = DynamicScope.newDynamicScope(scope);
context.pushScope(dynScope);
return dynScope;
}
private static class InvalidKeyException extends RuntimeException {}
private static final InvalidKeyException INVALID_KEY_EXCEPTION = new InvalidKeyException();
private static final RubyHash.VisitorWithState<StaticScope> CheckUnwantedKeywordsVisitor = new RubyHash.VisitorWithState<StaticScope>() {
@Override
public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, StaticScope scope) {
if (!isValidKeyword(scope, key)) throw INVALID_KEY_EXCEPTION;
}
};
private static boolean isValidKeyword(StaticScope scope, IRubyObject key) {
return key instanceof RubySymbol && scope.keywordExists(((RubySymbol) key).idString());
}
private static class GatherUnwantedKeywordsVisitor extends RubyHash.VisitorWithState<StaticScope> {
RubyArray invalidKwargs;
@Override
public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, StaticScope scope) {
if (!isValidKeyword(scope, key)) {
if (invalidKwargs == null) invalidKwargs = context.runtime.newArray();
invalidKwargs.add(key.inspect());
}
}
public void raiseIfError(ThreadContext context) {
if (invalidKwargs != null) {
//System.out.println("RAISEEEEE: " + context.getFile() + ":" + context.getLine());
RubyString errorMessage = (RubyString) invalidKwargs.join(context, context.runtime.newString(", "));
String prefix = invalidKwargs.size() == 1 ? "unknown keyword: " : "unknown keywords: ";
throw context.runtime.newArgumentError(prefix + errorMessage);
}
}
}
public static IRubyObject match3(ThreadContext context, RubyRegexp regexp, IRubyObject argValue) {
if (argValue instanceof RubyString) {
return regexp.op_match(context, argValue);
} else {
return argValue.callMethod(context, "=~", regexp);
}
}
public static IRubyObject extractOptionalArgument(RubyArray rubyArray, int minArgsLength, int index) {
int n = rubyArray.getLength();
return minArgsLength < n ? rubyArray.entry(index) : UNDEFINED;
}
@JIT @Interp
public static IRubyObject isDefinedBackref(ThreadContext context, IRubyObject definedMessage) {
return RubyMatchData.class.isInstance(context.getBackRef()) ?
definedMessage : context.nil;
}
@JIT @Interp
public static IRubyObject isDefinedGlobal(ThreadContext context, String name, IRubyObject definedMessage) {
return context.runtime.getGlobalVariables().isDefined(name) ?
definedMessage : context.nil;
}
// FIXME: This checks for match data differently than isDefinedBackref. Seems like they should use same mechanism?
@JIT @Interp
public static IRubyObject isDefinedNthRef(ThreadContext context, int matchNumber, IRubyObject definedMessage) {
IRubyObject backref = context.getBackRef();
if (backref instanceof RubyMatchData) {
if (!((RubyMatchData) backref).group(matchNumber).isNil()) {
return definedMessage;
}
}
return context.nil;
}
@JIT @Interp
public static IRubyObject isDefinedClassVar(ThreadContext context, RubyModule receiver, String name, IRubyObject definedMessage) {
boolean defined = receiver.isClassVarDefined(name);
if (!defined && receiver.isSingleton()) { // Look for class var in singleton if it is one.
IRubyObject attached = ((MetaClass) receiver).getAttached();
if (attached instanceof RubyModule) defined = ((RubyModule) attached).isClassVarDefined(name);
}
return defined ? definedMessage : context.nil;
}
@JIT @Interp