/
kernel.rb
976 lines (783 loc) · 21.5 KB
/
kernel.rb
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
module Kernel
def Array(obj)
ary = Rubinius::Type.check_convert_type obj, Array, :to_ary
return ary if ary
if array = Rubinius::Type.check_convert_type(obj, Array, :to_a)
array
else
[obj]
end
end
module_function :Array
def Complex(*args)
Rubinius.privately do
Complex.convert(*args)
end
end
module_function :Complex
def Float(obj)
case obj
when String
Rubinius::Type.coerce_string_to_float obj, true
else
Rubinius::Type.coerce_object_to_float obj
end
end
module_function :Float
##
# MRI uses a macro named NUM2DBL which has essentially the same semantics as
# Float(), with the difference that it raises a TypeError and not a
# ArgumentError. It is only used in a few places (in MRI and Rubinius).
#--
# If we can, we should probably get rid of this.
def FloatValue(obj)
exception = TypeError.new 'no implicit conversion to float'
case obj
when String
raise exception
else
begin
Rubinius::Type.coerce_object_to_float obj
rescue
raise exception
end
end
end
private :FloatValue
def Hash(obj)
return {} if obj.nil? || obj == []
if hash = Rubinius::Type.check_convert_type(obj, Hash, :to_hash)
return hash
end
raise TypeError, "can't convert #{obj.class} into Hash"
end
module_function :Hash
def Integer(obj, base=nil)
if obj.kind_of? String
if obj.empty?
raise ArgumentError, "invalid value for Integer: (empty string)"
else
base ||= 0
return obj.to_inum(base, true)
end
end
if base
raise ArgumentError, "base is only valid for String values"
end
case obj
when Integer
obj
when Float
if obj.nan? or obj.infinite?
raise FloatDomainError, "unable to coerce #{obj} to Integer"
else
obj.to_int
end
when NilClass
raise TypeError, "can't convert nil into Integer"
else
# Can't use coerce_to or try_convert because I think there is an
# MRI bug here where it will return the value without checking
# the return type.
if obj.respond_to? :to_int
if val = obj.to_int
return val
end
end
Rubinius::Type.coerce_to obj, Integer, :to_i
end
end
module_function :Integer
def Rational(a, b = 1)
Rubinius.privately do
Rational.convert a, b
end
end
module_function :Rational
def String(obj)
return obj if obj.kind_of? String
unless obj.respond_to?(:to_s)
raise TypeError, "can't convert #{obj.class} into String"
end
begin
str = obj.to_s
rescue NoMethodError
raise TypeError, "can't convert #{obj.class} into String"
end
unless str.kind_of? String
raise TypeError, "#to_s did not return a String"
end
return str
end
module_function :String
##
# MRI uses a macro named StringValue which has essentially the same
# semantics as obj.coerce_to(String, :to_str), but rather than using that
# long construction everywhere, we define a private method similar to
# String().
#
# Another possibility would be to change String() as follows:
#
# String(obj, sym=:to_s)
#
# and use String(obj, :to_str) instead of StringValue(obj)
def StringValue(obj)
Rubinius::Type.coerce_to obj, String, :to_str
end
module_function :StringValue
def __method__
scope = Rubinius::VariableScope.of_sender
name = scope.method.name
return nil if scope.method.for_module_body?
# If the name is still __block__, then it's in a script, so return nil
return nil if name == :__block__ or name == :__script__
name
end
module_function :__method__
alias_method :__callee__, :__method__
module_function :__callee__
def __dir__
scope = Rubinius::ConstantScope.of_sender
script = scope.current_script
basepath = script.file_path
fullpath = nil
return nil unless basepath
fullpath = if script.data_path
script.data_path
else
Rubinius.privately do
File.basic_realpath(basepath)
end
end
File.dirname fullpath
end
module_function :__dir__
def `(str) #`
str = StringValue(str) unless str.kind_of?(String)
pid, output = Rubinius::Mirror::Process.backtick str
Process.waitpid(pid)
Rubinius::Type.external_string output
end
module_function :` # `
def =~(other)
nil
end
def <=>(other)
self == other ? 0 : nil
end
def ===(other)
equal?(other) || self == other
end
def itself
self
end
def abort(msg=nil)
Process.abort msg
end
module_function :abort
def at_exit(prc=nil, &block)
if prc
unless prc.respond_to?(:call)
raise "Argument must respond to #call"
end
else
prc = block
end
unless prc
raise "must pass a #call'able or block"
end
Rubinius::AtExit.unshift(prc)
end
module_function :at_exit
def autoload(name, file)
Object.autoload(name, file)
end
private :autoload
def autoload?(name)
Object.autoload?(name)
end
private :autoload?
def block_given?
Rubinius::VariableScope.of_sender.block != nil
end
module_function :block_given?
alias_method :iterator?, :block_given?
module_function :iterator?
def caller(start = 1, length = nil)
frames = []
# The + 1 is to skip this frame
Rubinius.mri_backtrace(start + 1).map do |tup|
if length and frames.length == length
break
end
code = tup[0]
line = tup[1]
is_block = tup[2]
name = tup[3]
frames << "#{code.active_path}:#{line}:in `#{name}'"
end
frames
end
module_function :caller
##
# Returns the current call stack as an Array of Thread::Backtrace::Location
# instances. This method is available starting with Ruby 2.0.
#
def caller_locations(start = 1, length = nil)
full_trace = Rubinius.mri_backtrace(start + 1)
locations = []
full_trace.each do |tup|
if length and locations.length == length
break
end
scope = tup[0].scope
abs_path = tup[0].active_path
path = scope ? scope.active_path : abs_path
label = tup[3].to_s
locations << Thread::Backtrace::Location.new(label, abs_path, path, tup[1])
end
locations
end
module_function :caller_locations
def define_singleton_method(*args, &block)
singleton_class.send(:define_method, *args, &block)
end
def display(port=$>)
port.write self
end
def exec(*args)
Process.exec(*args)
end
module_function :exec
def exit(code=0)
Process.exit(code)
end
module_function :exit
def exit!(code=1)
Process.exit!(code)
end
module_function :exit!
def extend(*modules)
raise ArgumentError, "wrong number of arguments (0 for 1+)" if modules.empty?
Rubinius.check_frozen
modules.reverse_each do |mod|
Rubinius.privately do
mod.extend_object self
end
Rubinius.privately do
mod.extended self
end
end
self
end
alias_method :__extend__, :extend
def fork(&block)
Process.fork(&block)
end
module_function :fork
def getc
$stdin.getc
end
module_function :getc
def gets(sep=$/)
ARGF.gets(sep)
end
module_function :gets
def global_variables
Rubinius::Globals.variables
end
module_function :global_variables
def initialize_dup(other)
initialize_copy(other)
end
private :initialize_dup
def initialize_clone(other)
initialize_copy(other)
end
private :initialize_clone
def initialize_copy(source)
unless instance_of?(Rubinius::Type.object_class(source))
raise TypeError, "initialize_copy should take same class object"
end
end
private :initialize_copy
def inspect
prefix = "#<#{self.class}:0x#{self.__id__.to_s(16)}"
# The protocol here seems odd, but it's to match MRI.
#
# MRI side-calls to the C function that implements Kernel#to_s. If that
# method is overridden, the new Ruby method is never called. So, we inline
# the code for Kernel#to_s here because we simply dispatch to Ruby
# methods.
ivars = __instance_variables__
if ivars.empty?
return Rubinius::Type.infect "#{prefix}>", self
end
# Otherwise, if it's already been inspected, return the ...
return "#{prefix} ...>" if Thread.guarding? self
# Otherwise, gather the ivars and show them.
parts = []
Thread.recursion_guard self do
ivars.each do |var|
parts << "#{var}=#{__instance_variable_get__(var).inspect}"
end
end
if parts.empty?
str = "#{prefix}>"
else
str = "#{prefix} #{parts.join(' ')}>"
end
Rubinius::Type.infect(str, self)
return str
end
##
# Returns true if this object is an instance of the given class, otherwise
# false. Raises a TypeError if a non-Class object given.
#
# Module objects can also be given for MRI compatibility but the result is
# always false.
def instance_of?(cls)
Rubinius.primitive :object_instance_of
arg_class = Rubinius::Type.object_class(cls)
if arg_class != Class and arg_class != Module
# We can obviously compare against Modules but result is always false
raise TypeError, "instance_of? requires a Class argument"
end
Rubinius::Type.object_class(self) == cls
end
def instance_variable_get(sym)
Rubinius.primitive :object_get_ivar
sym = Rubinius::Type.ivar_validate sym
instance_variable_get sym
end
alias_method :__instance_variable_get__, :instance_variable_get
def instance_variable_set(sym, value)
Rubinius.primitive :object_set_ivar
sym = Rubinius::Type.ivar_validate sym
instance_variable_set sym, value
end
alias_method :__instance_variable_set__, :instance_variable_set
def instance_variables
ary = []
__all_instance_variables__.each do |sym|
ary << sym if sym.is_ivar?
end
ary
end
def instance_variable_defined?(name)
Rubinius.primitive :object_ivar_defined
instance_variable_defined? Rubinius::Type.ivar_validate(name)
end
# Both of these are for defined? when used inside a proxy obj that
# may undef the regular method. The compiler generates __ calls.
alias_method :__instance_variable_defined_p__, :instance_variable_defined?
alias_method :__respond_to_p__, :respond_to?
alias_method :is_a?, :kind_of?
def lambda
env = nil
Rubinius.asm do
push_block
# assign a pushed block to the above local variable "env"
# Note that "env" is indexed at 0.
set_local 0
end
raise ArgumentError, "block required" unless env
prc = Rubinius::Mirror::Proc.from_block ::Proc, env
# Make a proc lambda only when passed an actual block (ie, not using the
# "&block" notation), otherwise don't modify it at all.
prc.lambda_style! if env.is_a?(Rubinius::BlockEnvironment)
return prc
end
module_function :lambda
def load(name, wrap=false)
cl = Rubinius::CodeLoader.new(name)
cl.load(wrap)
Rubinius.run_script cl.compiled_code
Rubinius::CodeLoader.loaded_hook.trigger!(name)
return true
end
module_function :load
def loop
return to_enum(:loop) { Float::INFINITY } unless block_given?
begin
while true
yield
end
rescue StopIteration => e
e.result
end
end
module_function :loop
def method(name)
name = Rubinius::Type.coerce_to_symbol name
code = Rubinius.find_method(self, name)
if code
Method.new(self, code[1], code[0], name)
elsif respond_to_missing?(name, true)
Method.new(self, self.class, Rubinius::MissingMethod.new(self, name), name)
else
raise NameError, "undefined method `#{name}' for class #{self.class}"
end
end
def methods(all=true)
methods = singleton_methods(all)
if all
# We have to special case these because unlike true, false, nil,
# Type.object_singleton_class raises a TypeError.
case self
when Fixnum, Symbol
methods |= Rubinius::Type.object_class(self).instance_methods(true)
else
methods |= Rubinius::Type.object_singleton_class(self).instance_methods(true)
end
end
return methods if kind_of?(ImmediateValue)
undefs = []
Rubinius::Type.object_singleton_class(self).method_table.filter_entries do |entry|
undefs << entry.name.to_s if entry.visibility == :undef
end
return methods - undefs
end
def nil?
false
end
def object_id
Rubinius.primitive :object_id
raise PrimitiveFailure, "Kernel#object_id primitive failed"
end
def open(obj, *rest, &block)
if obj.respond_to?(:to_open)
obj = obj.to_open(*rest)
if block_given?
return yield(obj)
else
return obj
end
end
path = Rubinius::Type.coerce_to_path obj
if path.kind_of? String and path.prefix? '|'
return IO.popen(path[1..-1], *rest, &block)
end
File.open(path, *rest, &block)
end
module_function :open
def p(*a)
return nil if a.empty?
a.each { |obj| $stdout.puts obj.inspect }
$stdout.flush
a.size == 1 ? a.first : a
end
module_function :p
def print(*args)
args.each do |obj|
$stdout.write obj.to_s
end
nil
end
module_function :print
def printf(target, *args)
if target.kind_of?(String)
output = $stdout
else
output = target
target = args.shift
end
output.write Rubinius::Sprinter.get(target).call(*args)
nil
end
module_function :printf
def private_methods(all=true)
private_singleton_methods() | Rubinius::Type.object_class(self).private_instance_methods(all)
end
def private_singleton_methods
sc = Rubinius::Type.object_singleton_class self
methods = sc.method_table.private_names
m = sc
while m = m.direct_superclass
unless Rubinius::Type.object_kind_of?(m, Rubinius::IncludedModule) or
Rubinius::Type.singleton_class_object(m)
break
end
methods.concat m.method_table.private_names
end
methods
end
private :private_singleton_methods
def proc(&prc)
raise ArgumentError, "block required" unless prc
return prc
end
module_function :proc
def protected_methods(all=true)
protected_singleton_methods() | Rubinius::Type.object_class(self).protected_instance_methods(all)
end
def protected_singleton_methods
m = Rubinius::Type.object_singleton_class self
methods = m.method_table.protected_names
while m = m.direct_superclass
unless Rubinius::Type.object_kind_of?(m, Rubinius::IncludedModule) or
Rubinius::Type.singleton_class_object(m)
break
end
methods.concat m.method_table.protected_names
end
methods
end
private :protected_singleton_methods
def public_method(name)
name = Rubinius::Type.coerce_to_symbol name
code = Rubinius.find_public_method(self, name)
if code
Method.new(self, code[1], code[0], name)
elsif respond_to_missing?(name, false)
Method.new(self, self.class, Rubinius::MissingMethod.new(self, name), name)
else
raise NameError, "undefined method `#{name}' for #{self.inspect}"
end
end
def public_methods(all=true)
public_singleton_methods | Rubinius::Type.object_class(self).public_instance_methods(all)
end
def public_send(message, *args)
Rubinius.primitive :object_public_send
raise PrimitiveFailure, "Kernel#public_send primitive failed"
end
def public_singleton_methods
m = Rubinius::Type.object_singleton_class self
methods = m.method_table.public_names
while m = m.direct_superclass
unless Rubinius::Type.object_kind_of?(m, Rubinius::IncludedModule) or
Rubinius::Type.singleton_class_object(m)
break
end
methods.concat m.method_table.public_names
end
methods
end
private :public_singleton_methods
def putc(int)
$stdout.putc(int)
end
module_function :putc
def puts(*a)
$stdout.puts(*a)
nil
end
module_function :puts
def rand(limit=0)
if limit == 0
return Thread.current.randomizer.random_float
end
if limit.kind_of?(Range)
return Thread.current.randomizer.random(limit)
else
limit = Integer(limit).abs
if limit == 0
Thread.current.randomizer.random_float
else
Thread.current.randomizer.random_integer(limit - 1)
end
end
end
module_function :rand
def readline(sep=$/)
ARGF.readline(sep)
end
module_function :readline
def readlines(sep=$/)
ARGF.readlines(sep)
end
module_function :readlines
def remove_instance_variable(sym)
Rubinius.primitive :object_del_ivar
# If it's already a symbol, then we're here because it doesn't exist.
if sym.kind_of? Symbol
raise NameError, "instance variable '#{sym}' not defined"
end
# Otherwise because sym isn't a symbol, coerce it and try again.
remove_instance_variable Rubinius::Type.ivar_validate(sym)
end
def require(name)
Rubinius::CodeLoader.require name
end
module_function :require
def require_relative(name)
scope = Rubinius::ConstantScope.of_sender
Rubinius::CodeLoader.require_relative(name, scope)
end
module_function :require_relative
def select(*args)
IO.select(*args)
end
module_function :select
def send(message, *args)
Rubinius.primitive :object_send
raise PrimitiveFailure, "Kernel#send primitive failed"
end
def set_trace_func(*args)
raise NotImplementedError
end
module_function :set_trace_func
def sprintf(str, *args)
Rubinius::Sprinter.get(str).call(*args)
end
module_function :sprintf
alias_method :format, :sprintf
module_function :format
def sleep(duration=undefined)
Rubinius.primitive :vm_sleep
# The primitive will fail on arg count if sleep is called
# without an argument, so we call it again passing undefined
# to mean "sleep forever"
#
if undefined.equal? duration
return sleep(undefined)
end
if duration.kind_of? Numeric
float = Rubinius::Type.coerce_to duration, Float, :to_f
return sleep(float)
else
raise TypeError, 'time interval must be a numeric value'
end
end
module_function :sleep
def srand(seed=undefined)
if undefined.equal? seed
seed = Thread.current.randomizer.generate_seed
end
seed = Rubinius::Type.coerce_to seed, Integer, :to_int
Thread.current.randomizer.swap_seed seed
end
module_function :srand
def tap
yield self
self
end
def test(cmd, file1, file2=nil)
case cmd
when ?d
File.directory? file1
when ?e
File.exist? file1
when ?f
File.file? file1
when ?l
File.symlink? file1
when ?r
File.readable? file1
when ?R
File.readable_real? file1
when ?w
File.writable? file1
when ?W
File.writable_real? file1
when ?A
File.atime file1
when ?C
File.ctime file1
when ?M
File.mtime file1
else
raise NotImplementedError, "command ?#{cmd.chr} not implemented"
end
end
module_function :test
def to_enum(method=:each, *args, &block)
Enumerator.new(self, method, *args).tap do |enum|
Rubinius.privately { enum.size = block } if block_given?
end
end
alias_method :enum_for, :to_enum
def trap(sig, prc=nil, &block)
Signal.trap(sig, prc, &block)
end
module_function :trap
def singleton_method_added(name)
end
private :singleton_method_added
def singleton_method_removed(name)
end
private :singleton_method_removed
def singleton_method_undefined(name)
end
private :singleton_method_undefined
def singleton_methods(all=true)
m = Rubinius::Type.object_singleton_class self
mt = m.method_table
methods = mt.public_names + mt.protected_names
if all
while m = m.direct_superclass
unless Rubinius::Type.object_kind_of?(m, Rubinius::IncludedModule) or
Rubinius::Type.singleton_class_object(m)
break
end
mt = m.method_table
methods.concat mt.public_names
methods.concat mt.protected_names
end
end
methods.uniq
end
def spawn(*args)
Process.spawn(*args)
end
module_function :spawn
def syscall(*args)
raise NotImplementedError
end
module_function :syscall
def system(*args)
begin
pid = Process.spawn(*args)
rescue SystemCallError
return nil
end
Process.waitpid pid
$?.exitstatus == 0
end
module_function :system
def to_s
Rubinius::Type.infect("#<#{self.class}:0x#{self.__id__.to_s(16)}>", self)
end
def trace_var(name, cmd = nil, &block)
if !cmd && !block
raise(
ArgumentError,
'The 2nd argument should be a Proc/String, alternatively use a block'
)
end
# We have to use a custom proc since set_hook passes in both the variable
# name and value.
set = proc do |_, value|
if cmd.is_a?(String)
eval(cmd)
# In MRI if one passes both a proc in `cmd` and a block the latter will
# be ignored.
elsif cmd.is_a?(Proc)
cmd.call(value)
elsif block
block.call(value)
end
end
Rubinius::Globals.set_hook(name, :[], set)
end
module_function :trace_var
# In MRI one can specify a 2nd argument to remove a specific tracer.
# Rubinius::Globals however only supports one hook per variable, hence the
# 2nd dummy argument.
def untrace_var(name, *args)
Rubinius::Globals.remove_hook(name)
end
module_function :untrace_var
def warn(*messages)
$stderr.puts(*messages) if !$VERBOSE.nil? && !messages.empty?
nil
end
module_function :warn
def warning(message)
$stderr.puts message if $VERBOSE
end
module_function :warning
end
module Kernel
end