-
Notifications
You must be signed in to change notification settings - Fork 914
/
RubySymbol.java
1579 lines (1305 loc) · 55.8 KB
/
RubySymbol.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 Alan Moore <alan_moore@gmx.net>
* 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 Joey Gibson <joey@joeygibson.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2006 Derek Berner <derek.berner@state.nm.us>
* Copyright (C) 2006 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 org.jcodings.Encoding;
import org.jcodings.specific.ASCIIEncoding;
import org.jcodings.specific.USASCIIEncoding;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.compiler.Constantizable;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.ArgumentDescriptor;
import org.jruby.runtime.Block;
import org.jruby.runtime.BlockBody;
import org.jruby.runtime.CallSite;
import org.jruby.runtime.CallType;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.ContextAwareBlockBody;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.Signature;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.callsite.RefinedCachingCallSite;
import org.jruby.runtime.encoding.EncodingCapable;
import org.jruby.runtime.encoding.MarshalEncoding;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.runtime.opto.OptoFactory;
import org.jruby.util.ByteList;
import org.jruby.util.IdUtil;
import org.jruby.util.PerlHash;
import org.jruby.util.SipHashInline;
import org.jruby.util.SymbolNameType;
import org.jruby.util.TypeConverter;
import java.lang.ref.WeakReference;
import java.util.concurrent.locks.ReentrantLock;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.ids;
import static org.jruby.util.StringSupport.CR_7BIT;
import static org.jruby.util.StringSupport.codeLength;
import static org.jruby.util.StringSupport.codePoint;
import static org.jruby.util.StringSupport.codeRangeScan;
/**
* Represents a Ruby symbol (e.g. :bar)
*/
@JRubyClass(name = "Symbol", include = "Enumerable")
public class RubySymbol extends RubyObject implements MarshalEncoding, EncodingCapable, Constantizable {
@Deprecated
public static final long symbolHashSeedK0 = 5238926673095087190l;
private final String symbol;
private final int id;
private final ByteList symbolBytes;
private final int hashCode;
private String decodedString;
private RubyString rubyString;
private transient Object constant;
private SymbolNameType type;
/**
*
* @param runtime
* @param internedSymbol the String value of the new Symbol. This <em>must</em>
* have been previously interned
* @param symbolBytes the ByteList of the symbol's string representation
*/
private RubySymbol(Ruby runtime, String internedSymbol, ByteList symbolBytes) {
super(runtime, runtime.getSymbol(), false);
assert internedSymbol == internedSymbol.intern() : internedSymbol + " is not interned";
this.symbol = internedSymbol;
if (symbolBytes.getEncoding() != USASCIIEncoding.INSTANCE &&
codeRangeScan(symbolBytes.getEncoding(), symbolBytes) == CR_7BIT) {
symbolBytes = symbolBytes.dup();
symbolBytes.setEncoding(USASCIIEncoding.INSTANCE);
}
this.symbolBytes = symbolBytes;
this.id = runtime.allocSymbolId();
long k0 = Helpers.hashStart(runtime, id);
long hash = runtime.isSiphashEnabled() ? SipHashInline.hash24(
k0, 0, symbolBytes.getUnsafeBytes(),
symbolBytes.getBegin(), symbolBytes.getRealSize()) :
PerlHash.hash(k0, symbolBytes.getUnsafeBytes(),
symbolBytes.getBegin(), symbolBytes.getRealSize());
this.hashCode = (int) hash;
this.type = IdUtil.determineSymbolNameType(runtime, symbolBytes);
setFrozen(true);
}
private RubySymbol(Ruby runtime, String internedSymbol) {
this(runtime, internedSymbol, symbolBytesFromString(runtime, internedSymbol));
}
public static RubyClass createSymbolClass(Ruby runtime) {
RubyClass symbolClass = runtime.defineClass("Symbol", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
RubyClass symbolMetaClass = symbolClass.getMetaClass();
symbolClass.setClassIndex(ClassIndex.SYMBOL);
symbolClass.setReifiedClass(RubySymbol.class);
symbolClass.kindOf = new RubyModule.JavaClassKindOf(RubySymbol.class);
symbolClass.defineAnnotatedMethods(RubySymbol.class);
symbolMetaClass.undefineMethod("new");
symbolClass.includeModule(runtime.getComparable());
return symbolClass;
}
@Override
public ClassIndex getNativeClassIndex() {
return ClassIndex.SYMBOL;
}
/** rb_to_id
*
* @return a String representation of the symbol
*/
@Override
public final String asJavaString() {
return symbol;
}
/**
* Return an id string (e.g. raw ISO-8859_1 charset String) for use with our method tables etc.
*/
public String idString() {
return symbol;
}
/**
* Print a string for internal debugging purposes. This does a half-hearted attempt at representing the string in
* a displayable fashion for for error messages you should use RubyStringBuilder.str + ids + types to build up the
* error message. For identifier strings you should use idString(). For non-identifier strings where you want a
* raw String you should use asJavaString().
*
* @return a String
*/
@Override
public final String toString() {
String decoded = decodedString;
if (decoded == null) {
decodedString = decoded = RubyEncoding.decodeRaw(getBytes());
}
return decoded;
}
public final ByteList getBytes() {
return symbolBytes;
}
/**
* Make an instance variable out of this symbol (e.g. :foo will generate :foo=).
* @return the new symbol
*/
public RubySymbol asWriter() {
ByteList bytes = getBytes();
ByteList dup = bytes.dup(bytes.length() + 1);
dup.append((byte) '=');
return newIDSymbol(metaClass.runtime, dup);
}
public RubySymbol asInstanceVariable() {
ByteList bytes = getBytes();
ByteList dup = new ByteList(bytes.length() + 1);
dup.setEncoding(ByteList.safeEncoding(bytes.getEncoding()));
dup.append((byte) '@');
dup.append(bytes);
return newIDSymbol(metaClass.runtime, dup);
}
/**
* When we know we need an entry in the symbol table because the provided name will be needed to be
* accessed as a valid identifier later we can call this. If there is not already an entry we will
* return a new symbol. Otherwise, the existing entry.
*
* @param name to get symbol table entry for (it may be a symbol already)
* @return the symbol table entry.
*/
public static RubySymbol retrieveIDSymbol(IRubyObject name) {
return name instanceof RubySymbol ?
(RubySymbol) name : newIDSymbol(name.getRuntime(), name.convertToString().getByteList());
}
/**
* Retrieve an ID symbol but call the handler before any new symbol is added to the symbol table.
* This can be used for verifying the symbol is valid.
*
* @param name to get symbol table entry for (it may be a symbol already)
* @return the symbol table entry.
*/
public static RubySymbol retrieveIDSymbol(IRubyObject name, ObjBooleanConsumer<RubySymbol> handler) {
if (name instanceof RubySymbol) {
RubySymbol sym = (RubySymbol) name;
handler.accept(sym, false);
return sym;
}
return newIDSymbol(name.getRuntime(), name.convertToString().getByteList(), handler);
}
/**
* RubySymbol is created by passing in a String and bytes are extracted from that. We will
* pass in encoding of that string after construction but before use so it does not forget
* what it is.
*/
public void associateEncoding(Encoding encoding) {
symbolBytes.setEncoding(encoding);
}
/** short circuit for Symbol key comparison
*
*/
@Override
public final boolean eql(IRubyObject other) {
return other == this;
}
/**
* Is the string this constant represents a valid constant identifier name.
*/
public boolean validConstantName() {
return type == SymbolNameType.CONST;
}
/**
* Is the string this constant represents a valid constant identifier name.
*/
public boolean validInstanceVariableName() {
return type == SymbolNameType.INSTANCE;
}
/**
* Is the string this constant represents a valid constant identifier name.
*/
public boolean validClassVariableName() {
return type == SymbolNameType.CLASS;
}
public boolean validLocalVariableName() {
return type == SymbolNameType.LOCAL && !"nil".equals(idString());
}
@Override
public boolean isImmediate() {
return true;
}
@Override
public RubyClass getSingletonClass() {
throw getRuntime().newTypeError("can't define singleton");
}
public static RubySymbol getSymbolLong(Ruby runtime, long id) {
return runtime.getSymbolTable().lookup(id);
}
/* Symbol class methods.
*
*/
@Deprecated
public static RubySymbol newSymbol(Ruby runtime, IRubyObject name) {
if (name instanceof RubySymbol) {
return runtime.getSymbolTable().getSymbol(((RubySymbol) name).getBytes(), false);
} else if (name instanceof RubyString) {
return runtime.getSymbolTable().getSymbol(((RubyString) name).getByteList(), false);
} else {
return newSymbol(runtime, name.asString().getByteList());
}
}
public static RubySymbol newHardSymbol(Ruby runtime, IRubyObject name) {
if (name instanceof RubySymbol) {
return runtime.getSymbolTable().getSymbol(((RubySymbol) name).getBytes(), true);
} else if (name instanceof RubyString) {
return runtime.getSymbolTable().getSymbol(((RubyString) name).getByteList(), true);
}
return newSymbol(runtime, name.asString().getByteList());
}
public static RubySymbol newSymbol(Ruby runtime, String name) {
return runtime.getSymbolTable().getSymbol(name, false);
}
public static RubySymbol newSymbol(Ruby runtime, ByteList bytes) {
return runtime.getSymbolTable().getSymbol(bytes, false);
}
public static RubySymbol newHardSymbol(Ruby runtime, ByteList bytes) {
return runtime.getSymbolTable().getSymbol(bytes, true);
}
public static RubySymbol newHardSymbol(Ruby runtime, ByteList bytes, ObjBooleanConsumer<RubySymbol> handler) {
return runtime.getSymbolTable().getSymbol(bytes, handler, true);
}
public static RubySymbol newHardSymbol(Ruby runtime, String name) {
return runtime.getSymbolTable().getSymbol(name, true);
}
/**
* Return the symbol in the symbol table if it exists, null otherwise.
* This method will not create the symbol if it does not exist.
* @param runtime
* @param bytes
* @return
*/
public static RubySymbol newSymbol(Ruby runtime, ByteList bytes, ObjBooleanConsumer<RubySymbol> handler) {
return runtime.getSymbolTable().getSymbol(bytes, handler, false);
}
@FunctionalInterface
public interface ObjBooleanConsumer<T> {
void accept(T t, boolean b);
}
/**
* Generic identifier symbol creation (or retrieval) method.
*
* @param runtime of this Ruby instance.
* @param bytes to be made into a symbol (or to help retreive existing symbol)
* @return a new or existing symbol
*/
public static RubySymbol newIDSymbol(Ruby runtime, ByteList bytes) {
return newHardSymbol(runtime, bytes);
}
/**
* Generic identifier symbol creation (or retrieval) method that invokes a handler before storing new symbols.
*
* @param runtime of this Ruby instance.
* @param bytes to be made into a symbol (or to help retreive existing symbol)
* @return a new or existing symbol
*/
public static RubySymbol newIDSymbol(Ruby runtime, ByteList bytes, ObjBooleanConsumer<RubySymbol> handler) {
return newHardSymbol(runtime, bytes, handler);
}
/**
* Create a symbol whose intention is to be used as a constant. This will not
* only guarantee a symbol entry in the table but it will also verify the symbol
* conforms as a valid constant identifier.
*
* @param runtime of this Ruby instance.
* @param fqn if this constant symbol is part of a broader chain this is used for full name error reporting.
* @param bytes to be made into a symbol (or to help retreive existing symbol)
* @return a new or existing symbol
*/
public static RubySymbol newConstantSymbol(Ruby runtime, IRubyObject fqn, ByteList bytes) {
if (bytes.length() == 0) {
throw runtime.newNameError(str(runtime, "wrong constant name ", ids(runtime, fqn)), runtime.newSymbol(""));
}
RubySymbol symbol = runtime.newSymbol(bytes);
if (!symbol.validConstantName()) {
throw runtime.newNameError(str(runtime, "wrong constant name ", ids(runtime, fqn)), symbol);
}
return symbol;
}
public static RubySymbol newSymbol(Ruby runtime, String name, Encoding encoding) {
RubySymbol newSymbol = runtime.getSymbolTable().getSymbol(RubyString.encodeBytelist(name, encoding));
return newSymbol;
}
public static RubySymbol newHardSymbol(Ruby runtime, String name, Encoding encoding) {
RubySymbol newSymbol = runtime.getSymbolTable().getSymbol(RubyString.encodeBytelist(name, encoding));
return newSymbol;
}
/**
* @see org.jruby.compiler.Constantizable
*/
@Override
public Object constant() {
return constant == null ?
constant = OptoFactory.newConstantWrapper(IRubyObject.class, this) :
constant;
}
@Override
public IRubyObject inspect() {
return inspect(metaClass.runtime);
}
@JRubyMethod(name = "inspect")
public IRubyObject inspect(ThreadContext context) {
return inspect(context.runtime);
}
final RubyString inspect(final Ruby runtime) {
// TODO: 1.9 rb_enc_symname_p
Encoding resenc = runtime.getDefaultInternalEncoding();
if (resenc == null) resenc = runtime.getDefaultExternalEncoding();
RubyString str = RubyString.newString(runtime, getBytes());
if (!(isPrintable(runtime) && (resenc.equals(getBytes().getEncoding()) || str.isAsciiOnly()) &&
isSymbolName(symbol))) {
str = str.inspect(runtime);
}
ByteList result = new ByteList(str.getByteList().getRealSize() + 1);
result.setEncoding(str.getEncoding());
result.append((byte)':');
result.append(str.getByteList());
return RubyString.newString(runtime, result);
}
@Deprecated
public IRubyObject inspect19(ThreadContext context) {
return inspect(context);
}
@Override
public IRubyObject to_s() {
return to_s(metaClass.runtime);
}
@JRubyMethod(name = "to_s")
public IRubyObject to_s(ThreadContext context) {
return to_s(context.runtime);
}
final RubyString to_s(Ruby runtime) {
return RubyString.newStringShared(runtime, getBytes());
}
@JRubyMethod(name = "name")
public IRubyObject name(ThreadContext context) {
// FIXME: A race here where two in-flight to_s on same symbol can return a different instance.
if (rubyString == null) {
rubyString = RubyString.newStringShared(context.runtime, getBytes());
rubyString.setFrozen(true);
}
return rubyString;
}
public IRubyObject id2name() {
return to_s(metaClass.runtime);
}
@JRubyMethod
public IRubyObject id2name(ThreadContext context) {
return to_s(context);
}
@Override
public RubyString asString() {
return to_s(metaClass.runtime);
}
@JRubyMethod(name = "===")
@Override
public IRubyObject op_eqq(ThreadContext context, IRubyObject other) {
return RubyBoolean.newBoolean(context, this == other);
}
@JRubyMethod(name = "==")
@Override
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
return RubyBoolean.newBoolean(context, this == other);
}
@Deprecated
@Override
public RubyFixnum hash() {
return metaClass.runtime.newFixnum(hashCode());
}
@JRubyMethod
public RubyFixnum hash(ThreadContext context) {
return context.runtime.newFixnum(hashCode());
}
@Override
public int hashCode() {
return hashCode;
}
public int getId() {
return id;
}
@Override
public boolean equals(Object other) {
return other == this;
}
/**
* @see RubyBasicObject#compareTo(IRubyObject)
*/
@Override
public int compareTo(final IRubyObject that) {
// NOTE: we're expecting RubySymbol to always be Java sortable
if ( that instanceof RubySymbol ) {
return this.symbol.compareTo( ((RubySymbol) that).symbol );
}
return 0; // our <=> contract is to return 0 on non-comparables
}
@JRubyMethod(name = { "to_sym", "intern" })
public IRubyObject to_sym() { return this; }
@Deprecated
public IRubyObject to_sym19() { return this; }
private RubyString newShared(Ruby runtime) {
return RubyString.newStringShared(runtime, symbolBytes);
}
@JRubyMethod(name = {"succ", "next"})
public IRubyObject succ(ThreadContext context) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).succ(context).asString().getByteList());
}
@JRubyMethod(name = "<=>")
@Override
public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
Ruby runtime = context.runtime;
return !(other instanceof RubySymbol) ? context.nil :
newShared(runtime).op_cmp(context, ((RubySymbol)other).newShared(runtime));
}
@JRubyMethod
public IRubyObject casecmp(ThreadContext context, IRubyObject other) {
Ruby runtime = context.runtime;
return !(other instanceof RubySymbol) ? context.nil :
newShared(runtime).casecmp(context, ((RubySymbol) other).newShared(runtime));
}
@JRubyMethod(name = "casecmp?")
public IRubyObject casecmp_p(ThreadContext context, IRubyObject other) {
Ruby runtime = context.runtime;
return !(other instanceof RubySymbol) ? context.nil :
newShared(runtime).casecmp_p(context, ((RubySymbol) other).newShared(runtime));
}
@JRubyMethod(name = "=~")
@Override
public IRubyObject op_match(ThreadContext context, IRubyObject other) {
return newShared(context.runtime).op_match(context, other);
}
@JRubyMethod(name = "match")
public IRubyObject match_m(ThreadContext context, IRubyObject other, Block block) {
return newShared(context.runtime).match19(context, other, block);
}
@JRubyMethod(name = "match")
public IRubyObject match_m(ThreadContext context, IRubyObject other, IRubyObject pos, Block block) {
return newShared(context.runtime).match19(context, other, pos, block);
}
@JRubyMethod(name = "match", required = 1, rest = true, checkArity = false)
public IRubyObject match_m(ThreadContext context, IRubyObject[] args, Block block) {
return newShared(context.runtime).match19(context, args, block);
}
@JRubyMethod(name = "match?")
public IRubyObject match_p(ThreadContext context, IRubyObject other) {
return newShared(context.runtime).match_p(context, other);
}
@JRubyMethod(name = "match?")
public IRubyObject match_p(ThreadContext context, IRubyObject other, IRubyObject pos) {
return newShared(context.runtime).match_p(context, other, pos);
}
@JRubyMethod(name = {"[]", "slice"})
public IRubyObject op_aref(ThreadContext context, IRubyObject arg) {
return newShared(context.runtime).op_aref(context, arg);
}
@JRubyMethod(name = {"[]", "slice"})
public IRubyObject op_aref(ThreadContext context, IRubyObject arg1, IRubyObject arg2) {
return newShared(context.runtime).op_aref(context, arg1, arg2);
}
@JRubyMethod(name = {"length", "size"})
public IRubyObject length() {
final Ruby runtime = metaClass.runtime;
return RubyFixnum.newFixnum(runtime, newShared(runtime).strLength());
}
@JRubyMethod(name = "empty?")
public IRubyObject empty_p(ThreadContext context) {
return newShared(context.runtime).empty_p(context);
}
@JRubyMethod(name = "start_with?")
public IRubyObject start_with_p(ThreadContext context) {
return context.fals;
}
@JRubyMethod(name = "start_with?")
public IRubyObject start_with_p(ThreadContext context, IRubyObject arg) {
if (arg instanceof RubyRegexp) {
return ((RubyRegexp) arg).startsWith(context, to_s(context.runtime)) ? context.tru : context.fals;
}
return to_s(context.runtime).startsWith(arg.convertToString()) ? context.tru : context.fals;
}
@JRubyMethod(name = "start_with?", rest = true)
public IRubyObject start_with_p(ThreadContext context, IRubyObject[] args) {
for (int i = 0; i < args.length; i++) {
if (start_with_p(context, args[i]).isTrue()) return context.tru;
}
return context.fals;
}
@JRubyMethod(name = "end_with?")
public IRubyObject end_with_p(ThreadContext context) {
return context.fals;
}
@JRubyMethod(name = "end_with?")
public IRubyObject end_with_p(ThreadContext context, IRubyObject arg) {
return to_s(context.runtime).endWith(arg) ? context.tru : context.fals;
}
@JRubyMethod(name = "end_with?", rest = true)
public IRubyObject end_with_p(ThreadContext context, IRubyObject[]args) {
RubyString str = to_s(context.runtime);
for (int i = 0; i < args.length; i++) {
if (str.endWith(args[i])) return context.tru;
}
return context.fals;
}
@JRubyMethod
public IRubyObject upcase(ThreadContext context) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).upcase(context).getByteList());
}
@JRubyMethod
public IRubyObject upcase(ThreadContext context, IRubyObject arg) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).upcase(context, arg).getByteList());
}
@JRubyMethod
public IRubyObject upcase(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).upcase(context, arg0, arg1).getByteList());
}
@JRubyMethod
public IRubyObject downcase(ThreadContext context) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).downcase(context).getByteList());
}
@JRubyMethod
public IRubyObject downcase(ThreadContext context, IRubyObject arg) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).downcase(context, arg).getByteList());
}
@JRubyMethod
public IRubyObject downcase(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).downcase(context, arg0, arg1).getByteList());
}
@JRubyMethod
public IRubyObject swapcase(ThreadContext context) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).swapcase(context).getByteList());
}
@JRubyMethod
public IRubyObject swapcase(ThreadContext context, IRubyObject arg) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).swapcase(context, arg).getByteList());
}
@JRubyMethod
public IRubyObject swapcase(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).swapcase(context, arg0, arg1).getByteList());
}
@JRubyMethod
public IRubyObject capitalize(ThreadContext context) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).capitalize(context).getByteList());
}
@JRubyMethod
public IRubyObject capitalize(ThreadContext context, IRubyObject arg) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).capitalize(context, arg).getByteList());
}
@JRubyMethod
public IRubyObject capitalize(ThreadContext context, IRubyObject arg0, IRubyObject arg1) {
Ruby runtime = context.runtime;
return newSymbol(runtime, newShared(runtime).capitalize(context, arg0, arg1).getByteList());
}
@JRubyMethod
public IRubyObject encoding(ThreadContext context) {
return context.runtime.getEncodingService().getEncoding(getEncoding());
}
@JRubyMethod
public IRubyObject to_proc(ThreadContext context) {
BlockBody body = new SymbolProcBody(context.runtime, symbol);
return RubyProc.newProc(context.runtime,
new Block(body, Block.NULL_BLOCK.getBinding()),
Block.Type.LAMBDA);
}
public IRubyObject toRefinedProc(ThreadContext context, StaticScope scope) {
BlockBody body = new SymbolProcBody(context.runtime, symbol, scope);
return RubyProc.newProc(context.runtime,
new Block(body, Block.NULL_BLOCK.getBinding()),
Block.Type.LAMBDA);
}
private static boolean isIdentStart(char c) {
return ((c >= 'a' && c <= 'z')|| (c >= 'A' && c <= 'Z') || c == '_' || !(c < 128));
}
private static boolean isIdentChar(char c) {
return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || c == '_' || !(c < 128));
}
private static boolean isIdentifier(String s) {
if (s.isEmpty() || !isIdentStart(s.charAt(0))) return false;
for (int i = 1; i < s.length(); i++) {
if (!isIdentChar(s.charAt(i))) return false;
}
return true;
}
/**
* is_special_global_name from parse.c.
* @param s
* @return
*/
private static boolean isSpecialGlobalName(String s) {
if (s.isEmpty()) return false;
int length = s.length();
switch (s.charAt(0)) {
case '~': case '*': case '$': case '?': case '!': case '@': case '/': case '\\':
case ';': case ',': case '.': case '=': case ':': case '<': case '>': case '\"':
case '&': case '`': case '\'': case '+': case '0':
return length == 1;
case '-':
return (length == 1 || (length == 2 && isIdentChar(s.charAt(1))));
default:
for (int i = 0; i < length; i++) {
if (!Character.isDigit(s.charAt(i))) return false;
}
}
return true;
}
private boolean isPrintable(final Ruby runtime) {
ByteList symbolBytes = getBytes();
int p = symbolBytes.getBegin();
int end = p + symbolBytes.getRealSize();
byte[] bytes = symbolBytes.getUnsafeBytes();
Encoding enc = symbolBytes.getEncoding();
while (p < end) {
int c = codePoint(runtime, enc, bytes, p, end);
if (!enc.isPrint(c)) return false;
p += codeLength(enc, c);
}
return true;
}
private static boolean isSymbolName(final String str) {
if (str == null || str.isEmpty()) return false;
int length = str.length();
char c = str.charAt(0);
return isSymbolNameCommon(str, c, length) ||
(c == '!' && (length == 1 ||
(length == 2 && (str.charAt(1) == '~' || str.charAt(1) == '=')))) ||
isSymbolLocal(str, c, length);
}
private static boolean isSymbolNameCommon(final String str, final char first, final int length) {
switch (first) {
case '$':
if (length > 1 && isSpecialGlobalName(str.substring(1))) return true;
return isIdentifier(str.substring(1));
case '@':
int offset = 1;
if (length >= 2 && str.charAt(1) == '@') offset++;
return isIdentifier(str.substring(offset));
case '<':
return (length == 1 || (length == 2 && (str.equals("<<") || str.equals("<="))) ||
(length == 3 && str.equals("<=>")));
case '>':
return (length == 1) || (length == 2 && (str.equals(">>") || str.equals(">=")));
case '=':
return ((length == 2 && (str.equals("==") || str.equals("=~"))) ||
(length == 3 && str.equals("===")));
case '*':
return (length == 1 || (length == 2 && str.equals("**")));
case '+':
return (length == 1 || (length == 2 && str.equals("+@")));
case '-':
return (length == 1 || (length == 2 && str.equals("-@")));
case '|': case '^': case '&': case '/': case '%': case '~': case '`':
return length == 1;
case '[':
return str.equals("[]") || str.equals("[]=");
}
return false;
}
private static boolean isSymbolLocal(final String str, final char first, final int length) {
if (!isIdentStart(first)) return false;
boolean localID = isIdentStart(first);
int last = 1;
for (; last < length; last++) {
char d = str.charAt(last);
if (!isIdentChar(d)) break;
}
if (last == length) return true;
if (localID && last == length - 1) {
char d = str.charAt(last);
return d == '!' || d == '?' || d == '=';
}
return false;
}
@JRubyMethod(meta = true)
public static IRubyObject all_symbols(ThreadContext context, IRubyObject recv) {
return context.runtime.getSymbolTable().all_symbols();
}
@Deprecated
public static IRubyObject all_symbols(IRubyObject recv) {
return recv.getRuntime().getSymbolTable().all_symbols();
}
public static RubySymbol unmarshalFrom(UnmarshalStream input, UnmarshalStream.MarshalState state) throws java.io.IOException {
ByteList byteList = input.unmarshalString();
byteList.setEncoding(ASCIIEncoding.INSTANCE);
// Extra complicated interaction...
// We initially set to binary as newSymbol will make it US-ASCII if possible and code below will set explicit
// encoding otherwise. Motivation here is binary is capable of being walked during symbol type calculation
// (and at this point the bytelist can be data of any encoding without us knowing what). The proper type
// calculation will happen for non-US-ASCII below when it decodes the encoding. setEncoding will recalculate
// symbol type properly. This is all to work around registerLinkTarget being an ordered list. So a symbol
// retrieved while decoding the encoding would make this symbol get registered out of order...
// Need symbol to register before encoding, so pass in a lambda for remaining unmarshal logic
RubySymbol result = newSymbol(input.getRuntime(), byteList,
(sym, newSym) -> {
// get encoding from stream and set into symbol
if (state != null && state.isIvarWaiting()) {
try {
input.unmarshalInt(); // throw-away, always single ivar of encoding
IRubyObject value = input.unmarshalObject();
Encoding enc = input.symbolToEncoding(sym, value);
if (enc == null) throw new RuntimeException("BUG: No encoding found in marshal stream");
// only change encoding if the symbol has been newly-created
if (newSym) sym.setEncoding(enc);
state.setIvarWaiting(false);
} catch (Throwable t) {
Helpers.throwException(t);
}
}
});
return result;
}
@Override
public <T> T toJava(Class<T> target) {
if (target == String.class || target == CharSequence.class) {
return target.cast(symbol);
}
return super.toJava(target);
}
public static ByteList symbolBytesFromString(Ruby runtime, String internedSymbol) {
return new ByteList(ByteList.plain(internedSymbol), USASCIIEncoding.INSTANCE, false);
}
@Override
public Encoding getEncoding() {
return getBytes().getEncoding();
}
@Override
public void setEncoding(Encoding e) {
getBytes().setEncoding(e);
type = IdUtil.determineSymbolNameType(getRuntime(), getBytes());
}
public static final class SymbolTable {
static final int DEFAULT_INITIAL_CAPACITY = 1 << 10; // *must* be power of 2!
static final int MAXIMUM_CAPACITY = 1 << 16; // enough for a 64k buckets; if you need more than this, something's wrong
static final float DEFAULT_LOAD_FACTOR = 0.75f;
private final ReentrantLock tableLock = new ReentrantLock();
private volatile SymbolEntry[] symbolTable;
private int size;
private int threshold;
private final float loadFactor;
private final Ruby runtime;
public SymbolTable(Ruby runtime) {
this.runtime = runtime;
this.loadFactor = DEFAULT_LOAD_FACTOR;
this.threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
this.symbolTable = new SymbolEntry[DEFAULT_INITIAL_CAPACITY];
}