-
Notifications
You must be signed in to change notification settings - Fork 914
/
RubyClass.java
3102 lines (2628 loc) · 135 KB
/
RubyClass.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: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 2.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/epl-v20.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-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* 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 EPL, 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 EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import static org.jruby.api.Error.*;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.runtime.Visibility.PUBLIC;
import static org.jruby.util.CodegenUtils.ci;
import static org.jruby.util.CodegenUtils.p;
import static org.jruby.util.CodegenUtils.sig;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.types;
import static org.objectweb.asm.Opcodes.ACC_BRIDGE;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACC_SUPER;
import static org.objectweb.asm.Opcodes.ACC_SYNTHETIC;
import static org.objectweb.asm.Opcodes.ACC_VARARGS;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.compiler.impl.SkinnyMethodAdapter;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.java.codegen.MultiClassLoader;
import org.jruby.java.codegen.RealClassGenerator;
import org.jruby.java.codegen.Reified;
import org.jruby.java.proxies.ConcreteJavaProxy;
import org.jruby.java.proxies.JavaProxy;
import org.jruby.javasupport.Java;
import org.jruby.javasupport.Java.JCtorCache;
import org.jruby.javasupport.JavaConstructor;
import org.jruby.javasupport.JavaUtil;
import org.jruby.javasupport.proxy.JavaProxyClass;
import org.jruby.javasupport.proxy.ReifiedJavaProxy;
import org.jruby.javasupport.util.JavaClassConfiguration;
import org.jruby.lexer.yacc.SimpleSourcePosition;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callsite.CacheEntry;
import org.jruby.runtime.callsite.CachingCallSite;
import org.jruby.runtime.callsite.RespondToCallSite;
import org.jruby.runtime.ivars.VariableAccessor;
import org.jruby.runtime.ivars.VariableAccessorField;
import org.jruby.runtime.ivars.VariableTableManager;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.runtime.opto.Invalidator;
import org.jruby.util.ArraySupport;
import org.jruby.util.ClassDefiningClassLoader;
import org.jruby.util.CodegenUtils;
import org.jruby.util.JavaNameMangler;
import org.jruby.util.Loader;
import org.jruby.util.OneShotClassLoader;
import org.jruby.util.StringSupport;
import org.jruby.util.collections.ConcurrentWeakHashMap;
import org.jruby.util.log.Logger;
import org.jruby.util.log.LoggerFactory;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.commons.GeneratorAdapter;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Class", parent="Module")
public class RubyClass extends RubyModule {
private static final Logger LOG = LoggerFactory.getLogger(RubyClass.class);
public static void createClassClass(Ruby runtime, RubyClass classClass) {
classClass.setClassIndex(ClassIndex.CLASS);
classClass.setReifiedClass(RubyClass.class);
classClass.kindOf = new RubyModule.JavaClassKindOf(RubyClass.class);
classClass.undefineMethod("module_function");
classClass.undefineMethod("append_features");
classClass.undefineMethod("prepend_features");
classClass.undefineMethod("extend_object");
classClass.undefineMethod("refine");
classClass.defineAnnotatedMethods(RubyClass.class);
runtime.setBaseNewMethod(classClass.searchMethod("new"));
}
public static final ObjectAllocator CLASS_ALLOCATOR = (runtime, klass) -> {
RubyClass clazz = new RubyClass(runtime);
clazz.allocator = ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR; // Class.allocate object is not allocatable before it is initialized
return clazz;
};
public ObjectAllocator getAllocator() {
return allocator;
}
public void setAllocator(ObjectAllocator allocator) {
this.allocator = allocator;
}
/**
* Set a reflective allocator that calls a no-arg constructor on the given
* class.
*
* @param clazz The class on which to call the default constructor to allocate
*/
@SuppressWarnings("unchecked")
public void setClassAllocator(final Class<?> clazz) {
final Constructor<?> constructor;
try {
constructor = clazz.getConstructor();
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
this.allocator = (runtime, klazz) -> {
try {
RubyBasicObject object = (RubyBasicObject) constructor.newInstance();
object.setMetaClass(klazz);
return object;
} catch (InvocationTargetException e) {
throw newTypeError(runtime, "could not allocate " + clazz + " with default constructor:\n" + e.getTargetException(), e);
} catch (InstantiationException e) {
throw newTypeError(runtime, "could not allocate " + clazz + " with default constructor:\n" + e, e);
} catch (IllegalAccessException e) {
throw runtime.newSecurityError("could not allocate " + clazz + " due to inaccessible default constructor:\n" + e);
}
};
this.reifiedClass = (Class<? extends Reified>) clazz;
}
/**
* Set a reflective allocator that calls the "standard" Ruby object
* constructor (Ruby, RubyClass) on the given class.
*
* @param clazz The class from which to grab a standard Ruby constructor
*/
@SuppressWarnings("unchecked")
public void setRubyClassAllocator(final Class<? extends IRubyObject> clazz) {
final Constructor<? extends IRubyObject> constructor;
try {
constructor = clazz.getConstructor(Ruby.class, RubyClass.class);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
this.allocator = (runtime, klazz) -> {
try {
return constructor.newInstance(runtime, klazz);
} catch (InvocationTargetException e) {
throw newTypeError(runtime, "could not allocate " + clazz + " with (Ruby, RubyClass) constructor:\n" + e.getTargetException(), e);
} catch (InstantiationException e) {
throw newTypeError(runtime, "could not allocate " + clazz + " with (Ruby, RubyClass) constructor:\n" + e, e);
} catch (IllegalAccessException e) {
throw runtime.newSecurityError("could not allocate " + clazz + " due to inaccessible (Ruby, RubyClass) constructor:\n" + e);
}
};
this.reifiedClass = (Class<? extends Reified>) clazz;
}
/**
* Set a reflective allocator that calls the "standard" Ruby object
* constructor (Ruby, RubyClass) on the given class via a static
* __allocate__ method intermediate.
*
* @param clazz The class from which to grab a standard Ruby __allocate__ method.
*
* <p>Note: Used with `jrubyc --java` generated (interoperability) class files.</p>
* <p>Note: Used with new concrete extension.</p>
*/
public void setRubyStaticAllocator(final Class<?> clazz) {
final Method method;
try {
method = clazz.getDeclaredMethod("__allocate__", Ruby.class, RubyClass.class);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
}
this.allocator = (runtime, klazz) -> {
try {
return (IRubyObject) method.invoke(null, runtime, klazz);
} catch (InvocationTargetException e) {
throw newTypeError(runtime, "could not allocate " + clazz + " with (Ruby, RubyClass) method:\n" + e.getTargetException(), e);
} catch (IllegalAccessException e) {
throw runtime.newSecurityError("could not allocate " + clazz + " due to inaccessible (Ruby, RubyClass) method:\n" + e);
}
};
this.reifiedClass = (Class<? extends Reified>) clazz;
}
private static RaiseException newTypeError(final Ruby runtime, final String msg, final Exception e) {
return withException(createTypeError(runtime.getCurrentContext(), msg.toString()), e);
}
@JRubyMethod(name = "allocate")
public IRubyObject allocate() {
if (superClass == null) {
if (this != runtime.getBasicObject()) {
throw typeError(runtime.getCurrentContext(), "can't instantiate uninitialized class");
}
}
IRubyObject obj = allocator.allocate(runtime, this);
if (getMetaClass(obj).getRealClass() != getRealClass()) {
throw typeError(runtime.getCurrentContext(), "wrong instance allocation");
}
return obj;
}
public CallSite getBaseCallSite(int idx) {
return baseCallSites[idx];
}
public CallSite[] getBaseCallSites() {
return baseCallSites;
}
public CallSite[] getExtraCallSites() {
return extraCallSites;
}
public VariableTableManager getVariableTableManager() {
return variableTableManager;
}
public boolean hasObjectID() {
return variableTableManager.hasObjectID();
}
public Map<String, VariableAccessor> getVariableAccessorsForRead() {
return variableTableManager.getVariableAccessorsForRead();
}
public VariableAccessor getVariableAccessorForWrite(String name) {
return variableTableManager.getVariableAccessorForWrite(name);
}
public VariableAccessor getVariableAccessorForRead(String name) {
VariableAccessor accessor = getVariableAccessorsForRead().get(name);
if (accessor == null) accessor = VariableAccessor.DUMMY_ACCESSOR;
return accessor;
}
public VariableAccessor getFFIHandleAccessorForRead() {
return variableTableManager.getFFIHandleAccessorForRead();
}
public VariableAccessor getFFIHandleAccessorForWrite() {
return variableTableManager.getFFIHandleAccessorForWrite();
}
public VariableAccessor getObjectGroupAccessorForRead() {
return variableTableManager.getObjectGroupAccessorForRead();
}
public VariableAccessor getObjectGroupAccessorForWrite() {
return variableTableManager.getObjectGroupAccessorForWrite();
}
public int getVariableTableSize() {
return variableTableManager.getVariableTableSize();
}
public int getVariableTableSizeWithExtras() {
return variableTableManager.getVariableTableSizeWithExtras();
}
/**
* Get an array of all the known instance variable names. The offset into
* the array indicates the offset of the variable's value in the per-object
* variable array.
*
* @return a copy of the array of known instance variable names
*/
public String[] getVariableNames() {
return variableTableManager.getVariableNames();
}
public Map<String, VariableAccessor> getVariableTableCopy() {
return new HashMap<String, VariableAccessor>(getVariableAccessorsForRead());
}
@Override
public ClassIndex getNativeClassIndex() {
return ClassIndex.CLASS;
}
@Override
public boolean isModule() {
return false;
}
@Override
public boolean isClass() {
return true;
}
@Override
public boolean isSingleton() {
return false;
}
/** boot_defclass
* Create an initial Object meta class before Module and Kernel dependencies have
* squirreled themselves together.
*
* @param runtime we need it
* @return a half-baked meta class for object
*/
public static RubyClass createBootstrapClass(Ruby runtime, String name, RubyClass superClass, ObjectAllocator allocator) {
RubyClass obj;
if (superClass == null ) { // boot the Object class
obj = new RubyClass(runtime);
obj.marshal = DEFAULT_OBJECT_MARSHAL;
} else { // boot the Module and Class classes
obj = new RubyClass(runtime, superClass);
}
obj.setAllocator(allocator);
obj.setBaseName(name);
return obj;
}
/** separate path for MetaClass and IncludedModuleWrapper construction
* (rb_class_boot version for MetaClasses)
* no marshal, allocator initialization and addSubclass(this) here!
*/
protected RubyClass(Ruby runtime, RubyClass superClass, boolean objectSpace) {
super(runtime, runtime.getClassClass(), objectSpace);
this.runtime = runtime;
// Since this path is for included wrappers and singletons, use parent
// class's realClass and varTableMgr. If the latter is null, create a
// dummy, since we won't be using it anyway (we're above BasicObject
// so variable requests won't reach us).
if (superClass == null) {
this.realClass = null;
this.variableTableManager = new VariableTableManager(this);
} else {
if ((this.realClass = superClass.realClass) != null) {
this.variableTableManager = realClass.variableTableManager;
} else {
this.variableTableManager = new VariableTableManager(this);
}
}
setSuperClass(superClass); // this is the only case it might be null here (in MetaClass construction)
}
/** used by CLASS_ALLOCATOR (any Class' class will be a Class!)
* also used to bootstrap Object class
*/
protected RubyClass(Ruby runtime) {
super(runtime, runtime.getClassClass());
this.runtime = runtime;
this.realClass = this;
this.variableTableManager = new VariableTableManager(this);
setClassIndex(ClassIndex.CLASS);
}
/** rb_class_boot (for plain Classes)
* also used to bootstrap Module and Class classes
*/
protected RubyClass(Ruby runtime, RubyClass superClazz) {
this(runtime);
setSuperClass(superClazz);
marshal = superClazz.marshal; // use parent's marshal
superClazz.addSubclass(this);
allocator = superClazz.allocator;
}
/**
* A constructor which allows passing in an array of supplementary call sites.
*/
protected RubyClass(Ruby runtime, RubyClass superClazz, CallSite[] extraCallSites) {
this(runtime);
setSuperClass(superClazz);
this.marshal = superClazz.marshal; // use parent's marshal
superClazz.addSubclass(this);
this.extraCallSites = extraCallSites;
}
/**
* Construct a new class with the given name scoped under Object (global)
* and with Object as its immediate superclass.
* Corresponds to rb_class_new in MRI.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass) {
if (superClass == runtime.getClassClass()) typeError(runtime.getCurrentContext(), "can't make subclass of Class");
if (superClass.isSingleton()) typeError(runtime.getCurrentContext(), "can't make subclass of virtual class");
return new RubyClass(runtime, superClass);
}
/**
* A variation on newClass that allow passing in an array of supplementary
* call sites to improve dynamic invocation.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass, CallSite[] extraCallSites) {
if (superClass == runtime.getClassClass()) throw typeError(runtime.getCurrentContext(), "can't make subclass of Class");
if (superClass.isSingleton()) throw typeError(runtime.getCurrentContext(), "can't make subclass of virtual class");
return new RubyClass(runtime, superClass, extraCallSites);
}
/**
* Construct a new class with the given name, allocator, parent class,
* and containing class. If setParent is true, the class's parent will be
* explicitly set to the provided parent (rather than the new class just
* being assigned to a constant in that parent).
* Corresponds to rb_class_new/rb_define_class_id/rb_name_class/rb_set_class_path
* in MRI.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass, String name, ObjectAllocator allocator, RubyModule parent, boolean setParent) {
RubyClass clazz = newClass(runtime, superClass);
clazz.setBaseName(name);
clazz.setAllocator(allocator);
clazz.makeMetaClass(superClass.getMetaClass());
if (setParent) clazz.setParent(parent);
parent.setConstant(name, clazz);
clazz.inherit(superClass);
return clazz;
}
public static RubyClass newClass(Ruby runtime, RubyClass superClass, String name, ObjectAllocator allocator,
RubyModule parent, boolean setParent, String file, int line) {
RubyClass clazz = newClass(runtime, superClass);
clazz.setBaseName(name);
clazz.setAllocator(allocator);
clazz.makeMetaClass(superClass.getMetaClass());
if (setParent) clazz.setParent(parent);
parent.setConstant(name, clazz, file, line);
clazz.inherit(superClass);
return clazz;
}
/**
* A variation on newClass that allows passing in an array of supplementary
* call sites to improve dynamic invocation performance.
*/
public static RubyClass newClass(Ruby runtime, RubyClass superClass, String name, ObjectAllocator allocator, RubyModule parent, boolean setParent, CallSite[] extraCallSites) {
RubyClass clazz = newClass(runtime, superClass, extraCallSites);
clazz.setBaseName(name);
clazz.setAllocator(allocator);
clazz.makeMetaClass(superClass.getMetaClass());
if (setParent) clazz.setParent(parent);
parent.setConstant(name, clazz, BUILTIN_CONSTANT, -1);
clazz.inherit(superClass);
return clazz;
}
/**
* @see #getSingletonClass()
*/
RubyClass toSingletonClass(RubyBasicObject target) {
// replaced after makeMetaClass with MetaClass's toSingletonClass
return target.makeMetaClass(this);
}
static boolean notVisibleAndNotMethodMissing(DynamicMethod method, String name, IRubyObject caller, CallType callType) {
return !method.isCallableFrom(caller, callType) && !name.equals("method_missing");
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name, Block block) {
return finvokeWithRefinements(context, self, null, name, block);
}
public IRubyObject finvokeWithRefinements(ThreadContext context, IRubyObject self, StaticScope staticScope, String name, Block block) {
CacheEntry entry = searchWithRefinements(name, staticScope);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, block);
}
return method.call(context, self, entry.sourceModule, name, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject[] args, Block block) {
return finvokeWithRefinements(context, self, null, name, args, block);
}
public IRubyObject finvokeWithRefinements(ThreadContext context, IRubyObject self, StaticScope staticScope, String name,
IRubyObject[] args, Block block) {
assert args != null;
CacheEntry entry = searchWithRefinements(name, staticScope);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, args, block);
}
return method.call(context, self, entry.sourceModule, name, args, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg, Block block) {
return finvokeWithRefinements(context, self, null, name, arg, block);
}
public IRubyObject finvokeWithRefinements(ThreadContext context, IRubyObject self, StaticScope staticScope, String name,
IRubyObject arg, Block block) {
CacheEntry entry = searchWithRefinements(name, staticScope);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, arg, block);
}
return method.call(context, self, entry.sourceModule, name, arg, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, Block block) {
return finvokeWithRefinements(context, self, null, name, arg0, arg1, block);
}
public IRubyObject finvokeWithRefinements(ThreadContext context, IRubyObject self, StaticScope staticScope, String name,
IRubyObject arg0, IRubyObject arg1, Block block) {
CacheEntry entry = searchWithRefinements(name, staticScope);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, arg0, arg1, block);
}
return method.call(context, self, entry.sourceModule, name, arg0, arg1, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
return finvokeWithRefinements(context, self, null, name, arg0, arg1, arg2, block);
}
public IRubyObject finvokeWithRefinements(ThreadContext context, IRubyObject self, StaticScope staticScope, String name,
IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
CacheEntry entry = searchWithRefinements(name, staticScope);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, arg0, arg1, arg2, block);
}
return method.call(context, self, entry.sourceModule, name, arg0, arg1, arg2, block);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name) {
CacheEntry entry = searchWithCache(name);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, entry.sourceModule, name);
}
/**
* MRI: rb_funcallv_public
*/
public IRubyObject invokePublic(ThreadContext context, IRubyObject self, String name, IRubyObject arg) {
CacheEntry entry = searchWithCache(name);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method) || method.getVisibility() != PUBLIC) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, arg, Block.NULL_BLOCK);
}
return method.call(context, self, entry.sourceModule, name, arg);
}
/**
* Safely attempt to invoke the given method name on self, using respond_to? and method_missing as appropriate.
*
* MRI: rb_check_funcall
*/
public final IRubyObject finvokeChecked(ThreadContext context, IRubyObject self, String name) {
return checkFuncallDefault(context, self, name, IRubyObject.NULL_ARRAY);
}
/**
* Safely attempt to invoke the given method name on self, using respond_to? and method_missing as appropriate.
*
* MRI: rb_check_funcall
*/
public final IRubyObject finvokeChecked(ThreadContext context, IRubyObject self, JavaSites.CheckedSites sites) {
return checkFuncallDefault(context, self, sites);
}
/**
* Safely attempt to invoke the given method name on self, using respond_to? and method_missing as appropriate.
*
* MRI: rb_check_funcall
*/
public final IRubyObject finvokeChecked(ThreadContext context, IRubyObject self, String name, IRubyObject... args) {
return checkFuncallDefault(context, self, name, args);
}
/**
* Safely attempt to invoke the given method name on self, using respond_to? and method_missing as appropriate.
*
* MRI: rb_check_funcall
*/
public final IRubyObject finvokeChecked(ThreadContext context, IRubyObject self, JavaSites.CheckedSites sites, IRubyObject... args) {
return checkFuncallDefault(context, self, sites, args);
}
// MRI: rb_check_funcall_default
private IRubyObject checkFuncallDefault(ThreadContext context, IRubyObject self, String name, IRubyObject[] args) {
final RubyClass klass = this;
if (!checkFuncallRespondTo(context, klass, self, name)) return null; // return def;
DynamicMethod method = searchMethod(name);
if (!checkFuncallCallable(context, method, CallType.FUNCTIONAL, self)) {
return checkFuncallMissing(context, klass, self, name, args);
}
return method.call(context, self, klass, name, args);
}
// MRI: rb_check_funcall_default
private IRubyObject checkFuncallDefault(ThreadContext context, IRubyObject self, JavaSites.CheckedSites sites, IRubyObject[] args) {
final RubyClass klass = this;
if (!checkFuncallRespondTo(context, klass, self, sites.respond_to_X)) return null; // return def;
CacheEntry entry = sites.site.retrieveCache(klass);
DynamicMethod method = entry.method;
if (!checkFuncallCallable(context, method, CallType.FUNCTIONAL, self)) {
return checkFuncallMissing(context, klass, self, sites.methodName, sites.respond_to_missing, sites.method_missing, args);
}
return method.call(context, self, entry.sourceModule, sites.methodName, args);
}
// MRI: rb_check_funcall_default
private IRubyObject checkFuncallDefault(ThreadContext context, IRubyObject self, JavaSites.CheckedSites sites) {
final RubyClass klass = this;
if (!checkFuncallRespondTo(context, klass, self, sites.respond_to_X)) return null; // return def;
CacheEntry entry = sites.site.retrieveCache(klass);
DynamicMethod method = entry.method;
if (!checkFuncallCallable(context, method, CallType.FUNCTIONAL, self)) {
return checkFuncallMissing(context, klass, self, sites.methodName, sites.respond_to_missing, sites.method_missing);
}
return method.call(context, self, entry.sourceModule, sites.methodName);
}
// MRI: check_funcall_exec
private static IRubyObject checkFuncallExec(ThreadContext context, IRubyObject self, String name, IRubyObject... args) {
return self.callMethod(context, "method_missing", ArraySupport.newCopy(context.runtime.newSymbol(name), args));
}
// MRI: check_funcall_exec
private static IRubyObject checkFuncallExec(ThreadContext context, IRubyObject self, String name, CallSite methodMissingSite, IRubyObject... args) {
return methodMissingSite.call(context, self, self, ArraySupport.newCopy(context.runtime.newSymbol(name), args));
}
// MRI: check_funcall_failed
private static IRubyObject checkFuncallFailed(ThreadContext context, IRubyObject self, String name, RubyClass expClass, IRubyObject... args) {
if (self.respondsTo(name)) {
throw context.runtime.newRaiseException(expClass, name);
}
return null;
}
/**
* Check if the method has a custom respond_to? and call it if so with the method ID we're hoping to call.
*
* MRI: check_funcall_respond_to
*/
private static boolean checkFuncallRespondTo(ThreadContext context, RubyClass klass, IRubyObject recv, String mid) {
CacheEntry entry = klass.searchWithCache("respond_to?");
DynamicMethod me = entry.method;
// NOTE: isBuiltin here would be NOEX_BASIC in MRI, a flag only added to respond_to?, method_missing, and
// respond_to_missing? Same effect, I believe.
if (me == null || me.isUndefined() || me.isBuiltin()) return true;
return me.callRespondTo(context, recv, "respond_to?", entry.sourceModule, context.runtime.newSymbol(mid));
}
/**
* Check if the method has a custom respond_to? and call it if so with the method ID we're hoping to call.
*
* MRI: check_funcall_respond_to
*/
private static boolean checkFuncallRespondTo(ThreadContext context, RubyClass klass, IRubyObject recv, RespondToCallSite respondToSite) {
final Ruby runtime = context.runtime;
DynamicMethod me = respondToSite.retrieveCache(klass).method;
// NOTE: isBuiltin here would be NOEX_BASIC in MRI, a flag only added to respond_to?, method_missing, and
// respond_to_missing? Same effect, I believe.
if (me.isUndefined() || me.isBuiltin()) return true;
int required = me.getSignature().required();
if (required > 2) throw runtime.newArgumentError("respond_to? must accept 1 or 2 arguments (requires " + required + ")");
if (required == 1) {
return respondToSite.respondsTo(context, recv, recv);
} else {
return respondToSite.respondsTo(context, recv, recv, true);
}
}
// MRI: check_funcall_callable
static boolean checkFuncallCallable(ThreadContext context, DynamicMethod method, CallType callType, IRubyObject self) {
return rbMethodCallStatus(context, method, callType, self);
}
// MRI: rb_method_call_status
// FIXME: Partial impl because we don't have these "NOEX" flags
private static boolean rbMethodCallStatus(ThreadContext context, DynamicMethod method, CallType callType, IRubyObject self) {
return !method.isUndefined() && method.isCallableFrom(self, callType);
}
// MRI: check_funcall_missing
private static IRubyObject checkFuncallMissing(ThreadContext context, RubyClass klass, IRubyObject self, String method, IRubyObject... args) {
final Ruby runtime = context.runtime;
CacheEntry entry = klass.searchWithCache("respond_to_missing?");
DynamicMethod me = entry.method;
// MRI: basic_obj_respond_to_missing ...
if (!me.isUndefined() && !me.isBuiltin() && !me.callRespondTo(context, self, "respond_to_missing?", entry.sourceModule, runtime.newSymbol(method))) {
return null;
}
if ( klass.isMethodBuiltin("method_missing") ) return null;
final IRubyObject $ex = context.getErrorInfo();
try {
return checkFuncallExec(context, self, method, args);
} catch (RaiseException e) {
context.setErrorInfo($ex); // restore $!
return checkFuncallFailed(context, self, method, runtime.getNoMethodError(), args);
}
}
// MRI: check_funcall_missing
private static IRubyObject checkFuncallMissing(ThreadContext context, RubyClass klass, IRubyObject self, String method, CachingCallSite respondToMissingSite, CachingCallSite methodMissingSite, IRubyObject... args) {
final Ruby runtime = context.runtime;
CacheEntry entry = respondToMissingSite.retrieveCache(klass);
DynamicMethod me = entry.method;
// MRI: basic_obj_respond_to_missing ...
if (!me.isUndefined() && !me.isBuiltin() && !me.callRespondTo(context, self, "respond_to_missing?", entry.sourceModule, runtime.newSymbol(method))) {
return null;
}
if (methodMissingSite.retrieveCache(klass).method.isBuiltin()) return null;
final IRubyObject $ex = context.getErrorInfo();
try {
return checkFuncallExec(context, self, method, methodMissingSite, args);
}
catch (RaiseException e) {
context.setErrorInfo($ex); // restore $!
return checkFuncallFailed(context, self, method, runtime.getNoMethodError(), args);
}
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject[] args) {
assert args != null;
CacheEntry entry = searchWithCache(name);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, args, Block.NULL_BLOCK);
}
return method.call(context, self, entry.sourceModule, name, args);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg) {
CacheEntry entry = searchWithCache(name);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, arg, Block.NULL_BLOCK);
}
return method.call(context, self, entry.sourceModule, name, arg);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1) {
CacheEntry entry = searchWithCache(name);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, arg0, arg1, Block.NULL_BLOCK);
}
return method.call(context, self, entry.sourceModule, name, arg0, arg1);
}
public IRubyObject finvoke(ThreadContext context, IRubyObject self, String name,
IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
CacheEntry entry = searchWithCache(name);
DynamicMethod method = entry.method;
if (shouldCallMethodMissing(method)) {
return Helpers.callMethodMissing(context, self, this, method.getVisibility(), name, CallType.FUNCTIONAL, arg0, arg1, arg2, Block.NULL_BLOCK);
}
return method.call(context, self, entry.sourceModule, name, arg0, arg1, arg2);
}
// MRI: rb_method_basic_definition_p
public boolean checkMethodBasicDefinition(String name) {
DynamicMethod method = searchMethod(name);
return method != null && method.isBuiltin();
}
private void dumpReifiedClass(String dumpDir, String javaPath, byte[] classBytes) {
if (dumpDir != null) {
if (dumpDir.length() == 0) dumpDir = ".";
java.io.FileOutputStream classStream = null;
try {
java.io.File classFile = new java.io.File(dumpDir, javaPath + ".class");
classFile.getParentFile().mkdirs();
classStream = new java.io.FileOutputStream(classFile);
classStream.write(classBytes);
}
catch (IOException io) {
runtime.getWarnings().warn("unable to dump class file: " + io.getMessage());
}
finally {
if (classStream != null) {
try { classStream.close(); }
catch (IOException ignored) { /* no-op */ }
}
}
}
}
private void generateMethodAnnotations(Map<Class<?>, Map<String, Object>> methodAnnos, SkinnyMethodAdapter m, List<Map<Class<?>, Map<String, Object>>> parameterAnnos) {
if (methodAnnos != null && methodAnnos.size() != 0) {
for (Map.Entry<Class<?>, Map<String, Object>> entry : methodAnnos.entrySet()) {
m.visitAnnotationWithFields(ci(entry.getKey()), true, entry.getValue());
}
}
if (parameterAnnos != null && parameterAnnos.size() != 0) {
for (int i = 0; i < parameterAnnos.size(); i++) {
Map<Class<?>, Map<String, Object>> annos = parameterAnnos.get(i);
if (annos != null && annos.size() != 0) {
for (Iterator<Map.Entry<Class<?>, Map<String, Object>>> it = annos.entrySet().iterator(); it.hasNext();) {
Map.Entry<Class<?>, Map<String, Object>> entry = it.next();
m.visitParameterAnnotationWithFields(i, ci(entry.getKey()), true, entry.getValue());
}
}
}
}
}
private static boolean shouldCallMethodMissing(DynamicMethod method) {
return method.isUndefined();
}
private static boolean shouldCallMethodMissing(DynamicMethod method, String name, IRubyObject caller, CallType callType) {
return method.isUndefined() || notVisibleAndNotMethodMissing(method, name, caller, callType);
}
public IRubyObject invokeInherited(ThreadContext context, IRubyObject self, IRubyObject subclass) {
CacheEntry entry = metaClass.searchWithCache("inherited");
DynamicMethod method = entry.method;
if (method.isUndefined()) {
return Helpers.callMethodMissing(context, self, method.getVisibility(), "inherited", CallType.FUNCTIONAL, Block.NULL_BLOCK);
}
return method.call(context, self, entry.sourceModule, "inherited", subclass, Block.NULL_BLOCK);
}
/** rb_class_new_instance
*
*/
@JRubyMethod(name = "new", keywords = true)
public IRubyObject newInstance(ThreadContext context, Block block) {
IRubyObject obj = allocate();
baseCallSites[CS_IDX_INITIALIZE].call(context, obj, obj, block);
return obj;
}
@JRubyMethod(name = "new", keywords = true)
public IRubyObject newInstance(ThreadContext context, IRubyObject arg0, Block block) {
IRubyObject obj = allocate();
baseCallSites[CS_IDX_INITIALIZE].call(context, obj, obj, arg0, block);
return obj;
}
public IRubyObject newInstance(ThreadContext context, IRubyObject arg0) {
IRubyObject obj = allocate();
baseCallSites[CS_IDX_INITIALIZE].call(context, obj, obj, arg0);
return obj;
}
@JRubyMethod(name = "new", keywords = true)
public IRubyObject newInstance(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
IRubyObject obj = allocate();
baseCallSites[CS_IDX_INITIALIZE].call(context, obj, obj, arg0, arg1, block);
return obj;
}
@JRubyMethod(name = "new", keywords = true)
public IRubyObject newInstance(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) {
IRubyObject obj = allocate();
baseCallSites[CS_IDX_INITIALIZE].call(context, obj, obj, arg0, arg1, arg2, block);
return obj;
}
@JRubyMethod(name = "new", rest = true, keywords = true)
public IRubyObject newInstance(ThreadContext context, IRubyObject[] args, Block block) {
IRubyObject obj = allocate();
baseCallSites[CS_IDX_INITIALIZE].call(context, obj, obj, args, block);
return obj;
}
/** rb_class_initialize
*
*/
@Override
@JRubyMethod(name = "initialize", visibility = PRIVATE)
public IRubyObject initialize(ThreadContext context, Block block) {
checkNotInitialized();
return initializeCommon(context, runtime.getObject(), block);
}
@JRubyMethod(name = "initialize", visibility = PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject superObject, Block block) {
checkNotInitialized();
checkInheritable(context, superObject);
return initializeCommon(context, (RubyClass) superObject, block);
}
private RubyClass initializeCommon(ThreadContext context, RubyClass superClazz, Block block) {
setSuperClass(superClazz);
allocator = superClazz.allocator;
makeMetaClass(superClazz.getMetaClass());
marshal = superClazz.marshal;
superClazz.addSubclass(this);
inherit(superClazz);
super.initialize(context, block);
return this;
}
/** rb_class_init_copy
*
*/
@JRubyMethod(name = "initialize_copy", visibility = PRIVATE)
@Override
public IRubyObject initialize_copy(IRubyObject original) {
checkNotInitialized();
if (original instanceof MetaClass) throw typeError(runtime.getCurrentContext(), "can't copy singleton class");
super.initialize_copy(original);
RubyClass originalClazz = (RubyClass) original;
allocator = originalClazz.allocator;
// copy over reify options
javaClassConfiguration = originalClazz.javaClassConfiguration == null ? null : originalClazz.javaClassConfiguration.clone();
// copy over reified class if applicable
if (originalClazz.getJavaProxy() && originalClazz.reifiedClass != null &&