/
RubyKernel.java
1121 lines (927 loc) · 50.9 KB
/
RubyKernel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2004-2005 Charles O Nutter <headius@headius.com>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2005 Kiel Hodges <jruby-devel@selfsosoft.com>
* Copyright (C) 2006 Evan Buswell <evan@heron.sytes.net>
* Copyright (C) 2006 Ola Bini <ola@ologix.com>
* Copyright (C) 2006 Michael Studman <codehaus@michaelstudman.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
* Copyright (C) 2007 Nick Sieger <nicksieger@gmail.com>
* Copyright (C) 2008 Joseph LaFata <joe@quibb.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 CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Random;
import static org.jruby.RubyEnumerator.enumeratorize;
import static org.jruby.anno.FrameField.*;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.evaluator.ASTInterpreter;
import org.jruby.exceptions.JumpException;
import org.jruby.exceptions.MainExitException;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.JumpTarget;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Binding;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.Frame;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import static org.jruby.runtime.Visibility.*;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.load.IAutoloadMethod;
import org.jruby.runtime.load.LoadService;
import org.jruby.util.ByteList;
import org.jruby.util.IdUtil;
import org.jruby.util.TypeConverter;
/**
* Note: For CVS history, see KernelModule.java.
*/
@JRubyModule(name="Kernel")
public class RubyKernel {
public final static Class<?> IRUBY_OBJECT = IRubyObject.class;
public static RubyModule createKernelModule(Ruby runtime) {
RubyModule module = runtime.defineModule("Kernel");
runtime.setKernel(module);
module.defineAnnotatedMethods(RubyKernel.class);
module.defineAnnotatedMethods(RubyObject.class);
runtime.setRespondToMethod(module.searchMethod("respond_to?"));
module.setFlag(RubyObject.USER7_F, false); //Kernel is the only Module that doesn't need an implementor
return module;
}
@JRubyMethod(name = "at_exit", frame = true, module = true, visibility = PRIVATE)
public static IRubyObject at_exit(ThreadContext context, IRubyObject recv, Block block) {
return context.getRuntime().pushExitBlock(context.getRuntime().newProc(Block.Type.PROC, block));
}
@JRubyMethod(name = "autoload?", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject autoload_p(ThreadContext context, final IRubyObject recv, IRubyObject symbol) {
Ruby runtime = context.getRuntime();
RubyModule module = recv instanceof RubyModule ? (RubyModule) recv : runtime.getObject();
String name = module.getName() + "::" + symbol.asJavaString();
IAutoloadMethod autoloadMethod = runtime.getLoadService().autoloadFor(name);
if (autoloadMethod == null) return runtime.getNil();
return runtime.newString(autoloadMethod.file());
}
@JRubyMethod(name = "autoload", required = 2, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject autoload(final IRubyObject recv, IRubyObject symbol, final IRubyObject file) {
Ruby runtime = recv.getRuntime();
final LoadService loadService = runtime.getLoadService();
String nonInternedName = symbol.asJavaString();
if (!IdUtil.isValidConstantName(nonInternedName)) {
throw runtime.newNameError("autoload must be constant name", nonInternedName);
}
if (!(file instanceof RubyString)) throw runtime.newTypeError(file, runtime.getString());
RubyString fileString = file.convertToString();
if (fileString.isEmpty()) {
throw runtime.newArgumentError("empty file name");
}
final String baseName = symbol.asJavaString().intern(); // interned, OK for "fast" methods
final RubyModule module = recv instanceof RubyModule ? (RubyModule) recv : runtime.getObject();
String nm = module.getName() + "::" + baseName;
IRubyObject existingValue = module.fastFetchConstant(baseName);
if (existingValue != null && existingValue != RubyObject.UNDEF) return runtime.getNil();
module.fastStoreConstant(baseName, RubyObject.UNDEF);
loadService.addAutoload(nm, new IAutoloadMethod() {
public String file() {
return file.toString();
}
/**
* @see org.jruby.runtime.load.IAutoloadMethod#load(Ruby, String)
*/
public IRubyObject load(Ruby runtime, String name) {
boolean required = loadService.require(file());
// File to be loaded by autoload has already been or is being loaded.
if (!required) return null;
return module.fastGetConstant(baseName);
}
});
return runtime.getNil();
}
@JRubyMethod(name = "method_missing", rest = true, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject method_missing(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
if (args.length == 0 || !(args[0] instanceof RubySymbol)) throw runtime.newArgumentError("no id given");
Visibility lastVis = context.getLastVisibility();
CallType lastCallType = context.getLastCallType();
// create a lightweight thunk
IRubyObject msg = new RubyNameError.RubyNameErrorMessage(runtime,
recv,
args[0],
lastVis,
lastCallType);
final IRubyObject[]exArgs;
final RubyClass exc;
if (lastCallType != CallType.VARIABLE) {
exc = runtime.getNoMethodError();
exArgs = new IRubyObject[]{msg, args[0], RubyArray.newArrayNoCopy(runtime, args, 1)};
} else {
exc = runtime.getNameError();
exArgs = new IRubyObject[]{msg, args[0]};
}
throw new RaiseException((RubyException)exc.newInstance(context, exArgs, Block.NULL_BLOCK));
}
@JRubyMethod(name = "abort", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject abort(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if(args.length == 1) {
context.getRuntime().getGlobalVariables().get("$stderr").callMethod(context,"puts",args[0]);
}
throw new MainExitException(1,true);
}
@JRubyMethod(name = "Array", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_array(ThreadContext context, IRubyObject recv, IRubyObject object) {
IRubyObject value = object.checkArrayType();
if (value.isNil()) {
if (object.getMetaClass().searchMethod("to_a").getImplementationClass() != context.getRuntime().getKernel()) {
value = object.callMethod(context, "to_a");
if (!(value instanceof RubyArray)) throw context.getRuntime().newTypeError("`to_a' did not return Array");
return value;
} else {
return context.getRuntime().newArray(object);
}
}
return value;
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv) {
return RuntimeHelpers.invoke(context, context.getRuntime().getComplex(), "convert");
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return RuntimeHelpers.invoke(context, context.getRuntime().getComplex(), "convert", arg);
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return RuntimeHelpers.invoke(context, context.getRuntime().getComplex(), "convert", arg0, arg1);
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv) {
return RuntimeHelpers.invoke(context, context.getRuntime().getRational(), "convert");
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg) {
return RuntimeHelpers.invoke(context, context.getRuntime().getRational(), "convert", arg);
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return RuntimeHelpers.invoke(context, context.getRuntime().getRational(), "convert", arg0, arg1);
}
@JRubyMethod(name = "Float", module = true, visibility = PRIVATE)
public static RubyFloat new_float(IRubyObject recv, IRubyObject object) {
if(object instanceof RubyFixnum){
return RubyFloat.newFloat(object.getRuntime(), ((RubyFixnum)object).getDoubleValue());
}else if(object instanceof RubyFloat){
return (RubyFloat)object;
}else if(object instanceof RubyBignum){
return RubyFloat.newFloat(object.getRuntime(), RubyBignum.big2dbl((RubyBignum)object));
}else if(object instanceof RubyString){
if(((RubyString)object).getByteList().realSize == 0){ // rb_cstr_to_dbl case
throw recv.getRuntime().newArgumentError("invalid value for Float(): " + object.inspect());
}
return RubyNumeric.str2fnum(recv.getRuntime(),(RubyString)object,true);
}else if(object.isNil()){
throw recv.getRuntime().newTypeError("can't convert nil into Float");
} else {
RubyFloat rFloat = (RubyFloat)TypeConverter.convertToType(object, recv.getRuntime().getFloat(), "to_f");
if (Double.isNaN(rFloat.getDoubleValue())) throw recv.getRuntime().newArgumentError("invalid value for Float()");
return rFloat;
}
}
@JRubyMethod(name = "Integer", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_integer(ThreadContext context, IRubyObject recv, IRubyObject object) {
if (object instanceof RubyFloat) {
double val = ((RubyFloat)object).getDoubleValue();
if (val > (double) RubyFixnum.MAX && val < (double) RubyFixnum.MIN) {
return RubyNumeric.dbl2num(context.getRuntime(),((RubyFloat)object).getDoubleValue());
}
} else if (object instanceof RubyFixnum || object instanceof RubyBignum) {
return object;
} else if (object instanceof RubyString) {
return RubyNumeric.str2inum(context.getRuntime(),(RubyString)object,0,true);
}
IRubyObject tmp = TypeConverter.convertToType(object, context.getRuntime().getInteger(), "to_int", false);
if (tmp.isNil()) return object.convertToInteger("to_i");
return tmp;
}
@JRubyMethod(name = "String", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_string(ThreadContext context, IRubyObject recv, IRubyObject object) {
return TypeConverter.convertToType(object, context.getRuntime().getString(), "to_s");
}
/** rb_f_putc
*/
@JRubyMethod(name = "putc", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject putc(ThreadContext context, IRubyObject recv, IRubyObject ch) {
return RubyFixnum.newFixnum(context.getRuntime(), writeBytes(ch));
}
private static int writeBytes(IRubyObject str) {
ByteList byteList = str.asString().getByteList();
System.out.write(byteList.bytes, byteList.begin, byteList.realSize);
return byteList.realSize;
}
private static int writeChar(char ch) {
System.out.write(ch);
return 1;
}
@JRubyMethod(name = "puts", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
for (IRubyObject obj : args) {
writeBytes(obj);
writeChar('\n');
}
return context.getRuntime().getNil();
}
@JRubyMethod(name = "p", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject p(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
for (IRubyObject obj : args) {
writeBytes(obj.inspect());
writeChar('\n');
}
return context.getRuntime().getNil();
}
@JRubyMethod(name = "print", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject print(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
for (IRubyObject obj : args) {
writeBytes(obj);
writeChar('\n');
}
return context.getRuntime().getNil();
}
@JRubyMethod(name = "printf", rest = true, module = true, visibility = PRIVATE)
public static IRubyObject printf(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length != 0) {
IRubyObject defout = context.getRuntime().getGlobalVariables().get("$>");
if (!(args[0] instanceof RubyString)) {
defout = args[0];
args = ArgsUtil.popArray(args);
}
defout.callMethod(context, "write", RubyKernel.sprintf(recv, args));
}
return context.getRuntime().getNil();
}
/** Returns value of $_.
*
* @throws TypeError if $_ is not a String or nil.
* @return value of $_ as String.
*/
private static RubyString getLastlineString(ThreadContext context, Ruby runtime) {
IRubyObject line = context.getPreviousFrame().getLastLine();
if (line.isNil()) {
throw runtime.newTypeError("$_ value need to be String (nil given).");
} else if (!(line instanceof RubyString)) {
throw runtime.newTypeError("$_ value need to be String (" + line.getMetaClass().getName() + " given).");
} else {
return (RubyString) line;
}
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject sub_bang(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return getLastlineString(context, context.getRuntime()).sub_bang(context, args, block);
}
@JRubyMethod(name = "sub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject sub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
return getLastlineString(context, context.getRuntime()).sub_bang(context, arg0, block);
}
@JRubyMethod(name = "sub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject sub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
return getLastlineString(context, context.getRuntime()).sub_bang(context, arg0, arg1, block);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.sub_bang(context, args, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "sub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.sub_bang(context, arg0, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "sub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject sub(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.sub_bang(context, arg0, arg1, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject gsub_bang(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return getLastlineString(context, context.getRuntime()).gsub_bang(context, args, block);
}
@JRubyMethod(name = "gsub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject gsub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
return getLastlineString(context, context.getRuntime()).gsub_bang(context, arg0, block);
}
@JRubyMethod(name = "gsub!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject gsub_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
return getLastlineString(context, context.getRuntime()).gsub_bang(context, arg0, arg1, block);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the one or two-arg versions.
*/
public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.gsub_bang(context, args, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "gsub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.gsub_bang(context, arg0, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "gsub", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject gsub(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, Block block) {
RubyString str = (RubyString) getLastlineString(context, context.getRuntime()).dup();
if (!str.gsub_bang(context, arg0, arg1, block).isNil()) {
context.getPreviousFrame().setLastLine(str);
}
return str;
}
@JRubyMethod(name = "chop!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject chop_bang(ThreadContext context, IRubyObject recv, Block block) {
return getLastlineString(context, context.getRuntime()).chop_bang(context);
}
@JRubyMethod(name = "chop", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject chop(ThreadContext context, IRubyObject recv, Block block) {
RubyString str = getLastlineString(context, context.getRuntime());
if (str.getByteList().realSize > 0) {
str = (RubyString) str.dup();
str.chop_bang(context);
context.getPreviousFrame().setLastLine(str);
}
return str;
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the zero or one-arg versions.
*/
public static IRubyObject chomp_bang(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return getLastlineString(context, context.getRuntime()).chomp_bang(args);
}
@JRubyMethod(name = "chomp!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject chomp_bang(ThreadContext context, IRubyObject recv) {
return getLastlineString(context, context.getRuntime()).chomp_bang(context);
}
@JRubyMethod(name = "chomp!", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject chomp_bang(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
return getLastlineString(context, context.getRuntime()).chomp_bang(context, arg0);
}
/**
* Variable-arity version for compatibility. Not bound to Ruby.
* @deprecated Use the zero or one-arg versions.
*/
public static IRubyObject chomp(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
RubyString str = getLastlineString(context, context.getRuntime());
RubyString dup = (RubyString) str.dup();
if (dup.chomp_bang(args).isNil()) {
return str;
}
context.getPreviousFrame().setLastLine(dup);
return dup;
}
@JRubyMethod(name = "chomp", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject chomp(ThreadContext context, IRubyObject recv) {
RubyString str = getLastlineString(context, context.getRuntime());
RubyString dup = (RubyString) str.dup();
if (dup.chomp_bang(context).isNil()) {
return str;
}
context.getPreviousFrame().setLastLine(dup);
return dup;
}
@JRubyMethod(name = "chomp", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = LASTLINE, compat = CompatVersion.RUBY1_8)
public static IRubyObject chomp(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
RubyString str = getLastlineString(context, context.getRuntime());
RubyString dup = (RubyString) str.dup();
if (dup.chomp_bang(context, arg0).isNil()) {
return str;
}
context.getPreviousFrame().setLastLine(dup);
return dup;
}
/**
* Variable arity version for compatibility. Not bound to a Ruby method.
*
* @param context The thread context for the current thread
* @param recv The receiver of the method (usually a class that has included Kernel)
* @return
* @deprecated Use the versions with zero, one, or two args.
*/
public static IRubyObject split(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return getLastlineString(context, context.getRuntime()).split(context, args);
}
@JRubyMethod(name = "split", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = {LASTLINE, BACKREF}, compat = CompatVersion.RUBY1_8)
public static IRubyObject split(ThreadContext context, IRubyObject recv) {
return getLastlineString(context, context.getRuntime()).split(context);
}
@JRubyMethod(name = "split", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = {LASTLINE, BACKREF}, compat = CompatVersion.RUBY1_8)
public static IRubyObject split(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
return getLastlineString(context, context.getRuntime()).split(context, arg0);
}
@JRubyMethod(name = "split", frame = true, module = true, visibility = PRIVATE, reads = LASTLINE, writes = {LASTLINE, BACKREF}, compat = CompatVersion.RUBY1_8)
public static IRubyObject split(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
return getLastlineString(context, context.getRuntime()).split(context, arg0, arg1);
}
@JRubyMethod(name = "scan", required = 1, frame = true, module = true, visibility = PRIVATE, reads = {LASTLINE, BACKREF}, writes = {LASTLINE, BACKREF}, compat = CompatVersion.RUBY1_8)
public static IRubyObject scan(ThreadContext context, IRubyObject recv, IRubyObject pattern, Block block) {
return getLastlineString(context, context.getRuntime()).scan(context, pattern, block);
}
@JRubyMethod(name = "sleep", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject sleep(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
long milliseconds;
if (args.length == 0) {
// Zero sleeps forever
milliseconds = 0;
} else {
if (!(args[0] instanceof RubyNumeric)) {
throw context.getRuntime().newTypeError("can't convert " + args[0].getMetaClass().getName() + "into time interval");
}
milliseconds = (long) (args[0].convertToFloat().getDoubleValue() * 1000);
if (milliseconds < 0) {
throw context.getRuntime().newArgumentError("time interval must be positive");
} else if (milliseconds == 0) {
// Explicit zero in MRI returns immediately
return context.getRuntime().newFixnum(0);
}
}
long startTime = System.currentTimeMillis();
RubyThread rubyThread = context.getThread();
// Spurious wakeup-loop
do {
long loopStartTime = System.currentTimeMillis();
try {
// We break if we know this sleep was explicitly woken up/interrupted
if (!rubyThread.sleep(milliseconds)) break;
} catch (InterruptedException iExcptn) {
}
milliseconds -= (System.currentTimeMillis() - loopStartTime);
} while (milliseconds > 0);
return context.getRuntime().newFixnum(Math.round((System.currentTimeMillis() - startTime) / 1000.0));
}
// FIXME: Add at_exit and finalizers to exit, then make exit_bang not call those.
@JRubyMethod(name = "exit", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject exit(IRubyObject recv, IRubyObject[] args) {
exit(recv.getRuntime(), args, false);
return recv.getRuntime().getNil(); // not reached
}
@JRubyMethod(name = "exit!", optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject exit_bang(IRubyObject recv, IRubyObject[] args) {
exit(recv.getRuntime(), args, true);
return recv.getRuntime().getNil(); // not reached
}
private static void exit(Ruby runtime, IRubyObject[] args, boolean hard) {
int status = 1;
if (args.length > 0) {
RubyObject argument = (RubyObject)args[0];
if (argument instanceof RubyFixnum) {
status = RubyNumeric.fix2int(argument);
} else {
status = argument.isFalse() ? 1 : 0;
}
}
if (hard) {
throw new MainExitException(status, true);
} else {
throw runtime.newSystemExit(status);
}
}
/** Returns an Array with the names of all global variables.
*
*/
@JRubyMethod(name = "global_variables", module = true, visibility = PRIVATE)
public static RubyArray global_variables(ThreadContext context, IRubyObject recv) {
Ruby runtime = context.getRuntime();
RubyArray globalVariables = runtime.newArray();
for (String globalVariableName : runtime.getGlobalVariables().getNames()) {
globalVariables.append(runtime.newString(globalVariableName));
}
return globalVariables;
}
/** Returns an Array with the names of all local variables.
*
*/
@JRubyMethod(name = "local_variables", module = true, visibility = PRIVATE)
public static RubyArray local_variables(ThreadContext context, IRubyObject recv) {
final Ruby runtime = context.getRuntime();
RubyArray localVariables = runtime.newArray();
for (String name: context.getCurrentScope().getAllNamesInScope()) {
if (IdUtil.isLocal(name)) localVariables.append(runtime.newString(name));
}
return localVariables;
}
@JRubyMethod(name = "binding", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_8)
public static RubyBinding binding(ThreadContext context, IRubyObject recv, Block block) {
return RubyBinding.newBinding(context.getRuntime(), context.currentBinding(recv));
}
@JRubyMethod(name = "binding", module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static RubyBinding binding_1_9(ThreadContext context, IRubyObject recv, Block block) {
return RubyBinding.newBinding(context.getRuntime(), context.currentBinding());
}
@JRubyMethod(name = {"block_given?", "iterator?"}, frame = true, module = true, visibility = PRIVATE)
public static RubyBoolean block_given_p(ThreadContext context, IRubyObject recv, Block block) {
return context.getRuntime().newBoolean(context.getPreviousFrame().getBlock().isGiven());
}
@Deprecated
public static IRubyObject sprintf(IRubyObject recv, IRubyObject[] args) {
return sprintf(recv.getRuntime().getCurrentContext(), recv, args);
}
@JRubyMethod(name = {"sprintf", "format"}, required = 1, rest = true, module = true, visibility = PRIVATE)
public static IRubyObject sprintf(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length == 0) {
throw context.getRuntime().newArgumentError("sprintf must have at least one argument");
}
RubyString str = RubyString.stringValue(args[0]);
RubyArray newArgs = context.getRuntime().newArrayNoCopy(args);
newArgs.shift(context);
return str.op_format(context, newArgs);
}
@JRubyMethod(name = {"raise", "fail"}, optional = 3, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject raise(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
// FIXME: Pass block down?
Ruby runtime = context.getRuntime();
if (args.length == 0) {
IRubyObject lastException = runtime.getGlobalVariables().get("$!");
if (lastException.isNil()) {
throw new RaiseException(runtime, runtime.getRuntimeError(), "", false);
}
throw new RaiseException((RubyException) lastException);
}
IRubyObject exception;
if (args.length == 1) {
if (args[0] instanceof RubyString) {
throw new RaiseException((RubyException)runtime.getRuntimeError().newInstance(context, args, block));
}
if (!args[0].respondsTo("exception")) {
throw runtime.newTypeError("exception class/object expected");
}
exception = args[0].callMethod(context, "exception");
} else {
if (!args[0].respondsTo("exception")) {
throw runtime.newTypeError("exception class/object expected");
}
exception = args[0].callMethod(context, "exception", args[1]);
}
if (!runtime.fastGetClass("Exception").isInstance(exception)) {
throw runtime.newTypeError("exception object expected");
}
if (args.length == 3) {
((RubyException) exception).set_backtrace(args[2]);
}
if (runtime.getDebug().isTrue()) {
printExceptionSummary(context, runtime, (RubyException) exception);
}
throw new RaiseException((RubyException) exception);
}
private static void printExceptionSummary(ThreadContext context, Ruby runtime, RubyException rEx) {
Frame currentFrame = context.getCurrentFrame();
String msg = String.format("Exception `%s' at %s:%s - %s\n",
rEx.getMetaClass(),
currentFrame.getFile(), currentFrame.getLine() + 1,
rEx.to_s());
IRubyObject errorStream = runtime.getGlobalVariables().get("$stderr");
errorStream.callMethod(context, "write", runtime.newString(msg));
}
/**
* Require.
* MRI allows to require ever .rb files or ruby extension dll (.so or .dll depending on system).
* we allow requiring either .rb files or jars.
* @param recv ruby object used to call require (any object will do and it won't be used anyway).
* @param name the name of the file to require
**/
@JRubyMethod(name = "require", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject require(IRubyObject recv, IRubyObject name, Block block) {
Ruby runtime = recv.getRuntime();
if (runtime.getLoadService().require(name.convertToString().toString())) {
return runtime.getTrue();
}
return runtime.getFalse();
}
@JRubyMethod(name = "load", required = 1, optional = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject load(IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = recv.getRuntime();
RubyString file = args[0].convertToString();
boolean wrap = args.length == 2 ? args[1].isTrue() : false;
runtime.getLoadService().load(file.getByteList().toString(), wrap);
return runtime.getTrue();
}
@JRubyMethod(name = "eval", required = 1, optional = 3, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject eval(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
// string to eval
RubyString src = args[0].convertToString();
runtime.checkSafeString(src);
boolean bindingGiven = args.length > 1 && !args[1].isNil();
Binding binding = bindingGiven ? convertToBinding(args[1]) : context.previousBinding();
if (args.length > 2) {
// file given, use it and force it into binding
binding.setFile(args[2].convertToString().toString());
} else {
// file not given
if (bindingGiven) {
// binding given, use binding's file
} else {
// no binding given, use (eval)
binding.setFile("(eval)");
}
}
if (args.length > 3) {
// file given, use it and force it into binding
binding.setLine((int) args[3].convertToInteger().getLongValue());
} else {
// no binding given, use 0 for both
binding.setLine(0);
}
return ASTInterpreter.evalWithBinding(context, src, binding);
}
private static Binding convertToBinding(IRubyObject scope) {
if (scope instanceof RubyBinding) {
return ((RubyBinding)scope).getBinding().clone();
} else {
if (scope instanceof RubyProc) {
return ((RubyProc) scope).getBlock().getBinding().clone();
} else {
// bomb out, it's not a binding or a proc
throw scope.getRuntime().newTypeError("wrong argument type " + scope.getMetaClass() + " (expected Proc/Binding)");
}
}
}
@JRubyMethod(name = "callcc", frame = true, module = true, visibility = PRIVATE)
public static IRubyObject callcc(ThreadContext context, IRubyObject recv, Block block) {
RubyContinuation continuation = new RubyContinuation(context.getRuntime());
return continuation.enter(context, block);
}
@JRubyMethod(name = "caller", optional = 1, frame = true, module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_8)
public static IRubyObject caller(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
int level = args.length > 0 ? RubyNumeric.fix2int(args[0]) : 1;
if (level < 0) {
throw context.getRuntime().newArgumentError("negative level(" + level + ')');
}
return context.createCallerBacktrace(context.getRuntime(), level);
}
@JRubyMethod(name = "caller", optional = 1, frame = true, module = true, visibility = PRIVATE, compat = CompatVersion.RUBY1_9)
public static IRubyObject caller1_9(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
int level = args.length > 0 ? RubyNumeric.fix2int(args[0]) : 1;
if (level < 0) {
throw context.getRuntime().newArgumentError("negative level(" + level + ')');
}
return context.createCallerBacktrace(context.getRuntime(), level);
}
@JRubyMethod(name = "catch", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject rbCatch(ThreadContext context, IRubyObject recv, IRubyObject tag, Block block) {
CatchTarget target = new CatchTarget(tag.asJavaString());
try {
context.pushCatch(target);
return block.yield(context, tag);
} catch (JumpException.ThrowJump tj) {
if (tj.getTarget() == target) return (IRubyObject) tj.getValue();
throw tj;
} finally {
context.popCatch();
}
}
public static class CatchTarget implements JumpTarget {
private final String tag;
public CatchTarget(String tag) { this.tag = tag; }
public String getTag() { return tag; }
}
@JRubyMethod(name = "throw", required = 1, frame = true, optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject rbThrow(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.getRuntime();
String tag = args[0].asJavaString();
CatchTarget[] catches = context.getActiveCatches();
String message = "uncaught throw `" + tag + "'";
// Ordering of array traversal not important, just intuitive
for (int i = catches.length - 1 ; i >= 0 ; i--) {
if (tag.equals(catches[i].getTag())) {
//Catch active, throw for catch to handle
throw new JumpException.ThrowJump(catches[i], args.length > 1 ? args[1] : runtime.getNil());
}
}
// No catch active for this throw
RubyThread currentThread = context.getThread();
if (currentThread == runtime.getThreadService().getMainThread()) {
throw runtime.newNameError(message, tag);
} else {
throw runtime.newThreadError(message + " in thread 0x" + Integer.toHexString(RubyInteger.fix2int(currentThread.id())));
}
}
@JRubyMethod(name = "trap", required = 1, frame = true, optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject trap(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
context.getRuntime().getLoadService().require("jsignal");
return RuntimeHelpers.invoke(context, recv, "__jtrap", args, block);
}
@JRubyMethod(name = "warn", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject warn(ThreadContext context, IRubyObject recv, IRubyObject message) {
Ruby runtime = context.getRuntime();
if (runtime.warningsEnabled()) {
IRubyObject out = runtime.getGlobalVariables().get("$stderr");
RuntimeHelpers.invoke(context, out, "puts", message);
}
return runtime.getNil();
}
@JRubyMethod(name = "set_trace_func", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject set_trace_func(ThreadContext context, IRubyObject recv, IRubyObject trace_func, Block block) {
if (trace_func.isNil()) {
context.getRuntime().setTraceFunction(null);
} else if (!(trace_func instanceof RubyProc)) {
throw context.getRuntime().newTypeError("trace_func needs to be Proc.");
} else {
context.getRuntime().setTraceFunction((RubyProc) trace_func);
}
return trace_func;
}
@JRubyMethod(name = "trace_var", required = 1, optional = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject trace_var(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
if (args.length == 0) throw context.getRuntime().newArgumentError(0, 1);
RubyProc proc = null;
String var = args.length > 1 ? args[0].toString() : null;
// ignore if it's not a global var
if (var.charAt(0) != '$') return context.getRuntime().getNil();
if (args.length == 1) proc = RubyProc.newProc(context.getRuntime(), block, Block.Type.PROC);
if (args.length == 2) {
proc = (RubyProc)TypeConverter.convertToType(args[1], context.getRuntime().getProc(), "to_proc", true);
}
context.getRuntime().getGlobalVariables().setTraceVar(var, proc);
return context.getRuntime().getNil();
}
@JRubyMethod(name = "untrace_var", required = 1, optional = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject untrace_var(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
if (args.length == 0) throw context.getRuntime().newArgumentError(0, 1);
String var = args.length >= 1 ? args[0].toString() : null;
// ignore if it's not a global var
if (var.charAt(0) != '$') return context.getRuntime().getNil();
if (args.length > 1) {
ArrayList<IRubyObject> success = new ArrayList<IRubyObject>();
for (int i = 1; i < args.length; i++) {
if (context.getRuntime().getGlobalVariables().untraceVar(var, args[i])) {
success.add(args[i]);
}
}
return RubyArray.newArray(context.getRuntime(), success);
} else {
context.getRuntime().getGlobalVariables().untraceVar(var);
}
return context.getRuntime().getNil();
}
@JRubyMethod(name = "singleton_method_added", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject singleton_method_added(ThreadContext context, IRubyObject recv, IRubyObject symbolId, Block block) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "singleton_method_removed", required = 1, frame = true, module = true, visibility = PRIVATE)
public static IRubyObject singleton_method_removed(ThreadContext context, IRubyObject recv, IRubyObject symbolId, Block block) {
return context.getRuntime().getNil();
}
@JRubyMethod(name = "singleton_method_undefined", required = 1, frame = true, module = true, visibility = PRIVATE)