forked from jruby/jruby
/
RubyModule.java
3284 lines (2742 loc) · 120 KB
/
RubyModule.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-2007 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 William N Dortch <bill.dortch@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 clojure.lang.APersistentMap;
import clojure.lang.IPersistentMap;
import clojure.lang.LockingTransaction;
import clojure.lang.PersistentHashMap;
import clojure.lang.Ref;
import static org.jruby.anno.FrameField.VISIBILITY;
import static org.jruby.runtime.Visibility.MODULE_FUNCTION;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.runtime.Visibility.PROTECTED;
import static org.jruby.runtime.Visibility.PUBLIC;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyConstant;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JavaMethodDescriptor;
import org.jruby.anno.TypePopulator;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.compiler.ASTInspector;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.methods.AliasMethod;
import org.jruby.internal.runtime.methods.CallConfiguration;
import org.jruby.internal.runtime.methods.DefaultMethod;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.internal.runtime.methods.FullFunctionCallbackMethod;
import org.jruby.internal.runtime.methods.JavaMethod.JavaMethodOne;
import org.jruby.internal.runtime.methods.JavaMethod.JavaMethodZero;
import org.jruby.internal.runtime.methods.MethodMethod;
import org.jruby.internal.runtime.methods.ProcMethod;
import org.jruby.internal.runtime.methods.SimpleCallbackMethod;
import org.jruby.internal.runtime.methods.SynchronizedDynamicMethod;
import org.jruby.internal.runtime.methods.UndefinedMethod;
import org.jruby.internal.runtime.methods.WrapperMethod;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodFactory;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.callback.Callback;
import org.jruby.runtime.callsite.CacheEntry;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ClassProvider;
import org.jruby.util.IdUtil;
import org.jruby.util.collections.WeakHashSet;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Module")
public class RubyModule extends RubyObject {
private static final boolean DEBUG = false;
protected static final String ERR_INSECURE_SET_CONSTANT = "Insecure: can't modify constant";
protected static final String ERR_FROZEN_CONST_TYPE = "class/module ";
public static final Set<String> SCOPE_CAPTURING_METHODS = new HashSet<String>(Arrays.asList(
"eval",
"module_eval",
"class_eval",
"instance_eval",
"instance_exec",
"binding",
"local_variables"
));
public static final ObjectAllocator MODULE_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyModule(runtime, klass);
}
};
public static RubyClass createModuleClass(Ruby runtime, RubyClass moduleClass) {
moduleClass.index = ClassIndex.MODULE;
moduleClass.setReifiedClass(RubyModule.class);
moduleClass.kindOf = new RubyModule.KindOf() {
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyModule;
}
};
moduleClass.defineAnnotatedMethods(RubyModule.class);
moduleClass.defineAnnotatedMethods(ModuleKernelMethods.class);
return moduleClass;
}
public static class ModuleKernelMethods {
@JRubyMethod
public static IRubyObject autoload(IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return RubyKernel.autoload(recv, arg0, arg1);
}
@JRubyMethod(name = "autoload?")
public static IRubyObject autoload_p(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
return RubyKernel.autoload_p(context, recv, arg0);
}
}
@Override
public int getNativeTypeIndex() {
return ClassIndex.MODULE;
}
@Override
public boolean isModule() {
return true;
}
@Override
public boolean isClass() {
return false;
}
public boolean isSingleton() {
return false;
}
public static class KindOf {
public static final KindOf DEFAULT_KIND_OF = new KindOf();
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj.getMetaClass().hasModuleInHierarchy(type);
}
}
public boolean isInstance(IRubyObject object) {
return kindOf.isKindOf(object, this);
}
public Map<String, IRubyObject> getConstantMap() {
return (Map<String, IRubyObject>)constants.deref();
}
public IPersistentMap getPersistentConstants() {
return (IPersistentMap)constants.deref();
}
public synchronized Map<String, IRubyObject> getConstantMapForWrite() {
return (Map<String, IRubyObject>)constants.deref();
}
public void addIncludingHierarchy(IncludedModuleWrapper hierarchy) {
synchronized (getRuntime().getHierarchyLock()) {
Set<RubyClass> oldIncludingHierarchies = includingHierarchies;
if (oldIncludingHierarchies == Collections.EMPTY_SET) includingHierarchies = oldIncludingHierarchies = new WeakHashSet(4);
oldIncludingHierarchies.add(hierarchy);
}
}
/** separate path for MetaClass construction
*
*/
protected RubyModule(Ruby runtime, RubyClass metaClass, boolean objectSpace) {
super(runtime, metaClass, objectSpace);
id = runtime.allocModuleId();
runtime.addModule(this);
// if (parent == null) parent = runtime.getObject();
setFlag(USER7_F, !isClass());
generation = runtime.getNextModuleGeneration();
try {
constants = new Ref(PersistentHashMap.EMPTY);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** used by MODULE_ALLOCATOR and RubyClass constructors
*
*/
protected RubyModule(Ruby runtime, RubyClass metaClass) {
this(runtime, metaClass, runtime.isObjectSpaceEnabled());
}
/** standard path for Module construction
*
*/
protected RubyModule(Ruby runtime) {
this(runtime, runtime.getModule());
}
public boolean needsImplementer() {
return getFlag(USER7_F);
}
/** rb_module_new
*
*/
public static RubyModule newModule(Ruby runtime) {
return new RubyModule(runtime);
}
/** rb_module_new/rb_define_module_id/rb_name_class/rb_set_class_path
*
*/
public static RubyModule newModule(Ruby runtime, String name, RubyModule parent, boolean setParent) {
RubyModule module = newModule(runtime);
module.setBaseName(name);
if (setParent) module.setParent(parent);
parent.setConstant(name, module);
return module;
}
// synchronized method per JRUBY-1173 (unsafe Double-Checked Locking)
// FIXME: synchronization is still wrong in CP code
public synchronized void addClassProvider(ClassProvider provider) {
if (!classProviders.contains(provider)) {
Set<ClassProvider> cp = new HashSet<ClassProvider>(classProviders);
cp.add(provider);
classProviders = cp;
}
}
public synchronized void removeClassProvider(ClassProvider provider) {
Set<ClassProvider> cp = new HashSet<ClassProvider>(classProviders);
cp.remove(provider);
classProviders = cp;
}
private void checkForCyclicInclude(RubyModule m) throws RaiseException {
if (getNonIncludedClass() == m.getNonIncludedClass()) {
throw getRuntime().newArgumentError("cyclic include detected");
}
}
private RubyClass searchProvidersForClass(String name, RubyClass superClazz) {
RubyClass clazz;
for (ClassProvider classProvider: classProviders) {
if ((clazz = classProvider.defineClassUnder(this, name, superClazz)) != null) {
return clazz;
}
}
return null;
}
private RubyModule searchProvidersForModule(String name) {
RubyModule module;
for (ClassProvider classProvider: classProviders) {
if ((module = classProvider.defineModuleUnder(this, name)) != null) {
return module;
}
}
return null;
}
/** Getter for property superClass.
* @return Value of property superClass.
*/
public RubyClass getSuperClass() {
return superClass;
}
protected void setSuperClass(RubyClass superClass) {
// update superclass reference
this.superClass = superClass;
if (superClass != null && superClass.isSynchronized()) becomeSynchronized();
}
public RubyModule getParent() {
return parent;
}
public void setParent(RubyModule parent) {
this.parent = parent;
}
public Map<String, DynamicMethod> getMethods() {
return this.methods;
}
public synchronized Map<String, DynamicMethod> getMethodsForWrite() {
Map<String, DynamicMethod> myMethods = this.methods;
return myMethods == Collections.EMPTY_MAP ?
this.methods = new ConcurrentHashMap<String, DynamicMethod>(0, 0.9f, 1) :
myMethods;
}
// note that addMethod now does its own put, so any change made to
// functionality here should be made there as well
private void putMethod(String name, DynamicMethod method) {
getMethodsForWrite().put(name, method);
}
/**
* Is this module one that in an included one (e.g. an IncludedModuleWrapper).
*/
public boolean isIncluded() {
return false;
}
public RubyModule getNonIncludedClass() {
return this;
}
public String getBaseName() {
return classId;
}
public void setBaseName(String name) {
classId = name;
}
/**
* Generate a fully-qualified class name or a #-style name for anonymous and singleton classes.
*
* Ruby C equivalent = "classname"
*
* @return The generated class name
*/
public String getName() {
if (fullName == null) {
calculateName();
}
return fullName;
}
private void calculateName() {
fullName = calculateFullName();
}
private String calculateFullName() {
if (getBaseName() == null) {
if (bareName == null) {
if (isClass()) {
bareName = "#<" + "Class" + ":0x1" + String.format("%08x", System.identityHashCode(this)) + ">";
} else {
bareName = "#<" + "Module" + ":0x1" + String.format("%08x", System.identityHashCode(this)) + ">";
}
}
return bareName;
}
String result = getBaseName();
RubyClass objectClass = getRuntime().getObject();
for (RubyModule p = this.getParent(); p != null && p != objectClass; p = p.getParent()) {
String pName = p.getBaseName();
// This is needed when the enclosing class or module is a singleton.
// In that case, we generated a name such as null::Foo, which broke
// Marshalling, among others. The correct thing to do in this situation
// is to insert the generate the name of form #<Class:01xasdfasd> if
// it's a singleton module/class, which this code accomplishes.
if(pName == null) {
pName = p.getName();
}
result = pName + "::" + result;
}
return result;
}
/**
* Create a wrapper to use for including the specified module into this one.
*
* Ruby C equivalent = "include_class_new"
*
* @return The module wrapper
*/
@Deprecated
public IncludedModuleWrapper newIncludeClass(RubyClass superClazz) {
IncludedModuleWrapper includedModule = new IncludedModuleWrapper(getRuntime(), superClazz, this);
// include its parent (and in turn that module's parents)
if (getSuperClass() != null) {
includedModule.includeModule(getSuperClass());
}
return includedModule;
}
/**
* Finds a class that is within the current module (or class).
*
* @param name to be found in this module (or class)
* @return the class or null if no such class
*/
public RubyClass getClass(String name) {
IRubyObject module;
if ((module = getConstantAt(name)) instanceof RubyClass) {
return (RubyClass)module;
}
return null;
}
public RubyClass fastGetClass(String internedName) {
IRubyObject module;
if ((module = fastGetConstantAt(internedName)) instanceof RubyClass) {
return (RubyClass)module;
}
return null;
}
/**
* Include a new module in this module or class.
*
* @param arg The module to include
*/
public synchronized void includeModule(IRubyObject arg) {
assert arg != null;
testFrozen("module");
if (!isTaint()) {
getRuntime().secure(4);
}
if (!(arg instanceof RubyModule)) {
throw getRuntime().newTypeError("Wrong argument type " + arg.getMetaClass().getName() +
" (expected Module).");
}
RubyModule module = (RubyModule) arg;
// Make sure the module we include does not already exist
checkForCyclicInclude(module);
infectBy(module);
doIncludeModule(module);
invalidateConstantCache();
invalidateCacheDescendants();
}
public void defineMethod(String name, Callback method) {
Visibility visibility = name.equals("initialize") ?
PRIVATE : PUBLIC;
addMethod(name, new FullFunctionCallbackMethod(this, method, visibility));
}
public void defineAnnotatedMethod(Class clazz, String name) {
// FIXME: This is probably not very efficient, since it loads all methods for each call
boolean foundMethod = false;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals(name) && defineAnnotatedMethod(method, MethodFactory.createFactory(getRuntime().getJRubyClassLoader()))) {
foundMethod = true;
}
}
if (!foundMethod) {
throw new RuntimeException("No JRubyMethod present for method " + name + "on class " + clazz.getName());
}
}
public void defineAnnotatedConstants(Class clazz) {
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if (Modifier.isStatic(field.getModifiers())) {
defineAnnotatedConstant(field);
}
}
}
public boolean defineAnnotatedConstant(Field field) {
JRubyConstant jrubyConstant = field.getAnnotation(JRubyConstant.class);
if (jrubyConstant == null) return false;
String[] names = jrubyConstant.value();
if(names.length == 0) {
names = new String[]{field.getName()};
}
Class tp = field.getType();
IRubyObject realVal;
try {
if(tp == Integer.class || tp == Integer.TYPE || tp == Short.class || tp == Short.TYPE || tp == Byte.class || tp == Byte.TYPE) {
realVal = RubyNumeric.int2fix(getRuntime(), field.getInt(null));
} else if(tp == Boolean.class || tp == Boolean.TYPE) {
realVal = field.getBoolean(null) ? getRuntime().getTrue() : getRuntime().getFalse();
} else {
realVal = getRuntime().getNil();
}
} catch(Exception e) {
realVal = getRuntime().getNil();
}
for(String name : names) {
this.fastSetConstant(name, realVal);
}
return true;
}
public void defineAnnotatedMethods(Class clazz) {
defineAnnotatedMethodsIndividually(clazz);
}
public static class MethodClumper {
Map<String, List<JavaMethodDescriptor>> annotatedMethods = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> staticAnnotatedMethods = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> annotatedMethods1_8 = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> staticAnnotatedMethods1_8 = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> annotatedMethods1_9 = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> staticAnnotatedMethods1_9 = new HashMap<String, List<JavaMethodDescriptor>>();
Map<String, List<JavaMethodDescriptor>> allAnnotatedMethods = new HashMap<String, List<JavaMethodDescriptor>>();
public void clump(Class cls) {
Method[] declaredMethods = cls.getDeclaredMethods();
for (Method method: declaredMethods) {
JRubyMethod anno = method.getAnnotation(JRubyMethod.class);
if (anno == null) continue;
JavaMethodDescriptor desc = new JavaMethodDescriptor(method);
String name = anno.name().length == 0 ? method.getName() : anno.name()[0];
List<JavaMethodDescriptor> methodDescs;
Map<String, List<JavaMethodDescriptor>> methodsHash = null;
if (desc.isStatic) {
if (anno.compat() == CompatVersion.RUBY1_8) {
methodsHash = staticAnnotatedMethods1_8;
} else if (anno.compat() == CompatVersion.RUBY1_9) {
methodsHash = staticAnnotatedMethods1_9;
} else {
methodsHash = staticAnnotatedMethods;
}
} else {
if (anno.compat() == CompatVersion.RUBY1_8) {
methodsHash = annotatedMethods1_8;
} else if (anno.compat() == CompatVersion.RUBY1_9) {
methodsHash = annotatedMethods1_9;
} else {
methodsHash = annotatedMethods;
}
}
// add to specific
methodDescs = methodsHash.get(name);
if (methodDescs == null) {
methodDescs = new ArrayList<JavaMethodDescriptor>();
methodsHash.put(name, methodDescs);
}
methodDescs.add(desc);
// add to general
methodDescs = allAnnotatedMethods.get(name);
if (methodDescs == null) {
methodDescs = new ArrayList<JavaMethodDescriptor>();
allAnnotatedMethods.put(name, methodDescs);
}
methodDescs.add(desc);
}
}
public Map<String, List<JavaMethodDescriptor>> getAllAnnotatedMethods() {
return allAnnotatedMethods;
}
public Map<String, List<JavaMethodDescriptor>> getAnnotatedMethods() {
return annotatedMethods;
}
public Map<String, List<JavaMethodDescriptor>> getAnnotatedMethods1_8() {
return annotatedMethods1_8;
}
public Map<String, List<JavaMethodDescriptor>> getAnnotatedMethods1_9() {
return annotatedMethods1_9;
}
public Map<String, List<JavaMethodDescriptor>> getStaticAnnotatedMethods() {
return staticAnnotatedMethods;
}
public Map<String, List<JavaMethodDescriptor>> getStaticAnnotatedMethods1_8() {
return staticAnnotatedMethods1_8;
}
public Map<String, List<JavaMethodDescriptor>> getStaticAnnotatedMethods1_9() {
return staticAnnotatedMethods1_9;
}
}
public void defineAnnotatedMethodsIndividually(Class clazz) {
TypePopulator populator;
if (RubyInstanceConfig.FULL_TRACE_ENABLED || RubyInstanceConfig.REFLECTED_HANDLES) {
// we want reflected invokers or need full traces, use default (slow) populator
if (DEBUG) System.out.println("trace mode, using default populator");
populator = TypePopulator.DEFAULT;
} else {
try {
String qualifiedName = "org.jruby.gen." + clazz.getCanonicalName().replace('.', '$');
if (DEBUG) System.out.println("looking for " + qualifiedName + "$Populator");
Class populatorClass = Class.forName(qualifiedName + "$Populator");
populator = (TypePopulator)populatorClass.newInstance();
} catch (Throwable t) {
if (DEBUG) System.out.println("Could not find it, using default populator");
populator = TypePopulator.DEFAULT;
}
}
populator.populate(this, clazz);
}
public boolean defineAnnotatedMethod(String name, List<JavaMethodDescriptor> methods, MethodFactory methodFactory) {
JavaMethodDescriptor desc = methods.get(0);
if (methods.size() == 1) {
return defineAnnotatedMethod(desc, methodFactory);
} else {
DynamicMethod dynamicMethod = methodFactory.getAnnotatedMethod(this, methods);
define(this, desc, dynamicMethod);
return true;
}
}
public boolean defineAnnotatedMethod(Method method, MethodFactory methodFactory) {
JRubyMethod jrubyMethod = method.getAnnotation(JRubyMethod.class);
if (jrubyMethod == null) return false;
if(jrubyMethod.compat() == CompatVersion.BOTH ||
getRuntime().getInstanceConfig().getCompatVersion() == jrubyMethod.compat()) {
JavaMethodDescriptor desc = new JavaMethodDescriptor(method);
DynamicMethod dynamicMethod = methodFactory.getAnnotatedMethod(this, desc);
define(this, desc, dynamicMethod);
return true;
}
return false;
}
public boolean defineAnnotatedMethod(JavaMethodDescriptor desc, MethodFactory methodFactory) {
JRubyMethod jrubyMethod = desc.anno;
if (jrubyMethod == null) return false;
if(jrubyMethod.compat() == CompatVersion.BOTH ||
getRuntime().getInstanceConfig().getCompatVersion() == jrubyMethod.compat()) {
DynamicMethod dynamicMethod = methodFactory.getAnnotatedMethod(this, desc);
define(this, desc, dynamicMethod);
return true;
}
return false;
}
public void defineFastMethod(String name, Callback method) {
Visibility visibility = name.equals("initialize") ?
PRIVATE : PUBLIC;
addMethod(name, new SimpleCallbackMethod(this, method, visibility));
}
public void defineFastMethod(String name, Callback method, Visibility visibility) {
addMethod(name, new SimpleCallbackMethod(this, method, visibility));
}
public void definePrivateMethod(String name, Callback method) {
addMethod(name, new FullFunctionCallbackMethod(this, method, PRIVATE));
}
public void defineFastPrivateMethod(String name, Callback method) {
addMethod(name, new SimpleCallbackMethod(this, method, PRIVATE));
}
public void defineFastProtectedMethod(String name, Callback method) {
addMethod(name, new SimpleCallbackMethod(this, method, PROTECTED));
}
public void undefineMethod(String name) {
addMethod(name, UndefinedMethod.getInstance());
}
/** rb_undef
*
*/
public void undef(ThreadContext context, String name) {
Ruby runtime = context.getRuntime();
if (this == runtime.getObject()) runtime.secure(4);
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw new SecurityException("Insecure: can't undef");
}
testFrozen("module");
if (name.equals("__id__") || name.equals("__send__")) {
runtime.getWarnings().warn(ID.UNDEFINING_BAD, "undefining `"+ name +"' may cause serious problem");
}
DynamicMethod method = searchMethod(name);
if (method.isUndefined()) {
String s0 = " class";
RubyModule c = this;
if (c.isSingleton()) {
IRubyObject obj = ((MetaClass)c).getAttached();
if (obj != null && obj instanceof RubyModule) {
c = (RubyModule) obj;
s0 = "";
}
} else if (c.isModule()) {
s0 = " module";
}
throw runtime.newNameError("Undefined method " + name + " for" + s0 + " '" + c.getName() + "'", name);
}
addMethod(name, UndefinedMethod.getInstance());
if (isSingleton()) {
IRubyObject singleton = ((MetaClass)this).getAttached();
singleton.callMethod(context, "singleton_method_undefined", runtime.newSymbol(name));
} else {
callMethod(context, "method_undefined", runtime.newSymbol(name));
}
}
@JRubyMethod(name = "include?", required = 1)
public IRubyObject include_p(ThreadContext context, IRubyObject arg) {
if (!arg.isModule()) throw context.getRuntime().newTypeError(arg, context.getRuntime().getModule());
RubyModule moduleToCompare = (RubyModule) arg;
// See if module is in chain...Cannot match against itself so start at superClass.
for (RubyModule p = getSuperClass(); p != null; p = p.getSuperClass()) {
if (p.isSame(moduleToCompare)) return context.getRuntime().getTrue();
}
return context.getRuntime().getFalse();
}
// TODO: Consider a better way of synchronizing
public void addMethod(String name, DynamicMethod method) {
Ruby runtime = getRuntime();
if (this == runtime.getObject()) runtime.secure(4);
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw runtime.newSecurityError("Insecure: can't define method");
}
testFrozen("class/module");
addMethodInternal(name, method);
}
public void addMethodInternal(String name, DynamicMethod method) {
synchronized(getMethodsForWrite()) {
addMethodAtBootTimeOnly(name, method);
invalidateCacheDescendants();
}
}
/**
* This method is not intended for use by normal users; it is a fast-path
* method that skips synchronization and hierarchy invalidation to speed
* boot-time method definition.
*
* @param name The name to which to bind the method
* @param method The method to bind
*/
public void addMethodAtBootTimeOnly(String name, DynamicMethod method) {
getMethodsForWrite().put(name, method);
}
public void removeMethod(ThreadContext context, String name) {
Ruby runtime = context.getRuntime();
if (this == runtime.getObject()) runtime.secure(4);
if (runtime.getSafeLevel() >= 4 && !isTaint()) {
throw runtime.newSecurityError("Insecure: can't remove method");
}
testFrozen("class/module");
// We can safely reference methods here instead of doing getMethods() since if we
// are adding we are not using a IncludedModuleWrapper.
synchronized(getMethodsForWrite()) {
DynamicMethod method = (DynamicMethod) getMethodsForWrite().remove(name);
if (method == null) {
throw runtime.newNameError("method '" + name + "' not defined in " + getName(), name);
}
invalidateCacheDescendants();
}
if (isSingleton()) {
IRubyObject singleton = ((MetaClass)this).getAttached();
singleton.callMethod(context, "singleton_method_removed", runtime.newSymbol(name));
} else {
callMethod(context, "method_removed", runtime.newSymbol(name));
}
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public DynamicMethod searchMethod(String name) {
return searchWithCache(name).method;
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public CacheEntry searchWithCache(String name) {
CacheEntry entry = cacheHit(name);
if (entry != null) return entry;
// we grab serial number first; the worst that will happen is we cache a later
// update with an earlier serial number, which would just flush anyway
int token = getCacheToken();
DynamicMethod method = searchMethodInner(name);
if (method instanceof DefaultMethod) {
method = ((DefaultMethod)method).getMethodForCaching();
}
return method != null ? addToCache(name, method, token) : addToCache(name, UndefinedMethod.getInstance(), token);
}
public final int getCacheToken() {
return generation;
}
private final Map<String, CacheEntry> getCachedMethods() {
return this.cachedMethods;
}
private final Map<String, CacheEntry> getCachedMethodsForWrite() {
Map<String, CacheEntry> myCachedMethods = this.cachedMethods;
return myCachedMethods == Collections.EMPTY_MAP ?
this.cachedMethods = new ConcurrentHashMap<String, CacheEntry>(0, 0.75f, 1) :
myCachedMethods;
}
private CacheEntry cacheHit(String name) {
CacheEntry cacheEntry = getCachedMethods().get(name);
if (cacheEntry != null) {
if (cacheEntry.token == getCacheToken()) {
return cacheEntry;
}
}
return null;
}
protected static abstract class CacheEntryFactory {
public abstract CacheEntry newCacheEntry(DynamicMethod method, int token);
}
protected static final CacheEntryFactory NormalCacheEntryFactory = new CacheEntryFactory() {
public CacheEntry newCacheEntry(DynamicMethod method, int token) {
return new CacheEntry(method, token);
}
};
protected static final CacheEntryFactory SynchronizedCacheEntryFactory = new CacheEntryFactory() {
public CacheEntry newCacheEntry(DynamicMethod method, int token) {
return new CacheEntry(new SynchronizedDynamicMethod(method), token);
}
};
private volatile CacheEntryFactory cacheEntryFactory = NormalCacheEntryFactory;
// modifies this class only; used to make the Synchronized module synchronized
public void becomeSynchronized() {
cacheEntryFactory = SynchronizedCacheEntryFactory;
}
public boolean isSynchronized() {
return cacheEntryFactory == SynchronizedCacheEntryFactory;
}
private CacheEntry addToCache(String name, DynamicMethod method, int token) {
CacheEntry entry = cacheEntryFactory.newCacheEntry(method, token);
getCachedMethodsForWrite().put(name, entry);
return entry;
}
protected DynamicMethod searchMethodInner(String name) {
DynamicMethod method = getMethods().get(name);
if (method != null) return method;
return superClass == null ? null : superClass.searchMethodInner(name);
}
public void invalidateCacheDescendants() {
if (DEBUG) System.out.println("invalidating descendants: " + classId);
generation = getRuntime().getNextModuleGeneration();
// update all hierarchies into which this module has been included
synchronized (getRuntime().getHierarchyLock()) {
for (RubyClass includingHierarchy : includingHierarchies) {
includingHierarchy.invalidateCacheDescendants();
}
}
}
protected void invalidateConstantCache() {
getRuntime().incrementConstantGeneration();
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public DynamicMethod retrieveMethod(String name) {
return getMethods().get(name);
}
/**
* Search through this module and supermodules for method definitions. Cache superclass definitions in this class.
*
* @param name The name of the method to search for
* @return The method, or UndefinedMethod if not found
*/
public RubyModule findImplementer(RubyModule clazz) {
for (RubyModule module = this; module != null; module = module.getSuperClass()) {
if (module.isSame(clazz)) return module;
}
return null;
}
public void addModuleFunction(String name, DynamicMethod method) {
addMethod(name, method);
getSingletonClass().addMethod(name, method);
}
/** rb_define_module_function
*
*/
public void defineModuleFunction(String name, Callback method) {
definePrivateMethod(name, method);
getSingletonClass().defineMethod(name, method);
}