-
Notifications
You must be signed in to change notification settings - Fork 914
/
RubyModule.java
6236 lines (5067 loc) · 228 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: 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 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 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 com.headius.invokebinder.Binder;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessControlException;
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.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.jcodings.Encoding;
import org.jcodings.specific.USASCIIEncoding;
import org.jruby.anno.AnnotationBinder;
import org.jruby.anno.AnnotationHelper;
import org.jruby.anno.FrameField;
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.embed.Extension;
import org.jruby.exceptions.LoadError;
import org.jruby.exceptions.RaiseException;
import org.jruby.exceptions.RuntimeError;
import org.jruby.internal.runtime.AbstractIRMethod;
import org.jruby.internal.runtime.methods.AliasMethod;
import org.jruby.internal.runtime.methods.AttrReaderMethod;
import org.jruby.internal.runtime.methods.AttrWriterMethod;
import org.jruby.internal.runtime.methods.DefineMethodMethod;
import org.jruby.internal.runtime.methods.DelegatingDynamicMethod;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.internal.runtime.methods.JavaMethod;
import org.jruby.internal.runtime.methods.NativeCallMethod;
import org.jruby.internal.runtime.methods.PartialDelegatingMethod;
import org.jruby.internal.runtime.methods.ProcMethod;
import org.jruby.internal.runtime.methods.RefinedMarker;
import org.jruby.internal.runtime.methods.RefinedWrapper;
import org.jruby.internal.runtime.methods.SynchronizedDynamicMethod;
import org.jruby.internal.runtime.methods.UndefinedMethod;
import org.jruby.ir.IRClosure;
import org.jruby.ir.IRMethod;
import org.jruby.javasupport.JavaUtil;
import org.jruby.javasupport.binding.MethodGatherer;
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.Constants;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.IRBlockBody;
import org.jruby.runtime.MethodFactory;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.PositionAware;
import org.jruby.runtime.Signature;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.backtrace.RubyStackTraceElement;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.callsite.CacheEntry;
import org.jruby.runtime.load.LoadService;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.runtime.opto.Invalidator;
import org.jruby.runtime.opto.OptoFactory;
import org.jruby.runtime.profile.MethodEnhancer;
import org.jruby.util.RubyStringBuilder;
import org.jruby.util.ByteList;
import org.jruby.util.ClassProvider;
import org.jruby.util.IdUtil;
import org.jruby.util.StringSupport;
import org.jruby.util.TypeConverter;
import org.jruby.util.cli.Options;
import org.jruby.util.collections.WeakHashSet;
import org.jruby.util.log.Logger;
import org.jruby.util.log.LoggerFactory;
import static org.jruby.anno.FrameField.BACKREF;
import static org.jruby.anno.FrameField.BLOCK;
import static org.jruby.anno.FrameField.CLASS;
import static org.jruby.anno.FrameField.FILENAME;
import static org.jruby.anno.FrameField.LASTLINE;
import static org.jruby.anno.FrameField.LINE;
import static org.jruby.anno.FrameField.METHODNAME;
import static org.jruby.anno.FrameField.SCOPE;
import static org.jruby.anno.FrameField.SELF;
import static org.jruby.anno.FrameField.VISIBILITY;
import static org.jruby.api.Convert.*;
import static org.jruby.api.Error.typeError;
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 static org.jruby.runtime.Visibility.UNDEFINED;
import static org.jruby.util.CommonByteLists.COLON_COLON;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.ids;
import static org.jruby.util.RubyStringBuilder.types;
/**
*
* @author jpetersen
*/
@JRubyClass(name="Module")
public class RubyModule extends RubyObject {
private static final Logger LOG = LoggerFactory.getLogger(RubyModule.class);
// static { LOG.setDebugEnable(true); } // enable DEBUG output
public static final int CACHEPROXY_F = ObjectFlags.CACHEPROXY_F;
public static final int NEEDSIMPL_F = ObjectFlags.NEEDSIMPL_F;
public static final int REFINED_MODULE_F = ObjectFlags.REFINED_MODULE_F;
public static final int IS_OVERLAID_F = ObjectFlags.IS_OVERLAID_F;
public static final int OMOD_SHARED = ObjectFlags.OMOD_SHARED;
public static final int INCLUDED_INTO_REFINEMENT = ObjectFlags.INCLUDED_INTO_REFINEMENT;
public static final int TEMPORARY_NAME = ObjectFlags.TEMPORARY_NAME;
public static final String BUILTIN_CONSTANT = "";
public static final ObjectAllocator MODULE_ALLOCATOR = RubyModule::new;
public static RubyClass createModuleClass(Ruby runtime, RubyClass moduleClass) {
moduleClass.setClassIndex(ClassIndex.MODULE);
moduleClass.setReifiedClass(RubyModule.class);
moduleClass.kindOf = new RubyModule.JavaClassKindOf(RubyModule.class);
moduleClass.defineAnnotatedMethods(RubyModule.class);
moduleClass.defineAnnotatedMethods(ModuleKernelMethods.class);
return moduleClass;
}
public void checkValidBindTargetFrom(ThreadContext context, RubyModule originModule, boolean fromBind) throws RaiseException {
// Module methods can always be transplanted
if (!originModule.isModule() && !hasModuleInHierarchy(originModule)) {
if (originModule instanceof MetaClass) {
throw typeError(context, "can't bind singleton method to a different class");
} else {
String thing = fromBind ? "an instance" : "a subclass"; // bind : define_method
throw typeError(context, "bind argument must be " + thing + " of ", originModule, "");
}
}
}
/**
* Get the ClassIndex for this class. Will be NO_CLASS for non-core types.
*/
public ClassIndex getClassIndex() {
return classIndex;
}
/**
* Set the ClassIndex for this core class. Only used at boot time for core
* types.
*
* @param classIndex the ClassIndex for this type
*/
void setClassIndex(ClassIndex classIndex) {
this.classIndex = classIndex;
this.index = classIndex.ordinal();
}
@JRubyMethod
public IRubyObject autoload(ThreadContext context, IRubyObject symbol, IRubyObject file) {
final Ruby runtime = context.runtime;
final RubyString fileString =
StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, file));
if (fileString.isEmpty()) throw runtime.newArgumentError("empty file name");
final String symbolStr = symbol.asJavaString();
if (!IdUtil.isValidConstantName(symbolStr)) {
throw runtime.newNameError("autoload must be constant name", symbolStr);
}
IRubyObject existingValue = fetchConstant(symbolStr);
if (existingValue != null && existingValue != RubyObject.UNDEF) return context.nil;
defineAutoload(symbolStr, fileString);
return context.nil;
}
@JRubyMethod(name = "autoload?")
public IRubyObject autoload_p(ThreadContext context, IRubyObject symbol) {
return hasAutoload(context, TypeConverter.checkID(symbol).idString(), true);
}
@JRubyMethod(name = "autoload?")
public IRubyObject autoload_p(ThreadContext context, IRubyObject symbol, IRubyObject inherit) {
return hasAutoload(context, TypeConverter.checkID(symbol).idString(), inherit.isTrue());
}
public IRubyObject hasAutoload(ThreadContext context, String idString, boolean inherit) {
for (RubyModule mod = this; mod != null; mod = mod.getSuperClass()) {
final IRubyObject loadedValue = mod.fetchConstant(idString);
if (loadedValue == UNDEF) {
final RubyString file;
Autoload autoload = mod.getAutoloadMap().get(idString);
// autoload has been evacuated
if (autoload == null) return context.nil;
// autoload has been completed
if (autoload.getValue() != null) return context.nil;
file = autoload.getPath();
// autoload is in progress on another thread
if (autoload.ctx != null && !autoload.isSelf(context)) return file;
// file load is in progress or file is already loaded
if (!getRuntime().getLoadService().featureAlreadyLoaded(file.asJavaString())) return file;
}
if (!inherit) break;
}
return context.nil;
}
@Override
public ClassIndex getNativeClassIndex() {
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) {
RubyModule cl = obj.getMetaClass();
// Not sure how but this happens in test_objects_are_released_by_cache_map
if (cl == null) return false;
return cl.hasAncestor(type);
}
}
public static final class JavaClassKindOf extends RubyModule.KindOf {
private final Class klass;
public JavaClassKindOf(Class klass) {
this.klass = klass;
}
@Override
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return klass.isInstance(obj);
}
}
public boolean isInstance(IRubyObject object) {
return kindOf.isKindOf(object, this);
}
public boolean hasAncestor(RubyModule type) {
return searchAncestor(type.getDelegate().getOrigin()) != null;
}
public Map<String, ConstantEntry> getConstantMap() {
return getOrigin().constants;
}
public Map<String, ConstantEntry> getConstantMapForWrite() {
Map<String, ConstantEntry> constants = this.constants;
if (constants == Collections.EMPTY_MAP) {
synchronized (this) {
constants = this.constants;
if (constants == Collections.EMPTY_MAP) {
constants = this.constants = new ConcurrentHashMap<>(2, 0.9f, 1);
}
}
}
return constants;
}
/**
* AutoloadMap must be accessed after checking ConstantMap. Checking UNDEF value in constantMap works as a guard.
* For looking up constant, check constantMap first then try to get an Autoload object from autoloadMap.
* For setting constant, update constantMap first and remove an Autoload object from autoloadMap.
*/
protected Map<String, Autoload> getAutoloadMap() {
return autoloads;
}
protected Map<String, Autoload> getAutoloadMapForWrite() {
Map<String, Autoload> autoloads = this.autoloads;
if (autoloads == Collections.EMPTY_MAP) {
synchronized (this) {
autoloads = this.autoloads;
if (autoloads == Collections.EMPTY_MAP) {
autoloads = this.autoloads = new ConcurrentHashMap<>(2, 0.9f, 1);
}
}
}
return autoloads;
}
@SuppressWarnings("unchecked")
public void addIncludingHierarchy(IncludedModule hierarchy) {
synchronized (getRuntime().getHierarchyLock()) {
Set<RubyClass> including = this.includingHierarchies;
if (including == Collections.EMPTY_SET) {
including = this.includingHierarchies = new WeakHashSet(4);
}
including.add(hierarchy);
}
}
public final MethodHandle getIdTest() {
MethodHandle idTest = this.idTest;
if (idTest != null) return idTest;
return this.idTest = newIdTest();
}
protected final MethodHandle newIdTest() {
return Binder.from(boolean.class, ThreadContext.class, IRubyObject.class)
.insert(2, id)
.invoke(testModuleMatch);
}
/** 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(NEEDSIMPL_F, !isClass());
updateGeneration(runtime);
if (runtime.getInstanceConfig().isProfiling()) {
cacheEntryFactory = new ProfilingCacheEntryFactory(runtime, NormalCacheEntryFactory);
} else {
cacheEntryFactory = NormalCacheEntryFactory;
}
// set up an invalidator for use in new optimization strategies
methodInvalidator = OptoFactory.newMethodInvalidator(this);
}
/** 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(NEEDSIMPL_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, String file, int line) {
RubyModule module = newModule(runtime);
module.setBaseName(name);
if (setParent) module.setParent(parent);
parent.setConstant(name, module, file, line);
return module;
}
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 final synchronized void addClassProvider(ClassProvider provider) {
Set<ClassProvider> classProviders = this.classProviders;
if (!classProviders.contains(provider)) {
Set<ClassProvider> cp = new HashSet<>(classProviders.size() + 1);
cp.addAll(classProviders);
cp.add(provider);
this.classProviders = cp;
}
}
public final synchronized void removeClassProvider(ClassProvider provider) {
Set<ClassProvider> cp = new HashSet<>(classProviders);
cp.remove(provider);
this.classProviders = cp;
}
private void checkForCyclicInclude(RubyModule m) throws RaiseException {
if (isSameOrigin(m)) throw getRuntime().newArgumentError("cyclic include detected");
}
protected void checkForCyclicPrepend(RubyModule m) throws RaiseException {
if (isSameOrigin(m)) throw getRuntime().newArgumentError(getName() + " cyclic prepend detected " + m.getName());
}
private RubyClass searchProvidersForClass(String name, RubyClass superClazz) {
Set<ClassProvider> classProviders = this.classProviders;
if (classProviders == Collections.EMPTY_SET) return null;
RubyClass clazz;
for (ClassProvider classProvider: classProviders) {
if ((clazz = classProvider.defineClassUnder(this, name, superClazz)) != null) {
return clazz;
}
}
return null;
}
private RubyModule searchProvidersForModule(String name) {
Set<ClassProvider> classProviders = this.classProviders;
if (classProviders == Collections.EMPTY_SET) return null;
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;
}
public 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 RubyModule getMethodLocation() {
return methodLocation;
}
public void setMethodLocation(RubyModule module){
methodLocation = module;
}
public Map<String, DynamicMethod> getMethods() {
return this.methods;
}
public Map<String, DynamicMethod> getMethodsForWrite() {
Map<String, DynamicMethod> methods = this.methods;
if (methods != Collections.EMPTY_MAP) return methods;
synchronized (this) {
methods = this.methods;
return methods == Collections.EMPTY_MAP ?
this.methods = new ConcurrentHashMap<>(2, 0.9f, 1) : // CHM initial-size: 4
methods;
}
}
/**
* <p>Note: Internal API - only public as its used by generated code!</p>
* @param runtime
* @param id identifier string (8859_1). Matching entry in symbol table.
* @param method
* @return method
*/ // NOTE: used by AnnotationBinder
public DynamicMethod putMethod(Ruby runtime, String id, DynamicMethod method) {
if (hasPrepends()) {
method = method.dup();
method.setImplementationClass(methodLocation);
}
DynamicMethod oldMethod = methodLocation.getMethodsForWrite().put(id, method);
if (oldMethod != null && oldMethod.isRefined()) {
methodLocation.getMethodsForWrite().put(id, new RefinedWrapper(method.getImplementationClass(), method.getVisibility(), id, method));
}
runtime.addProfiledMethod(id, method);
return method;
}
/**
* Is this module one that in an included one (e.g. an {@link IncludedModuleWrapper}).
* @see IncludedModule
*/
public boolean isIncluded() {
return false;
}
public boolean isPrepended() {
return false;
}
/**
* In an included or prepended module what is the ACTUAL module it represents?
* @return the actual module of an included/prepended module.
*/
public RubyModule getOrigin() {
return this;
}
@Deprecated
public RubyModule getNonIncludedClass() {
return this;
}
public RubyModule getDelegate() {
return this;
}
/**
* Get the "real" module, either the current one or the nearest ancestor that is not a singleton or include wrapper.
*
* See {@link RubyClass#getRealClass()}.
*
* @return the nearest non-singleton non-include module in the hierarchy
*/
public RubyModule getRealModule() {
RubyModule cl = this;
while (cl != null &&
(cl.isSingleton() || cl.isIncluded())) {
cl = cl.superClass;
}
return cl;
}
/**
* Get the base name of this class, or null if it is an anonymous class.
*
* @return base name of the class
*/
public String getBaseName() {
return baseName;
}
/**
* Set the base name of the class. If null, the class effectively becomes
* anonymous (though constants elsewhere may reference it).
* @param name the new base name of the class
*/
public void setBaseName(String name) {
baseName = name;
cachedName = null;
cachedRubyName = null;
}
/**
* 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 (cachedName != null) return cachedName;
return calculateName();
}
/**
* Generate a fully-qualified class name or a #-style name for anonymous and singleton classes which
* is properly encoded. The returned string is always frozen.
*
* @return a properly encoded class name.
*
* Note: getId() is only really valid for ASCII values. This should be favored over using it.
*/
public RubyString rubyName() {
return cachedRubyName != null ? cachedRubyName : calculateRubyName();
}
public RubyString rubyBaseName() {
String baseName = getBaseName();
final Ruby runtime = metaClass.runtime;
return baseName == null ? null : runtime.newSymbol(baseName).to_s(runtime);
}
private RubyString calculateAnonymousRubyName() {
Ruby runtime = getRuntime();
RubyString anonBase = runtime.newString("#<"); // anonymous classes get the #<Class:0xdeadbeef> format
anonBase.append(metaClass.getRealClass().rubyName()).append(runtime.newString(":0x"));
anonBase.append(runtime.newString(Integer.toHexString(System.identityHashCode(this)))).append(runtime.newString(">"));
return anonBase;
}
private RubyString calculateRubyName() {
boolean cache = true;
if (getBaseName() == null) return calculateAnonymousRubyName(); // no name...anonymous!
if (usingTemporaryName()) { // temporary name
cachedRubyName = getRuntime().newSymbol(baseName).toRubyString(getRuntime().getCurrentContext());
return cachedRubyName;
}
Ruby runtime = getRuntime();
RubyClass objectClass = runtime.getObject();
List<RubyString> parents = new ArrayList<>();
for (RubyModule p = getParent(); p != null && p != objectClass; p = p.getParent()) {
if (p == this) break; // Break out of cyclic namespaces like C::A = C2; C2::A = C (jruby/jruby#2314)
RubyString name = p.rubyBaseName();
// 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 (name == null) {
cache = false;
name = p.rubyName();
}
parents.add(name);
}
Collections.reverse(parents);
RubyString colons = runtime.newString("::");
RubyString fullName = runtime.newString(); // newString creates empty ByteList which ends up as
fullName.setEncoding(USASCIIEncoding.INSTANCE); // ASCII-8BIT. 8BIT is unfriendly to string concats.
for (RubyString parent: parents) {
RubyString rubyString = fullName.catWithCodeRange(parent);
rubyString.catWithCodeRange(colons);
}
fullName.catWithCodeRange(rubyBaseName());
fullName.setFrozen(true);
if (cache) cachedRubyName = fullName;
return fullName;
}
/**
* Get the "simple" name for the class, which is either the "base" name or
* the "anonymous" class name.
*
* @return the "simple" name of the class
*/
public String getSimpleName() {
if (baseName != null) return baseName;
return calculateAnonymousName();
}
/**
* Recalculate the fully-qualified name of this class/module.
*/
private String calculateName() {
boolean cache = true;
if (getBaseName() == null) {
// we are anonymous, use anonymous name
return calculateAnonymousName();
}
Ruby runtime = getRuntime();
String name = getBaseName();
RubyClass objectClass = runtime.getObject();
// First, we count the parents
int parentCount = 0;
for (RubyModule p = getParent() ; p != null && p != objectClass ; p = p.getParent()) {
// Break out of cyclic namespaces like C::A = C2; C2::A = C (jruby/jruby#2314)
if (p == this) break;
parentCount++;
}
// Allocate a String array for all of their names and populate it
String[] parentNames = new String[parentCount];
int i = parentCount - 1;
int totalLength = name.length() + parentCount * 2; // name length + enough :: for all parents
for (RubyModule p = getParent() ; p != null && p != objectClass ; p = p.getParent(), i--) {
// Break out of cyclic namespaces like C::A = C2; C2::A = C (jruby/jruby#2314)
if (p == this) break;
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) {
cache = false;
pName = p.getName();
}
parentNames[i] = pName;
totalLength += pName.length();
}
// Then build from the front using a StringBuilder
StringBuilder builder = new StringBuilder(totalLength);
for (String parentName : parentNames) {
builder.append(parentName).append("::");
}
builder.append(name);
String fullName = builder.toString();
if (cache) cachedName = fullName;
return fullName;
}
private String calculateAnonymousName() {
String cachedName = this.cachedName;
if (cachedName == null) {
// anonymous classes get the #<Class:0xdeadbeef> format
cachedName = this.cachedName = "#<" + anonymousMetaNameWithIdentifier() + '>';
}
return cachedName;
}
@JRubyMethod(required = 1)
public IRubyObject set_temporary_name(ThreadContext context, IRubyObject arg) {
if (baseName != null && IdUtil.isValidConstantName(baseName) && (parent == null || parent.baseName != null)) {
throw context.runtime.newRuntimeError("can't change permanent name");
}
if (arg.isNil()) {
setBaseName(null);
} else {
RubyString name = arg.convertToString();
if (name.length() == 0) throw context.runtime.newArgumentError("empty class/module name");
if (isValidConstantPath(name))
throw context.runtime.newArgumentError("the temporary name must not be a constant path to avoid confusion");
setFlag(TEMPORARY_NAME, true);
// We make sure we generate ISO_8859_1 String and also guarantee when we want to print this name
// later it does not lose track of the orignal encoding.
RubySymbol symbol = context.runtime.newSymbol(name.getByteList());
setBaseName(symbol.idString());
}
return this;
}
String anonymousMetaNameWithIdentifier() {
return metaClass.getRealClass().getName() + ":0x" + Integer.toHexString(System.identityHashCode(this));
}
@JRubyMethod(name = "refine", reads = SCOPE)
public IRubyObject refine(ThreadContext context, IRubyObject klass, Block block) {
if (!block.isGiven()) throw context.runtime.newArgumentError("no block given");
if (block.isEscaped()) throw context.runtime.newArgumentError("can't pass a Proc as a block to Module#refine");
if (!(klass instanceof RubyModule)) throw typeError(context, klass, "Class or Module");
if (refinements == Collections.EMPTY_MAP) refinements = newRefinementsMap();
if (activatedRefinements == Collections.EMPTY_MAP) activatedRefinements = newActivatedRefinementsMap();
RubyModule moduleToRefine = (RubyModule) klass;
RubyModule refinement = refinements.get(moduleToRefine);
if (refinement == null) {
refinement = createNewRefinedModule(context, moduleToRefine);
// Add it to the activated chain of other refinements already added to this class we are refining
addActivatedRefinement(context, moduleToRefine, refinement);
}
// Executes the block supplied with the defined method definitions using the refinement as it's module.
yieldRefineBlock(context, refinement, block);
return refinement;
}
private RubyModule createNewRefinedModule(ThreadContext context, RubyModule klass) {
Ruby runtime = context.runtime;
RubyModule newRefinement = new RubyModule(runtime, runtime.getRefinement());
RubyClass superClass = refinementSuperclass(runtime, klass);
newRefinement.setSuperClass(superClass);
newRefinement.setFlag(REFINED_MODULE_F, true);
newRefinement.setFlag(NEEDSIMPL_F, false); // Refinement modules should not do implementer check
newRefinement.refinedClass = klass;
newRefinement.definedAt = this;
refinements.put(klass, newRefinement);
return newRefinement;
}
private static RubyClass refinementSuperclass(Ruby runtime, RubyModule superClass) {
if (superClass.isModule()) {
return new IncludedModuleWrapper(runtime, runtime.getBasicObject(), superClass);
} else {
return (RubyClass) superClass;
}
}
private void yieldRefineBlock(ThreadContext context, RubyModule refinement, Block block) {
block = block.cloneBlockAndFrame(EvalType.MODULE_EVAL);
block.getBinding().setSelf(refinement);
RubyModule overlayModule = block.getBody().getStaticScope().getOverlayModuleForWrite(context);
overlayModule.refinements = refinements;
block.yieldSpecific(context);
}
// This has three cases:
// 1. class being refined has never had any refines happen to it yet: return itself
// 2. class has been refined: return already existing refinementwrapper (chain of modules to call against)
// 3. refinement is already in the refinementwrapper so we do not need to add it to the wrapper again: return null
private RubyClass getAlreadyActivatedRefinementWrapper(RubyClass classWeAreRefining, RubyModule refinement) {
// We have already encountered at least one refine on this class. Return that wrapper.
RubyClass moduleWrapperForRefinement = activatedRefinements.get(classWeAreRefining);
if (moduleWrapperForRefinement == null) return classWeAreRefining;
for (RubyModule c = moduleWrapperForRefinement; c != null && c.isIncluded(); c = c.getSuperClass()) {
if (c.getOrigin() == refinement) return null;
}
return moduleWrapperForRefinement;
}
/*
* We will find whether we have already refined once and get that set of includedmodules or we will start to create
* one. The new refinement will be added as a new included module on the front. It will also add all superclasses
* of the refinement into this call chain.
*
* MRI: add_activated_refinement
*/
private void addActivatedRefinement(ThreadContext context, RubyModule moduleToRefine, RubyModule refinement) {
// RubyClass superClass = getAlreadyActivatedRefinementWrapper(classWeAreRefining, refinement);
// if (superClass == null) return; // already been refined and added to refinementwrapper
RubyClass superClass = null;
RubyClass c = activatedRefinements.get(moduleToRefine);
if (c != null) {
superClass = c;
while (c != null && c.isIncluded()) {
if (c.getOrigin() == refinement) {
/* already used refinement */
return;
}
c = c.getSuperClass();
}
}
refinement.setFlag(IS_OVERLAID_F, true);
IncludedModuleWrapper iclass = new IncludedModuleWrapper(context.runtime, superClass, refinement);
c = iclass;
c.refinedClass = moduleToRefine;
for (refinement = refinement.getSuperClass(); refinement != null; refinement = refinement.getSuperClass()) {
refinement.setFlag(IS_OVERLAID_F, true);
c.setSuperClass(new IncludedModuleWrapper(context.runtime, c.getSuperClass(), refinement));
c = c.getSuperClass();
c.refinedClass = moduleToRefine;
}
activatedRefinements.put(moduleToRefine, iclass);
}
@JRubyMethod(name = "using", visibility = PRIVATE, reads = {SELF, SCOPE})
public IRubyObject using(ThreadContext context, IRubyObject refinedModule) {
if (context.getFrameSelf() != this) throw context.runtime.newRuntimeError("Module#using is not called on self");
if (context.getCurrentStaticScope().isWithinMethod()) {
throw context.runtime.newRuntimeError("Module#using is not permitted in methods");
}
// I pass the cref even though I don't need to so that the concept is simpler to read
StaticScope staticScope = context.getCurrentStaticScope();
RubyModule overlayModule = staticScope.getOverlayModuleForWrite(context);
usingModule(context, overlayModule, refinedModule);
return this;
}
// mri: rb_using_module
public static void usingModule(ThreadContext context, RubyModule cref, IRubyObject refinedModule) {
usingModuleRecursive(context, cref, castToModule(context, refinedModule));
}
// mri: using_module_recursive
private static void usingModuleRecursive(ThreadContext context, RubyModule cref, RubyModule module) {
RubyClass superClass = module.getSuperClass();
// For each superClass of the refined module also use their refinements for the given cref
if (superClass != null) usingModuleRecursive(context, cref, superClass);
if (module instanceof DelegatedModule) {
module = module.getDelegate();
} else if (!module.isModule()) {
throw typeError(context, module, "Module");
}
Map<RubyModule, RubyModule> refinements = module.refinements;
if (refinements == null) return; // No refinements registered for this module
for (Map.Entry<RubyModule, RubyModule> entry: refinements.entrySet()) {
usingRefinement(context.runtime, cref, entry.getKey(), entry.getValue());
}