-
-
Notifications
You must be signed in to change notification settings - Fork 938
Expand file tree
/
Copy pathRubyBasicObject.java
More file actions
3191 lines (2815 loc) · 116 KB
/
RubyBasicObject.java
File metadata and controls
3191 lines (2815 loc) · 116 KB
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) 2008 Thomas E Enebo <enebo@acm.org>
*
* 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 org.jcodings.Encoding;
import org.jruby.anno.JRubyMethod;
import org.jruby.api.Convert;
import org.jruby.api.Create;
import org.jruby.api.JRubyAPI;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.ir.interpreter.Interpreter;
import org.jruby.java.proxies.JavaProxy;
import org.jruby.javasupport.JavaUtil;
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.Helpers;
import org.jruby.runtime.JavaSites;
import org.jruby.runtime.JavaSites.BasicObjectSites;
import org.jruby.runtime.ObjectAllocator;
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.InstanceVariables;
import org.jruby.runtime.builtin.InternalVariables;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.callsite.CacheEntry;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.runtime.ivars.VariableAccessor;
import org.jruby.runtime.ivars.VariableTableManager;
import org.jruby.runtime.marshal.CoreObjectType;
import org.jruby.util.ArraySupport;
import org.jruby.util.IdUtil;
import org.jruby.util.TypeConverter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
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.Access.arrayClass;
import static org.jruby.api.Access.encodingService;
import static org.jruby.api.Access.globalVariables;
import static org.jruby.api.Access.hashClass;
import static org.jruby.api.Access.integerClass;
import static org.jruby.api.Access.stringClass;
import static org.jruby.api.Check.checkID;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Convert.asSymbol;
import static org.jruby.api.Convert.castAsModule;
import static org.jruby.api.Convert.toInt;
import static org.jruby.api.Create.newArray;
import static org.jruby.api.Create.newEmptyArray;
import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.nameError;
import static org.jruby.api.Error.typeError;
import static org.jruby.api.Warn.warn;
import static org.jruby.ir.runtime.IRRuntimeHelpers.dupIfKeywordRestAtCallsite;
import static org.jruby.runtime.Helpers.invokeChecked;
import static org.jruby.runtime.Helpers.invokedynamic;
import static org.jruby.runtime.ThreadContext.CALL_KEYWORD;
import static org.jruby.runtime.ThreadContext.CALL_KEYWORD_REST;
import static org.jruby.runtime.ThreadContext.CALL_SPLATS;
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.invokedynamic.MethodNames.EQL;
import static org.jruby.runtime.invokedynamic.MethodNames.OP_CMP;
import static org.jruby.runtime.invokedynamic.MethodNames.OP_EQUAL;
import static org.jruby.util.Inspector.COMMA;
import static org.jruby.util.Inspector.EQUALS;
import static org.jruby.util.Inspector.GT;
import static org.jruby.util.Inspector.SPACE;
import static org.jruby.util.Inspector.SPACE_DOT_DOT_DOT_GT;
import static org.jruby.util.Inspector.inspectPrefix;
import static org.jruby.util.RubyStringBuilder.ids;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.types;
import static org.jruby.util.io.EncodingUtils.encStrBufCat;
/**
* RubyBasicObject is the only implementation of the
* {@link org.jruby.runtime.builtin.IRubyObject}. Every Ruby object in JRuby
* is represented by something that is an instance of RubyBasicObject. In
* the core class implementations, this means doing a subclass
* that extends RubyBasicObject. In other cases it means using a simple
* RubyBasicObject instance and its data fields to store specific
* information about the Ruby object.
*
* Some care has been taken to make the implementation be as
* monomorphic as possible, so that the Java Hotspot engine can
* improve performance of it. That is the reason for several patterns
* that might seem odd in this class.
*
* The IRubyObject interface used to have lots of methods for
* different things, but these have now mostly been refactored into
* several interfaces that gives access to that specific part of the
* object. This gives us the possibility to switch out that subsystem
* without changing interfaces again. For example, instance variable
* and internal variables are handled this way, but the implementation
* in RubyObject only returns "this" in {@link #getInstanceVariables()} and
* {@link #getInternalVariables()}.
*
* Methods that are implemented here, such as "initialize" should be implemented
* with care; reification of Ruby classes into Java classes can produce
* conflicting method names in rare cases. See JRUBY-5906 for an example.
*/
@SuppressWarnings("ComparableType")
public class RubyBasicObject implements Cloneable, IRubyObject, Serializable, Comparable<IRubyObject>, CoreObjectType, InstanceVariables, InternalVariables {
//private static final Logger LOG = LoggerFactory.getLogger(RubyBasicObject.class);
//private static final boolean DEBUG = false;
/** The class of this object */
protected transient RubyClass metaClass;
/** object flags */
protected byte flags;
/** variable table, lazily allocated as needed (if needed) */
public transient Object[] varTable;
/** locking stamp for Unsafe ops updating the vartable */
public transient volatile byte varTableStamp;
/**
* The error message used when some one tries to modify an
* instance variable in a high security setting.
*/
public static final String ERR_INSECURE_SET_INST_VAR = "Insecure: can't modify instance variable";
static final byte FALSE = 0b00000001;
static final byte NIL = 0b00000010;
static final byte FROZEN = 0b00000100;
@Deprecated(since = "10.0.3.0")
public static final int ALL_F = -1;
/** @deprecated external access to global object flags is going away */
@Deprecated(since = "10.0.3.0")
public static final int FALSE_F = FALSE;
/**
* This flag is a bit funny. It's used to denote that this value
* is nil. It's a bit counterintuitive for a Java programmer to
* not use subclassing to handle this case, since we have a
* RubyNil subclass anyway. Well, the reason for it being a flag
* is that the {@link #isNil()} method is called extremely often. So often
* that it gives a good speed boost to make it monomorphic and
* final. It turns out using a flag for this actually gives us
* better performance than having a polymorphic {@link #isNil()} method.
*
* @deprecated external access to global object flags is going away
*/
@Deprecated(since = "10.0.3.0")
public static final int NIL_F = NIL;
@Deprecated(since = "10.0.3.0")
public static final int FROZEN_F = ObjectFlags.FROZEN_F;
/**
* A value that is used as a null sentinel in among other places
* the RubyArray implementation. It will cause large problems to
* call any methods on this object.
*/
public static final IRubyObject NEVER = new RubyBasicObject();
/**
* A value that specifies an undefined value. This value is used
* as a sentinel for undefined constant values, and other places
* where neither null nor NEVER makes sense.
*/
public static final IRubyObject UNDEF = new RubyBasicObject();
/**
* It's not valid to create a totally empty RubyObject. Since the
* RubyObject is always defined in relation to a runtime, that
* means that creating RubyObjects from outside the class might
* cause problems.
*/
private RubyBasicObject(){}
/**
* Default allocator instance for all Ruby objects. The only
* reason to not use this allocator is if you actually need to
* have all instances of something be a subclass of RubyObject.
*
* @see org.jruby.runtime.ObjectAllocator
*/
public static final ObjectAllocator BASICOBJECT_ALLOCATOR = RubyBasicObject::new;
/**
* Will create the Ruby class BasicObject in the runtime specified. This method needs to take the
* actual class as an argument because of the Object class' central part in runtime initialization.
* @param context the thread context
* @param BasicObject reference to BasicObject
*/
public static void finishBasicObjectClass(ThreadContext context, RubyClass BasicObject) {
BasicObject.classIndex(ClassIndex.OBJECT).
defineMethods(context, RubyBasicObject.class);
recacheBuiltinMethods(context, BasicObject);
}
static void recacheBuiltinMethods(ThreadContext context, RubyClass BasicObject) {
// Since method_missing is marked module we actually define two builtin versions
context.runtime.setDefaultMethodMissing(BasicObject.searchMethod("method_missing"),
BasicObject.metaClass.searchMethod("method_missing"));
}
@JRubyMethod(name = "initialize", visibility = PRIVATE)
public IRubyObject initialize(ThreadContext context) {
return context.nil;
}
/**
* Standard path for object creation. Objects are entered into ObjectSpace
* only if ObjectSpace is enabled.
* @param runtime the runtime
* @param metaClass the meta class
*/
public RubyBasicObject(Ruby runtime, RubyClass metaClass) {
this.metaClass = metaClass;
runtime.addToObjectSpace(true, this);
}
/**
* Path for objects that don't enter objectspace.
* @param metaClass the new metaclass
*/
public RubyBasicObject(RubyClass metaClass) {
this.metaClass = metaClass;
}
/**
* Path for objects who want to decide whether they don't want to be in
* ObjectSpace even when it is on. (notably used by objects being
* considered immediate, they'll always pass false here)
* @param runtime the runtime
* @param metaClass the metaclass
* @param useObjectSpace should object space be enabled
*/
protected RubyBasicObject(Ruby runtime, RubyClass metaClass, boolean useObjectSpace) {
this.metaClass = metaClass;
runtime.addToObjectSpace(useObjectSpace, this);
}
/** rb_frozen_class_p
*
* Helper to test whether this object is frozen, and if it is will
* throw an exception based on the message.
* @param message is frozen
*/
protected final void testFrozen(String message) {
if (isFrozen()) {
throw getRuntime().newFrozenError(message, this);
}
}
/** rb_frozen_class_p
*
* Helper to test whether this object is frozen, and if it is will
* throw an exception based on the message.
*/
protected final void testFrozen() {
if (isFrozen()) {
var context = getRuntime().getCurrentContext();
throw context.runtime.newFrozenError((isClass() ? "Class: " : (isModule() ? "Module: " : "Object: ")) + inspect(context), this);
}
}
/**
* @deprecated external access to global object flags is going away
*/
@Deprecated(since = "10.0.3.0")
public final void setFlag(int flag, boolean set) {
if (flag == FROZEN) {
setFrozen(set);
} else if (set) {
flags |= flag;
} else {
flags &= ~flag;
}
}
/**
* @deprecated external access to global object flags is going away
*/
@Deprecated(since = "10.0.3.0")
public final boolean getFlag(int flag) {
if (flag == FROZEN) {
return isFrozen();
}
return (flags & flag) != 0;
}
/**
* Will invoke a named method with no arguments and no block if that method or a custom
* method missing exists. Otherwise returns null. 1.9: rb_check_funcall
*/
@Override
public final IRubyObject checkCallMethod(ThreadContext context, String name) {
return Helpers.invokeChecked(context, this, name);
}
/**
* Will invoke a named method with no arguments and no block if that method or a custom
* method missing exists. Otherwise returns null. 1.9: rb_check_funcall
*/
@Override
public final IRubyObject checkCallMethod(ThreadContext context, JavaSites.CheckedSites sites) {
return Helpers.invokeChecked(context, this, sites);
}
/**
* Will invoke a named method with no arguments and no block.
*/
@Override
public final IRubyObject callMethod(ThreadContext context, String name) {
return Helpers.invoke(context, this, name);
}
/**
* Will invoke a named method with one argument and no block with
* functional invocation.
*/
@Override
public final IRubyObject callMethod(ThreadContext context, String name, IRubyObject arg) {
return Helpers.invoke(context, this, name, arg);
}
/**
* Will invoke a named method with the supplied arguments and no
* block with functional invocation.
*/
@Override
public final IRubyObject callMethod(ThreadContext context, String name, IRubyObject[] args) {
return Helpers.invoke(context, this, name, args);
}
public final IRubyObject callMethod(String name, IRubyObject... args) {
return Helpers.invoke(metaClass.runtime.getCurrentContext(), this, name, args);
}
public final IRubyObject callMethod(String name, IRubyObject arg) {
return Helpers.invoke(metaClass.runtime.getCurrentContext(), this, name, arg);
}
public final IRubyObject callMethod(String name) {
return Helpers.invoke(metaClass.runtime.getCurrentContext(), this, name);
}
/**
* Will invoke a named method with the supplied arguments and
* supplied block with functional invocation.
*/
@Override
public final IRubyObject callMethod(ThreadContext context, String name, IRubyObject[] args, Block block) {
return Helpers.invoke(context, this, name, args, block);
}
/**
* Does this object represent nil?
*
* @return true if nil
*/
@Override
public final boolean isNil() {
return (flags & NIL) != 0;
}
/**
* Is this value a truthy value or not?
*
* @return true if truthy
*/
@Override
public final boolean isTrue() {
return (flags & FALSE) == 0;
}
/**
* Is this value a falsey value or not?
*
* @return true if falsey
*/
public final boolean isFalse() {
return (flags & FALSE) != 0;
}
/** whether the object has been frozen */ /**
* Is this value frozen or not?
*
* @return true if this object is frozen, false otherwise
*/
@Override
public boolean isFrozen() {
return (flags & FROZEN) != 0;
}
/**
* Sets whether this object is frozen or not.
*
* @param frozen should this object be frozen?
*/
@Override
public void setFrozen(boolean frozen) {
if (frozen) {
flags |= FROZEN;
} else {
flags &= ~FROZEN;
}
}
/**
* Is object immediate (def: Fixnum, Symbol, true, false, nil?).
*/
@Override
public boolean isImmediate() {
return false;
}
@Override
public boolean isSpecialConst() {
return isImmediate() || !isTrue();
}
// MRI: special_object_p
public boolean isSpecialObject() {
// This is broader than MRI but immediates and numeric overlap so I don't think it will hurt.
// RubyNumeric vs limited list to also include Numeric/Integer so we need not duplicate clone
// (and potentially others).
return isImmediate() || this instanceof RubyNumeric;
}
/**
* if exist return the meta-class else return the type of the object.
*
*/
@Override
public final RubyClass getMetaClass() {
return metaClass;
}
public static RubyClass getMetaClass(IRubyObject arg) {
return ((RubyBasicObject) arg).metaClass;
}
@Override
public RubyClass getSingletonClass() {
return singletonClass(getCurrentContext());
}
/**
* Will either return the existing singleton class for this object, or create a new one and return that.
* For a few types a singleton class is not possible so it will throw an error.
*
* @param context the current thread context
* @return the singleton of this type
*/
// MRI: rb_singleton_class
@JRubyAPI
public RubyClass singletonClass(ThreadContext context) {
RubyClass klass = metaClass.toSingletonClass(context, this);
if (isFrozen()) klass.setFrozen(true);
return klass;
}
@Deprecated(since = "10.0.0.0")
public RubyClass makeMetaClass(RubyClass superClass) {
return makeMetaClass(getCurrentContext(), superClass);
}
/** rb_make_metaclass
*
* Will create a new meta class, insert this in the chain of
* classes for this specific object, and return the generated meta
* class.
* @param context the thread context
* @param superClass the super class
* @return the new meta class
*/
public RubyClass makeMetaClass(ThreadContext context, RubyClass superClass) {
MetaClass klass = new MetaClass(context.runtime, superClass, this); // rb_class_boot
setMetaClass(klass);
klass.setMetaClass(superClass.getRealClass().metaClass);
return klass;
}
/**
* This will create a new metaclass. This is only used during bootstrapping before
* the initial ThreadContext is defined. Normal needs of making a metaclass should use
* {@link RubyBasicObject#makeMetaClass(ThreadContext, RubyClass)}
* @param runtime the runtime
* @param superClass of the metaclass
* @param Class a reference to Ruby Class
* @return the new metaclass
*/
public RubyClass makeMetaClassBootstrap(Ruby runtime, RubyClass superClass, RubyClass Class) {
MetaClass klass = new MetaClass(runtime, superClass, Class, this); // rb_class_boot
setMetaClass(klass);
klass.setMetaClass(superClass.getRealClass().metaClass);
return klass;
}
/**
* Makes it possible to change the metaclass of an object. In
* practice, this is a simple version of Smalltalks Become, except
* that it doesn't work when we're dealing with subclasses. In
* practice it's used to change the singleton/meta class used,
* without changing the "real" inheritance chain.
* @param metaClass the meta class to set
*/
public void setMetaClass(RubyClass metaClass) {
this.metaClass = metaClass;
}
/**
* @see org.jruby.runtime.builtin.IRubyObject#getType()
*/
@Override
public final RubyClass getType() {
return metaClass.getRealClass();
}
/**
* Does this object respond to the specified message? Uses a
* shortcut if it can be proved that respond_to? and respond_to_missing?
* haven't been overridden.
*/
@Override
public final boolean respondsTo(String name) {
final Ruby runtime = metaClass.runtime;
final CacheEntry entry = metaClass.searchWithCache("respond_to?");
final DynamicMethod respondTo = entry.method;
// fastest path; builtin respond_to? and respond_to_missing? so we just check isMethodBound
if ( respondTo.equals(runtime.getRespondToMethod()) &&
metaClass.searchMethod("respond_to_missing?").equals(runtime.getRespondToMissingMethod()) ) {
return metaClass.respondsToMethod(name, false);
}
final ThreadContext context = runtime.getCurrentContext();
final RubySymbol mname = asSymbol(context, name);
// respond_to? or respond_to_missing? is not defined, so we must dispatch to trigger method_missing
if ( respondTo.isUndefined() ) {
return sites(context).respond_to.call(context, this, this, mname).isTrue();
} else {
return respondTo.callRespondTo(context, this, "respond_to?", entry.sourceModule, mname);
}
}
/**
* Does this object respond to the specified message via "method_missing?"
*/
@Override
public final boolean respondsToMissing(String name) {
return respondsToMissing(name, true);
}
/**
* Does this object respond to the specified message via "method_missing?"
*/
@Override
public final boolean respondsToMissing(String name, boolean incPrivate) {
CacheEntry entry = metaClass.searchWithCache("respond_to_missing?");
DynamicMethod method = entry.method;
// perhaps should try a smart version as for respondsTo above?
if (method.isUndefined())return false;
var context = getRuntime().getCurrentContext();
return method.call(context, this, entry.sourceModule, "respond_to_missing?",
asSymbol(context, name), incPrivate ? context.tru : context.fals).isTrue();
}
/**
* Will return the runtime that this object is associated with.
*
* @return current runtime
*/
@Override
public final Ruby getRuntime() {
return metaClass.runtime;
}
// As part of reducing usage of getRuntime() this method was added so it is
// easier to know how many real uses of getRuntime() we still need to eliminate.
// IMPORTANT: This method should only be used in deprecated methods. If you do
// not have access then you should continue using getRuntime().getCurrentContext()
// until we can plumb ThreadContext into whatever method needs it.
@Deprecated(since = "10.0.0.0")
public final ThreadContext getCurrentContext() {
return getRuntime().getCurrentContext();
}
/**
* Will return the Java interface that most closely can represent
* this object, when working through Java integration translations.
* @return the true Java class of this (Ruby) object
*/
@Override
public Class<?> getJavaClass() {
Object obj = JavaUtil.unwrapJava(dataGetStruct(), null);
return obj != null ? obj.getClass() : getClass();
}
/** rb_to_id
*
* Will try to convert this object to a String using the Ruby
* "to_str" if the object isn't already a String. If this still
* doesn't work, will throw a Ruby TypeError.
* @return a (Java) string
*/
@Override
public String asJavaString() {
IRubyObject str = checkStringType();
if (str.isNil()) throw typeError(getRuntime().getCurrentContext(), this, "String");
return str.asJavaString();
}
/** rb_obj_as_string
*
* First converts this object into a String using the "to_s"
* method and returns it. If
* to_s doesn't return a Ruby String, {@link Convert#anyToString} is used
* instead.
*/
@Override
public RubyString asString() {
Ruby runtime = metaClass.runtime;
ThreadContext context = runtime.getCurrentContext();
BasicObjectSites sites = sites(context);
IRubyObject str = sites.to_s.call(context, this, this);
if (!(str instanceof RubyString)) return Convert.anyToString(context, this);
return (RubyString) str;
}
/**
* Tries to convert this object to a Ruby Array using the "to_ary" method.
* @return array representation of this
*/
@Override
public RubyArray convertToArray() {
var context = getRuntime().getCurrentContext();
return (RubyArray) TypeConverter.convertToType(context, this, arrayClass(context), sites(context).to_ary_checked);
}
/**
* Tries to convert this object to a Ruby Hash using the "to_hash" method.
* @return hash representation of this
*/
@Override
public RubyHash convertToHash() {
ThreadContext context = getRuntime().getCurrentContext();
return (RubyHash) TypeConverter.convertToType(context, this, hashClass(context), sites(context).to_hash_checked);
}
/**
* Tries to convert this object to a Ruby Float using the "to_f" method.
* @return float representation of this
*/
@Override
public RubyFloat convertToFloat() {
Ruby runtime = metaClass.runtime;
ThreadContext context = runtime.getCurrentContext();
BasicObjectSites sites = sites(context);
return (RubyFloat) TypeConverter.convertToType(context, this, runtime.getFloat(), sites.to_f_checked);
}
/**
* Tries to convert this object to a Ruby Integer using the "to_int" method.
* @return an integer representation of this
*/
@Override
public RubyInteger convertToInteger() {
Ruby runtime = metaClass.runtime;
ThreadContext context = runtime.getCurrentContext();
BasicObjectSites sites = sites(context);
IRubyObject result = TypeConverter.convertToType(context, this, integerClass(context), sites.to_int_checked, true);
if (!(result instanceof RubyInteger)) throw typeError(context, "", this, "#to_int should return Integer");
return (RubyInteger) result;
}
/**
* Tries to convert this object to a Ruby Integer using the supplied conversion method.
* @param convertMethod conversion method to use e.g. "to_i"
* @return an integer representation of this
*/
@Override
public RubyInteger convertToInteger(String convertMethod) {
if (convertMethod.equals("to_int")) return convertToInteger();
IRubyObject result;
Ruby runtime = metaClass.runtime;
if (convertMethod.equals("to_i")) {
ThreadContext context = runtime.getCurrentContext();
BasicObjectSites sites = sites(context);
result = TypeConverter.convertToType(context, this, runtime.getInteger(), sites.to_i_checked, true);
} else {
result = TypeConverter.convertToType(this, runtime.getInteger(), convertMethod, true);
}
if (!(result instanceof RubyInteger)) {
throw typeError(runtime.getCurrentContext(), str(runtime, types(runtime, getMetaClass()),
"#", ids(runtime, convertMethod), " should return Integer"));
}
return (RubyInteger) result;
}
/**
* Tries to convert this object to a Ruby String using the "to_str" method.
* @return a string representation of this
*/
@Override
public RubyString convertToString() {
Ruby runtime = metaClass.runtime;
ThreadContext context = runtime.getCurrentContext();
BasicObjectSites sites = sites(context);
return (RubyString) TypeConverter.convertToType(context, this, stringClass(context), sites.to_str_checked);
}
/**
* Internal method that helps to convert any object into the
* format of a class name and a hex string inside of #<>.
*/
@Override
public IRubyObject anyToString() {
Ruby runtime = metaClass.runtime;
return Convert.anyToString(runtime.getCurrentContext(), this);
}
/**
* raw (id) strings are not properly encoded but in an iso_8859_1 form. This method will lookup
* properly encoded string from the symbol table.
* @param id the id of the string
* @return the string of the symbol found from id
*/
public RubyString decode(String id) {
var context = getRuntime().getCurrentContext();
return (RubyString) asSymbol(context, id).to_s(context);
}
/** rb_check_string_type
*
* Tries to return a coerced string representation of this object,
* using "to_str". If that returns something other than a String
* or nil, an empty String will be returned.
*
*/
@Override
public IRubyObject checkStringType() {
Ruby runtime = metaClass.runtime;
ThreadContext context = runtime.getCurrentContext();
BasicObjectSites sites = sites(context);
return TypeConverter.checkStringType(context, sites.to_str_checked, this);
}
/** rb_check_array_type
*
* Returns the result of trying to convert this object to an Array with "to_ary".
*/
@Override
public IRubyObject checkArrayType() {
Ruby runtime = metaClass.runtime;
ThreadContext context = runtime.getCurrentContext();
BasicObjectSites sites = sites(context);
return TypeConverter.checkArrayType(context, sites.to_ary_checked, this);
}
/**
* @see IRubyObject#toJava
*/
@Override
public <T> T toJava(Class<T> target) {
return defaultToJava(target);
}
final <T> T defaultToJava(Class<T> target) {
// for callers that unconditionally pass null retval type (JRUBY-4737)
if (target == void.class) return null;
final Object value = unwrap_java_object();
if (value != null) {
// ensure the object is associated with the wrapper we found it in,
// so that if it comes back we don't re-wrap it
if (target.isAssignableFrom(value.getClass())) {
getRuntime().getJavaSupport().getObjectProxyCache().put(value, this);
return (T) value;
}
}
else if (JavaUtil.isDuckTypeConvertable(getClass(), target)) {
synchronized (this) {
if (unwrap_java_object() != null) { // double check under lock
return defaultToJava(target); // concurrent proxy interface impl initialization
}
return JavaUtil.convertProcToInterface(getRuntime().getCurrentContext(), this, target);
}
}
else if (!target.isAssignableFrom(getClass())) {
throw typeError(getRuntime().getCurrentContext(), "cannot convert instance of ", this, " to " + target);
}
return (T) this;
}
private Object unwrap_java_object() {
final Object innerWrapper = dataGetStruct(); // java_object
if (innerWrapper instanceof JavaProxy) { // for interface impls
return ((JavaProxy) innerWrapper).getObject(); // never null
}
return null;
}
@Override
public IRubyObject dup() {
if (isSpecialObject()) return this;
ThreadContext context = getRuntime().getCurrentContext();
IRubyObject dup = metaClass.getRealClass().allocate(context);
initCopy(context, dup, this);
sites(context).initialize_dup.call(context, dup, dup, this);
return dup;
}
/** init_copy
*
* Initializes a copy with variable and special instance variable
* information, and then call the initialize_copy Ruby method.
*/
private static void initCopy(ThreadContext context, IRubyObject clone, IRubyObject original) {
assert !clone.isFrozen() : "frozen object (" + clone.getMetaClass().getName(context) + ") allocated";
original.copySpecialInstanceVariables(clone);
if (original.hasVariables()) {
clone.syncVariables(original);
((RubyBasicObject) clone).dupFinalizer(context);
}
if (original instanceof RubyModule) {
RubyModule cloneMod = (RubyModule)clone;
cloneMod.syncConstants((RubyModule)original);
cloneMod.syncClassVariables((RubyModule)original);
cloneMod.initializeCopiedModule(context, original);
}
}
protected static boolean OBJ_INIT_COPY(IRubyObject obj, IRubyObject orig) {
if (obj == orig) return false;
objInitCopy(obj, orig);
return true;
}
protected static void objInitCopy(IRubyObject obj, IRubyObject orig) {
if (obj == orig) return;
// FIXME: booooo!
((RubyBasicObject)obj).checkFrozen();
// Not implemented
// checkTrusted();
if (obj.getClass() != orig.getClass() || obj.getMetaClass().getRealClass() != orig.getMetaClass().getRealClass()) {
throw typeError(obj.getRuntime().getCurrentContext(), "initialize_copy should take same class object");
}
}
/**
* Lots of MRI objects keep their state in non-lookupable ivars
* (e:g. Range, Struct, etc). This method is responsible for
* dupping our java field equivalents
*/
@Override
public void copySpecialInstanceVariables(IRubyObject clone) {
}
@Override
public IRubyObject rbClone() {
var context = getRuntime().getCurrentContext();
return rbCloneInternal(context, context.nil);
}
public IRubyObject rbClone(ThreadContext context, IRubyObject maybeOpts) {
IRubyObject kwfreeze = ArgsUtil.getFreezeOpt(context, maybeOpts);
return rbCloneInternal(context, kwfreeze);
}
// MRI: rb_dup_setup
protected RubyBasicObject dupSetup(ThreadContext context, RubyBasicObject dup) {
initCopy(context, dup, this);
sites(context).initialize_dup.call(context, dup, dup, this);
return dup;
}
// MRI: rb_clone_setup
protected RubyBasicObject cloneSetup(ThreadContext context, RubyBasicObject clone, IRubyObject freeze) {
clone.setMetaClass(getSingletonClassCloneAndAttach(context, clone));
initCopy(context, clone, this);
if (freeze == context.nil) {
sites(context).initialize_clone.call(context, clone, clone, this);
if (this instanceof RubyString str && str.isChilled()) {
if (str.isChilledLiteral()) {
((RubyString) clone).chill();
} else {
((RubyString) clone).chill_symbol_string();
}
} else if (isFrozen()) {
clone.setFrozen(true);
}
} else { // will always be true or false (MRI has bulletproofing to catch odd values (rb_bug explodes).
// FIXME: MRI uses C module variables to make a single hash ever for this setup. We build every time.
RubyHash opts = RubyHash.newHash(context.runtime, asSymbol(context, "freeze"), freeze);
context.callInfo = CALL_KEYWORD;
sites(context).initialize_clone.call(context, clone, clone, this, opts);
if (freeze == context.tru) clone.freeze(context);
if (clone.getMetaClass().isSingleton()) clone.getMetaClass().setFrozen(clone.isFrozen());
}
return clone;
}
// freeze (false, true, nil)
private RubyBasicObject rbCloneInternal(ThreadContext context, IRubyObject freeze) {
// MRI: immutable_obj_clone
if (isSpecialObject()) {
if (freeze == context.fals) throw argumentError(context, str(context.runtime, "can't unfreeze ", types(context.runtime, getType())));
return this;
}
// We're cloning ourselves, so we know the result should be a RubyObject
RubyBasicObject clone = (RubyBasicObject) metaClass.getRealClass().allocate(context);