/
RubyKernel.java
2393 lines (2008 loc) · 102 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: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v20.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Chad Fowler <chadfowler@chadfowler.com>
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-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 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 java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import jnr.constants.platform.Errno;
import jnr.posix.POSIX;
import org.jcodings.specific.USASCIIEncoding;
import org.jruby.anno.FrameField;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyModule;
import org.jruby.ast.util.ArgsUtil;
import org.jruby.common.IRubyWarnings.ID;
import org.jruby.common.RubyWarnings;
import org.jruby.exceptions.CatchThrow;
import org.jruby.exceptions.MainExitException;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.internal.runtime.methods.JavaMethod.JavaMethodNBlock;
import org.jruby.ir.interpreter.Interpreter;
import org.jruby.java.proxies.ConcreteJavaProxy;
import org.jruby.platform.Platform;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Binding;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.JavaSites.KernelSites;
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.callsite.CacheEntry;
import org.jruby.util.ArraySupport;
import org.jruby.util.ByteList;
import org.jruby.util.ConvertBytes;
import org.jruby.util.IdUtil;
import org.jruby.util.ShellLauncher;
import org.jruby.util.StringSupport;
import org.jruby.util.TypeConverter;
import org.jruby.util.cli.Options;
import org.jruby.util.func.ObjectIntIntFunction;
import org.jruby.util.io.OpenFile;
import org.jruby.util.io.PopenExecutor;
import static org.jruby.RubyEnumerator.enumeratorizeWithSize;
import static org.jruby.RubyIO.checkUnsupportedOptions;
import static org.jruby.RubyIO.checkValidSpawnOptions;
import static org.jruby.RubyIO.UNSUPPORTED_SPAWN_OPTIONS;
import static org.jruby.anno.FrameField.BLOCK;
import static org.jruby.anno.FrameField.FILENAME;
import static org.jruby.anno.FrameField.LASTLINE;
import static org.jruby.anno.FrameField.METHODNAME;
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.RubyEnumerator.SizeFn;
import static org.jruby.anno.FrameField.*;
/**
* Note: For CVS history, see KernelModule.java.
*/
@JRubyModule(name="Kernel")
public class RubyKernel {
public static class MethodMissingMethod extends JavaMethodNBlock {
private final Visibility visibility;
private final CallType callType;
MethodMissingMethod(RubyModule implementationClass, Visibility visibility, CallType callType) {
super(implementationClass, Visibility.PRIVATE, "method_missing");
this.callType = callType;
this.visibility = visibility;
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) {
return RubyKernel.methodMissing(context, self, name, visibility, callType, args);
}
}
public static RubyModule createKernelModule(Ruby runtime) {
RubyModule module = runtime.defineModule("Kernel");
module.defineAnnotatedMethods(RubyKernel.class);
module.setFlag(RubyModule.NEEDSIMPL_F, false); //Kernel is the only normal Module that doesn't need an implementor
runtime.setPrivateMethodMissing(new MethodMissingMethod(module, PRIVATE, CallType.NORMAL));
runtime.setProtectedMethodMissing(new MethodMissingMethod(module, PROTECTED, CallType.NORMAL));
runtime.setVariableMethodMissing(new MethodMissingMethod(module, PUBLIC, CallType.VARIABLE));
runtime.setSuperMethodMissing(new MethodMissingMethod(module, PUBLIC, CallType.SUPER));
runtime.setNormalMethodMissing(new MethodMissingMethod(module, PUBLIC, CallType.NORMAL));
if (runtime.getInstanceConfig().isAssumeLoop()) {
module.defineAnnotatedMethods(LoopMethods.class);
}
recacheBuiltinMethods(runtime, module);
return module;
}
/**
* Cache built-in versions of several core methods, to improve performance by using identity comparison (==) rather
* than going ahead with dynamic dispatch.
*
* @param runtime
*/
static void recacheBuiltinMethods(Ruby runtime, RubyModule kernelModule) {
runtime.setRespondToMethod(kernelModule.searchMethod("respond_to?"));
runtime.setRespondToMissingMethod(kernelModule.searchMethod("respond_to_missing?"));
}
@JRubyMethod(module = true, visibility = PRIVATE)
public static IRubyObject at_exit(ThreadContext context, IRubyObject recv, Block block) {
return context.runtime.pushExitBlock(context.runtime.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) {
final Ruby runtime = context.runtime;
final RubyModule module = getModuleForAutoload(runtime, recv);
final RubyString file = module.getAutoloadFile(symbol.asJavaString());
return file == null ? context.nil : file;
}
@JRubyMethod(required = 2, module = true, visibility = PRIVATE)
public static IRubyObject autoload(ThreadContext context, final IRubyObject recv, IRubyObject symbol, IRubyObject file) {
final Ruby runtime = context.runtime;
final String nonInternedName = symbol.asJavaString();
if (!IdUtil.isValidConstantName(nonInternedName)) {
throw runtime.newNameError("autoload must be constant name", nonInternedName);
}
final RubyString fileString =
StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, file));
if (fileString.isEmpty()) throw runtime.newArgumentError("empty file name");
final String baseName = nonInternedName.intern(); // interned, OK for "fast" methods
final RubyModule module = getModuleForAutoload(runtime, recv);
IRubyObject existingValue = module.fetchConstant(baseName);
if (existingValue != null && existingValue != RubyObject.UNDEF) return context.nil;
module.defineAutoload(baseName, new RubyModule.AutoloadMethod() {
public RubyString getFile() { return fileString; }
public void load(final Ruby runtime) {
final String file = getFile().asJavaString();
if (runtime.getLoadService().autoloadRequire(file)) {
// Do not finish autoloading by cyclic autoload
module.finishAutoload(baseName);
}
}
});
return context.nil;
}
@Deprecated
public static IRubyObject autoload(final IRubyObject recv, IRubyObject symbol, IRubyObject file) {
return autoload(recv.getRuntime().getCurrentContext(), recv, symbol, file);
}
static RubyModule getModuleForAutoload(Ruby runtime, IRubyObject recv) {
RubyModule module = recv instanceof RubyModule ? (RubyModule) recv : recv.getMetaClass().getRealClass();
if (module == runtime.getKernel()) {
// special behavior if calling Kernel.autoload directly
module = runtime.getObject().getSingletonClass();
}
return module;
}
public static IRubyObject method_missing(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Visibility lastVis = context.getLastVisibility();
CallType lastCallType = context.getLastCallType();
if (args.length == 0 || !(args[0] instanceof RubySymbol)) {
throw context.runtime.newArgumentError("no id given");
}
return methodMissingDirect(context, recv, (RubySymbol) args[0], lastVis, lastCallType, args);
}
protected static IRubyObject methodMissingDirect(ThreadContext context, IRubyObject recv, RubySymbol symbol, Visibility lastVis, CallType lastCallType, IRubyObject[] args) {
return methodMissing(context, recv, symbol.idString(), lastVis, lastCallType, args, true);
}
public static IRubyObject methodMissing(ThreadContext context, IRubyObject recv, String name, Visibility lastVis, CallType lastCallType, IRubyObject[] args) {
return methodMissing(context, recv, name, lastVis, lastCallType, args, false);
}
public static IRubyObject methodMissing(ThreadContext context, IRubyObject recv, String name, Visibility lastVis, CallType lastCallType, IRubyObject[] args, boolean dropFirst) {
Ruby runtime = context.runtime;
boolean privateCall = false;
if (lastCallType == CallType.VARIABLE || lastCallType == CallType.FUNCTIONAL) {
privateCall = true;
} else if (lastVis == PUBLIC) {
privateCall = true;
}
if (lastCallType == CallType.VARIABLE) {
throw runtime.newNameError(getMethodMissingFormat(lastVis, lastCallType), recv, name, privateCall);
}
throw runtime.newNoMethodError(getMethodMissingFormat(lastVis, lastCallType), recv, name, RubyArray.newArrayMayCopy(runtime, args, dropFirst ? 1 : 0), privateCall);
}
private static String getMethodMissingFormat(Visibility visibility, CallType callType) {
String format = "undefined method `%s' for %s%s%s";
if (visibility == PRIVATE) {
format = "private method `%s' called for %s%s%s";
} else if (visibility == PROTECTED) {
format = "protected method `%s' called for %s%s%s";
} else if (callType == CallType.VARIABLE) {
format = "undefined local variable or method `%s' for %s%s%s";
} else if (callType == CallType.SUPER) {
format = "super: no superclass method `%s' for %s%s%s";
}
return format;
}
@Deprecated
public static IRubyObject open19(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
return open(context, recv, args, block);
}
@JRubyMethod(name = "open", required = 1, optional = 3, module = true, visibility = PRIVATE)
public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.runtime;
// symbol to_open = 0;
boolean redirect = false;
int argc = args.length;
if (argc >= 1) {
// CONST_ID(to_open, "to_open");
if (args[0].respondsTo("to_open")) {
redirect = true;
} else {
IRubyObject tmp = args[0];
tmp = RubyFile.get_path(context, tmp);
if (tmp == context.nil) {
redirect = true;
} else {
IRubyObject cmd = PopenExecutor.checkPipeCommand(context, tmp);
if (cmd != context.nil) {
if (PopenExecutor.nativePopenAvailable(runtime)) {
args[0] = cmd;
return PopenExecutor.popen(context, args, runtime.getIO(), block);
} else {
throw runtime.newArgumentError("pipe open is not supported without native subprocess logic");
}
}
}
}
}
if (redirect) {
IRubyObject io = args[0].callMethod(context, "to_open", Arrays.copyOfRange(args, 1, args.length));
RubyIO.ensureYieldClose(context, io, block);
return io;
}
return RubyIO.open(context, runtime.getFile(), args, block);
}
@JRubyMethod(module = true, visibility = PRIVATE)
public static IRubyObject getc(ThreadContext context, IRubyObject recv) {
context.runtime.getWarnings().warn(ID.DEPRECATED_METHOD, "getc is obsolete; use STDIN.getc instead");
IRubyObject defin = context.runtime.getGlobalVariables().get("$stdin");
return sites(context).getc.call(context, defin, defin);
}
// MRI: rb_f_gets
@JRubyMethod(optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject gets(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.runtime;
IRubyObject argsFile = runtime.getArgsFile();
if (recv == argsFile) {
return RubyArgsFile.gets(context, argsFile, args);
}
return sites(context).gets.call(context, argsFile, argsFile, args);
}
@JRubyMethod(optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject abort(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.runtime;
RubyString message = null;
if(args.length == 1) {
message = args[0].convertToString();
IRubyObject stderr = runtime.getGlobalVariables().get("$stderr");
sites(context).puts.call(context, stderr, stderr, message);
}
exit(runtime, new IRubyObject[] { runtime.getFalse(), message }, false);
return runtime.getNil(); // not reached
}
// MRI: rb_f_array
@JRubyMethod(name = "Array", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_array(ThreadContext context, IRubyObject recv, IRubyObject object) {
return TypeConverter.rb_Array(context, object);
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv) {
RubyClass complex = context.runtime.getComplex();
return sites(context).convert_complex.call(context, complex, complex);
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
RubyClass complex = context.runtime.getComplex();
return sites(context).convert_complex.call(context, complex, complex, arg0);
}
@JRubyMethod(name = "Complex", module = true, visibility = PRIVATE)
public static IRubyObject new_complex(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
RubyClass complex = context.runtime.getComplex();
return sites(context).convert_complex.call(context, complex, complex, arg0, arg1);
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv) {
RubyClass rational = context.runtime.getRational();
return sites(context).convert_rational.call(context, rational, rational);
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
RubyClass rational = context.runtime.getRational();
return sites(context).convert_rational.call(context, rational, rational, arg0);
}
@JRubyMethod(name = "Rational", module = true, visibility = PRIVATE)
public static IRubyObject new_rational(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
RubyClass rational = context.runtime.getRational();
return sites(context).convert_rational.call(context, rational, rational, arg0, arg1);
}
@Deprecated
public static RubyFloat new_float19(IRubyObject recv, IRubyObject object) {
return new_float(recv, object);
}
@JRubyMethod(name = "Float", module = true, visibility = PRIVATE)
public static RubyFloat new_float(IRubyObject recv, IRubyObject object) {
return new_float(recv.getRuntime(), object);
}
private static final ByteList ZEROx = new ByteList(new byte[] { '0','x' }, false);
public static RubyFloat new_float(final Ruby runtime, IRubyObject object) {
if (object instanceof RubyInteger){
return new_float(runtime, (RubyInteger) object);
}
if (object instanceof RubyFloat) {
return (RubyFloat) object;
}
if (object instanceof RubyString){
RubyString str = (RubyString) object;
ByteList bytes = str.getByteList();
if (bytes.getRealSize() == 0){ // rb_cstr_to_dbl case
throw runtime.newArgumentError("invalid value for Float(): " + object.inspect());
}
if (bytes.startsWith(ZEROx)) { // startsWith("0x")
return ConvertBytes.byteListToInum(runtime, bytes, 16, true).toFloat();
}
return RubyNumeric.str2fnum(runtime, str, true);
}
if (object.isNil()){
throw runtime.newTypeError("can't convert nil into Float");
}
ThreadContext context = runtime.getCurrentContext();
KernelSites sites = sites(context);
return (RubyFloat) TypeConverter.convertToType(context, object, runtime.getFloat(), sites.to_f_checked);
}
static RubyFloat new_float(final Ruby runtime, RubyInteger num) {
if (num instanceof RubyBignum) {
return RubyFloat.newFloat(runtime, RubyBignum.big2dbl((RubyBignum) num));
}
return RubyFloat.newFloat(runtime, ((RubyFixnum) num).getDoubleValue());
}
@JRubyMethod(name = "Hash", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_hash(ThreadContext context, IRubyObject recv, IRubyObject arg) {
IRubyObject tmp;
Ruby runtime = context.runtime;
if (arg == context.nil) return RubyHash.newHash(runtime);
tmp = TypeConverter.checkHashType(context, sites(context).to_hash_checked, arg);
if (tmp == context.nil) {
if (arg instanceof RubyArray && ((RubyArray) arg).isEmpty()) {
return RubyHash.newHash(runtime);
}
throw runtime.newTypeError("can't convert " + arg.getMetaClass() + " into Hash");
}
return tmp;
}
@JRubyMethod(name = "Integer", module = true, visibility = PRIVATE)
public static IRubyObject new_integer(ThreadContext context, IRubyObject recv, IRubyObject object) {
return TypeConverter.convertToInteger(context, object, 0);
}
@JRubyMethod(name = "Integer", module = true, visibility = PRIVATE)
public static IRubyObject new_integer(ThreadContext context, IRubyObject recv, IRubyObject object, IRubyObject base) {
return TypeConverter.convertToInteger(context, object, RubyNumeric.num2int(base));
}
@Deprecated
public static IRubyObject new_integer19(ThreadContext context, IRubyObject recv, IRubyObject object) {
return new_integer(context, recv, object);
}
@JRubyMethod(name = "String", required = 1, module = true, visibility = PRIVATE)
public static IRubyObject new_string(ThreadContext context, IRubyObject recv, IRubyObject object) {
Ruby runtime = context.runtime;
KernelSites sites = sites(context);
IRubyObject tmp = TypeConverter.checkStringType(context, sites.to_str_checked, object, runtime.getString());
if (tmp == context.nil) {
tmp = TypeConverter.convertToType(context, object, runtime.getString(), sites(context).to_s_checked);
}
return tmp;
}
@Deprecated
public static IRubyObject new_string19(ThreadContext context, IRubyObject recv, IRubyObject object) {
return new_string(context, recv, object);
}
// MRI: rb_f_p_internal
@JRubyMethod(rest = true, module = true, visibility = PRIVATE)
public static IRubyObject p(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby runtime = context.runtime;
int argc = args.length;
int i;
IRubyObject ret = context.nil;
IRubyObject defout = runtime.getGlobalVariables().get("$>");
IRubyObject defaultRS = context.runtime.getGlobalVariables().getDefaultSeparator();
boolean defoutWriteBuiltin = defout instanceof RubyIO &&
defout.getMetaClass().isMethodBuiltin("write");
for (i=0; i<argc; i++) {
// pulled out as rb_p in MRI
// rb_p(argv[i]);
IRubyObject obj = args[i];
IRubyObject str = RubyBasicObject.rbInspect(context, obj);
if (defoutWriteBuiltin) {
((RubyIO)defout).write(context, str, true);
((RubyIO)defout).write(context, defaultRS, true);
}
else {
RubyIO.write(context, defout, str);
RubyIO.write(context, defout, defaultRS);
}
}
if (argc == 1) {
ret = args[0];
}
else if (argc > 1) {
ret = RubyArray.newArray(runtime, args);
}
if (defout instanceof RubyIO) {
((RubyIO)defout).flush(context);
}
return ret;
}
@JRubyMethod(required = 1, module = true)
public static IRubyObject public_method(ThreadContext context, IRubyObject recv, IRubyObject symbol) {
return recv.getMetaClass().newMethod(recv, symbol.asJavaString(), true, PUBLIC, true, false);
}
/** rb_f_putc
*/
@JRubyMethod(required = 1, module = true, visibility = PRIVATE)
public static IRubyObject putc(ThreadContext context, IRubyObject recv, IRubyObject ch) {
IRubyObject defout = context.runtime.getGlobalVariables().get("$>");
if (recv == defout) {
return RubyIO.putc(context, recv, ch);
}
return sites(context).putc.call(context, defout, defout, ch);
}
@JRubyMethod(module = true, visibility = PRIVATE)
public static IRubyObject puts(ThreadContext context, IRubyObject recv) {
IRubyObject defout = context.runtime.getGlobalVariables().get("$>");
if (recv == defout) {
return RubyIO.puts0(context, recv);
}
return sites(context).puts.call(context, defout, defout);
}
@JRubyMethod(module = true, visibility = PRIVATE)
public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject arg0) {
IRubyObject defout = context.runtime.getGlobalVariables().get("$>");
if (recv == defout) {
return RubyIO.puts1(context, recv, arg0);
}
return sites(context).puts.call(context, defout, defout, arg0);
}
@JRubyMethod(module = true, visibility = PRIVATE)
public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) {
IRubyObject defout = context.runtime.getGlobalVariables().get("$>");
if (recv == defout) {
return RubyIO.puts2(context, recv, arg0, arg1);
}
return sites(context).puts.call(context, defout, defout, arg0, arg1);
}
@JRubyMethod(module = true, visibility = PRIVATE)
public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) {
IRubyObject defout = context.runtime.getGlobalVariables().get("$>");
if (recv == defout) {
return RubyIO.puts3(context, recv, arg0, arg1, arg2);
}
return sites(context).puts.call(context, defout, defout, arg0, arg1, arg2);
}
@JRubyMethod(rest = true, module = true, visibility = PRIVATE)
public static IRubyObject puts(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject defout = context.runtime.getGlobalVariables().get("$>");
if (recv == defout) {
return RubyIO.puts(context, recv, args);
}
return sites(context).puts.call(context, defout, defout, args);
}
// rb_f_print
@JRubyMethod(rest = true, module = true, visibility = PRIVATE, reads = LASTLINE)
public static IRubyObject print(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
RubyIO.print(context, context.runtime.getGlobalVariables().get("$>"), args);
return context.nil;
}
// rb_f_printf
@JRubyMethod(rest = true, module = true, visibility = PRIVATE)
public static IRubyObject printf(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
if (args.length == 0) return context.nil;
final IRubyObject out;
if (args[0] instanceof RubyString) {
out = context.runtime.getGlobalVariables().get("$>");
}
else {
out = args[0];
args = Arrays.copyOfRange(args, 1, args.length);
}
RubyIO.write(context, out, sprintf(context, recv, args));
return context.nil;
}
@JRubyMethod(optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject readline(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
IRubyObject line = gets(context, recv, args);
if (line.isNil()) {
throw context.runtime.newEOFError();
}
return line;
}
@JRubyMethod(optional = 1, module = true, visibility = PRIVATE)
public static IRubyObject readlines(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return RubyArgsFile.readlines(context, context.runtime.getArgsFile(), args);
}
@JRubyMethod(name = "respond_to_missing?", visibility = PRIVATE)
public static IRubyObject respond_to_missing_p(ThreadContext context, IRubyObject recv, IRubyObject symbol) {
return context.fals;
}
@JRubyMethod(name = "respond_to_missing?", visibility = PRIVATE)
public static IRubyObject respond_to_missing_p(ThreadContext context, IRubyObject recv, IRubyObject symbol, IRubyObject isPrivate) {
return context.fals;
}
/** Returns value of $_.
*
* @throws RaiseException TypeError if $_ is not a String or nil.
* @return value of $_ as String.
*/
private static RubyString getLastlineString(ThreadContext context, Ruby runtime) {
IRubyObject line = context.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;
}
}
@JRubyMethod(required = 1, optional = 3, module = true, visibility = PRIVATE)
public static IRubyObject select(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
return RubyIO.select(context, recv, args);
}
@JRubyMethod(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 {
milliseconds = (long) ( RubyTime.convertTimeInterval(context, args[0]) * 1000 );
// Explicit zero in MRI returns immediately
if ( milliseconds == 0 ) return context.runtime.newFixnum(0);
}
final long startTime = System.currentTimeMillis();
final RubyThread rubyThread = context.getThread();
boolean interrupted = false;
try {
// Spurious wakeup-loop
do {
long loopStartTime = System.currentTimeMillis();
if (!rubyThread.sleep(milliseconds)) break;
milliseconds -= (System.currentTimeMillis() - loopStartTime);
} while (milliseconds > 0);
} catch (InterruptedException ie) {
// ignore; sleep gets interrupted
interrupted = true;
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
return context.runtime.newFixnum(Math.round((System.currentTimeMillis() - startTime) / 1000.0));
}
// FIXME: Add at_exit and finalizers to exit, then make exit_bang not call those.
@JRubyMethod(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 = hard ? 1 : 0;
String message = null;
if (args.length > 0) {
RubyObject argument = (RubyObject) args[0];
if (argument instanceof RubyBoolean) {
status = argument.isFalse() ? 1 : 0;
} else {
status = RubyNumeric.fix2int(argument);
}
}
if (args.length == 2) {
if (args[1] instanceof RubyString) {
message = ((RubyString) args[1]).toString();
}
}
if (hard) {
if (runtime.getInstanceConfig().isHardExit()) {
System.exit(status);
} else {
throw new MainExitException(status, true);
}
} else {
if (message == null) {
throw runtime.newSystemExit(status);
} else {
throw runtime.newSystemExit(status, message);
}
}
}
/**
* @param context
* @param recv
* @return 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.runtime;
RubyArray globalVariables = runtime.newArray();
for (String globalVariableName : runtime.getGlobalVariables().getNames()) {
globalVariables.append(runtime.newSymbol(globalVariableName));
}
return globalVariables;
}
@Deprecated
public static RubyArray global_variables19(ThreadContext context, IRubyObject recv) {
return global_variables(context, recv);
}
/**
* @param context
* @param recv
* @return an Array with the names of all local variables.
*/
@JRubyMethod(name = "local_variables", module = true, visibility = PRIVATE, reads = SCOPE)
public static RubyArray local_variables(ThreadContext context, IRubyObject recv) {
return context.getCurrentStaticScope().getLocalVariables(context.runtime);
}
@Deprecated
public static RubyArray local_variables19(ThreadContext context, IRubyObject recv) {
return local_variables(context, recv);
}
@JRubyMethod(name = "binding", module = true, visibility = PRIVATE,
reads = {LASTLINE, BACKREF, VISIBILITY, BLOCK, SELF, METHODNAME, LINE, CLASS, FILENAME, SCOPE},
writes = {LASTLINE, BACKREF, VISIBILITY, BLOCK, SELF, METHODNAME, LINE, CLASS, FILENAME, SCOPE})
public static RubyBinding binding(ThreadContext context, IRubyObject recv, Block block) {
return RubyBinding.newBinding(context.runtime, context.currentBinding());
}
@Deprecated
public static RubyBinding binding19(ThreadContext context, IRubyObject recv, Block block) {
return binding(context, recv, block);
}
@JRubyMethod(name = {"block_given?", "iterator?"}, module = true, visibility = PRIVATE, reads = BLOCK)
public static RubyBoolean block_given_p(ThreadContext context, IRubyObject recv) {
return RubyBoolean.newBoolean(context, context.getCurrentFrame().getBlock().isGiven());
}
@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.runtime.newArgumentError("sprintf must have at least one argument");
}
RubyString str = RubyString.stringValue(args[0]);
IRubyObject arg;
if (args.length == 2 && args[1] instanceof RubyHash) {
arg = args[1];
} else {
RubyArray newArgs = RubyArray.newArrayMayCopy(context.runtime, args);
newArgs.shift(context);
arg = newArgs;
}
return str.op_format(context, arg);
}
@Deprecated
public static IRubyObject sprintf(IRubyObject recv, IRubyObject[] args) {
return sprintf(recv.getRuntime().getCurrentContext(), recv, args);
}
@JRubyMethod(name = {"raise", "fail"}, optional = 3, module = true, visibility = PRIVATE, omit = true)
public static IRubyObject raise(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
final Ruby runtime = context.runtime;
int argc = args.length;
boolean forceCause = false;
// semi extract_raise_opts :
IRubyObject cause = null;
if (argc > 0) {
IRubyObject last = args[argc - 1];
if (last instanceof RubyHash) {
RubyHash opt = (RubyHash) last;
RubySymbol key;
if (!opt.isEmpty() && (opt.has_key_p(context, key = runtime.newSymbol("cause")) == runtime.getTrue())) {
cause = opt.delete(context, key, Block.NULL_BLOCK);
forceCause = true;
if (opt.isEmpty() && --argc == 0) { // more opts will be passed along
throw runtime.newArgumentError("only cause is given with no arguments");
}
}
}
}
if ( argc > 0 ) { // for argc == 0 we will be raising $!
// NOTE: getErrorInfo needs to happen before new RaiseException(...)
if ( cause == null ) cause = context.getErrorInfo(); // returns nil for no error-info
}
maybeRaiseJavaException(runtime, args, argc, cause);
RaiseException raise;
switch (argc) {
case 0:
IRubyObject lastException = runtime.getGlobalVariables().get("$!");
if (lastException.isNil()) {
raise = RaiseException.from(runtime, runtime.getRuntimeError(), "");
} else {
// non RubyException value is allowed to be assigned as $!.
raise = ((RubyException) lastException).toThrowable();
}
break;
case 1:
if (args[0] instanceof RubyString) {
raise = ((RubyException) runtime.getRuntimeError().newInstance(context, args, block)).toThrowable();
} else {
raise = convertToException(context, args[0], null).toThrowable();
}
break;
case 2:
raise = convertToException(context, args[0], args[1]).toThrowable();
break;
default:
RubyException exception = convertToException(context, args[0], args[1]);
exception.setBacktrace(args[2]);
raise = exception.toThrowable();
break;
}
if (runtime.isDebug()) {
printExceptionSummary(runtime, raise.getException());
}
if (forceCause || argc > 0 && raise.getException().getCause() == null && cause != raise.getException()) {
raise.getException().setCause(cause);
}
throw raise;
}
private static void maybeRaiseJavaException(final Ruby runtime,
final IRubyObject[] args, final int argc, final IRubyObject cause) {
// Check for a Java exception
ConcreteJavaProxy exception = null;
switch (argc) {
case 0:
IRubyObject lastException = runtime.getGlobalVariables().get("$!");
if (lastException instanceof ConcreteJavaProxy) {
exception = (ConcreteJavaProxy) lastException;
}
break;
case 1:
if (args.length == 1 && args[0] instanceof ConcreteJavaProxy) {
exception = (ConcreteJavaProxy) args[0];
}
break;
}
if (exception != null) {
// looks like someone's trying to raise a Java exception. Let them.
Object maybeThrowable = exception.getObject();
if (!(maybeThrowable instanceof Throwable)) {
throw runtime.newTypeError("can't raise a non-Throwable Java object");
}
final Throwable ex = (Throwable) maybeThrowable;
Helpers.throwException(ex); return; // not reached
}
}
private static RubyException convertToException(ThreadContext context, IRubyObject obj, IRubyObject optionalMessage) {
if (!obj.respondsTo("exception")) {
throw context.runtime.newTypeError("exception class/object expected");
}
IRubyObject exception;
if (optionalMessage == null) {
exception = obj.callMethod(context, "exception");
} else {
exception = obj.callMethod(context, "exception", optionalMessage);
}
try {
return (RubyException) exception;
} catch (ClassCastException cce) {
throw context.runtime.newTypeError("exception object expected");
}
}
private static void printExceptionSummary(Ruby runtime, RubyException rEx) {
RubyStackTraceElement[] elements = rEx.getBacktraceElements();
RubyStackTraceElement firstElement = elements.length > 0 ? elements[0] :
new RubyStackTraceElement("", "", "(empty)", 0, false);
String msg = String.format("Exception `%s' at %s:%s - %s\n",
rEx.getMetaClass(),
firstElement.getFileName(), firstElement.getLineNumber(),
TypeConverter.convertToType(rEx, runtime.getString(), "to_s"));
runtime.getErrorStream().print(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", module = true, visibility = PRIVATE)
public static IRubyObject require(ThreadContext context, IRubyObject recv, IRubyObject name, Block block) {
IRubyObject tmp = name.checkStringType();
if (tmp != context.nil) return requireCommon(context.runtime, (RubyString) tmp, block);
return requireCommon(context.runtime, RubyFile.get_path(context, name), block);
}
private static IRubyObject requireCommon(Ruby runtime, RubyString name, Block block) {
RubyString path = StringSupport.checkEmbeddedNulls(runtime, name);
return runtime.newBoolean(runtime.getLoadService().require(path.toString()));
}
@JRubyMethod(name = "require_relative", module = true, visibility = PRIVATE, reads = SCOPE)
public static IRubyObject require_relative(ThreadContext context, IRubyObject recv, IRubyObject name){
Ruby runtime = context.runtime;
RubyString relativePath = RubyFile.get_path(context, name);
String file = context.getCurrentStaticScope().getIRScope().getFile();
if (file == null || file.matches("\\A\\((.*)\\)")) {
throw runtime.newLoadError("cannot infer basepath");
}
RubyClass fileClass = runtime.getFile();
IRubyObject realpath = RubyFile.realpath(context, fileClass, runtime.newString(file));
IRubyObject dirname = RubyFile.dirname(context, fileClass,
realpath);
IRubyObject absoluteFeature = RubyFile.expand_path(context, fileClass, relativePath, dirname);