-
Notifications
You must be signed in to change notification settings - Fork 178
/
cext.rb
2314 lines (1909 loc) · 58.8 KB
/
cext.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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
# truffleruby_primitives: true
# Copyright (c) 2015, 2024 Oracle and/or its affiliates. All rights reserved. This
# code is released under a tri EPL/GPL/LGPL license. You can use it,
# redistribute it and/or modify it under the terms of the:
#
# Eclipse Public License version 2.0, or
# GNU General Public License version 2, or
# GNU Lesser General Public License version 2.1.
require_relative 'cext_ruby'
require_relative 'cext_constants'
require_relative 'cext_structs'
# TODO (eregon, 1 Sep 2022): should we always_split or use separate CallTargets for usages of Primitive.call_with* in this file?
module Truffle::CExt
DATA_TYPE = Primitive.object_hidden_var_create :data_type
DATA_STRUCT = Primitive.object_hidden_var_create :data_struct # struct RData* or struct RTypedData*
DATA_MARKER = Primitive.object_hidden_var_create :data_marker
DATA_MEMSIZER = Primitive.object_hidden_var_create :data_memsizer
RB_TYPE = Primitive.object_hidden_var_create :rb_type
ALLOCATOR_FUNC = Primitive.object_hidden_var_create :allocator_func
RB_IO_STRUCT = Primitive.object_hidden_var_create :rb_io_struct
SULONG = Truffle::Boot.get_option('cexts-sulong')
NFI = !SULONG
SET_LIBTRUFFLERUBY = -> libtruffleruby do
LIBTRUFFLERUBY = libtruffleruby
end
SET_LIBTRAMPOLINE = -> libtrampoline do
LIBTRAMPOLINE = libtrampoline
end
SETUP_WRAPPERS = -> lib do
# signature starts with an extra pointer which is for passing the native function to call
POINTER_TO_POINTER_WRAPPERS = [nil] + (1..16).map do |n|
sig = -"(pointer,#{(['pointer'] * n).join(',')}):pointer"
Primitive.interop_eval_nfi(sig).bind(lib[:"rb_tr_setjmp_wrapper_pointer#{n}_to_pointer"])
end
POINTER_TO_POINTER_WRAPPER = POINTER_TO_POINTER_WRAPPERS[1]
POINTER2_TO_POINTER_WRAPPER = POINTER_TO_POINTER_WRAPPERS[2]
POINTER3_TO_POINTER_WRAPPER = POINTER_TO_POINTER_WRAPPERS[3]
VOID_TO_VOID_WRAPPER = Primitive.interop_eval_nfi('(pointer):void').bind(lib[:rb_tr_setjmp_wrapper_void_to_void])
POINTER_TO_VOID_WRAPPER = Primitive.interop_eval_nfi('(pointer,pointer):void').bind(lib[:rb_tr_setjmp_wrapper_pointer1_to_void])
POINTER2_TO_VOID_WRAPPER = Primitive.interop_eval_nfi('(pointer,pointer,pointer):void').bind(lib[:rb_tr_setjmp_wrapper_pointer2_to_void])
POINTER3_TO_VOID_WRAPPER = Primitive.interop_eval_nfi('(pointer,pointer,pointer,pointer):void').bind(lib[:rb_tr_setjmp_wrapper_pointer3_to_void])
POINTER3_TO_INT_WRAPPER = Primitive.interop_eval_nfi('(pointer,pointer,pointer,pointer):sint32').bind(lib[:rb_tr_setjmp_wrapper_pointer3_to_int])
POINTER_TO_SIZE_T_WRAPPER = Primitive.interop_eval_nfi('(pointer,pointer):uint64').bind(lib[:rb_tr_setjmp_wrapper_pointer1_to_size_t])
INT_POINTER2_TO_POINTER_WRAPPER = Primitive.interop_eval_nfi('(pointer,sint32,pointer,pointer):pointer').bind(lib[:rb_tr_setjmp_wrapper_int_pointer2_to_pointer])
POINTER2_INT_TO_POINTER_WRAPPER = Primitive.interop_eval_nfi('(pointer,pointer,pointer,sint32):pointer').bind(lib[:rb_tr_setjmp_wrapper_pointer2_int_to_pointer])
POINTER2_INT_POINTER2_TO_POINTER_WRAPPER = Primitive.interop_eval_nfi('(pointer,pointer,pointer,sint32,pointer,pointer):pointer').bind(lib[:rb_tr_setjmp_wrapper_pointer2_int_pointer2_to_pointer])
RB_BLOCK_CALL_FUNC_WRAPPER = POINTER2_INT_POINTER2_TO_POINTER_WRAPPER
RB_DEFINE_METHOD_WRAPPERS = [
# argc=0 still means passing (VALUE self) for rb_define_method
# argc >= 0 # (VALUE obj); (VALUE obj, VALUE arg1); (VALUE obj, VALUE arg1, VALUE arg2); ...
*POINTER_TO_POINTER_WRAPPERS[1..-1],
nil,
# argc == -2 # (VALUE obj, VALUE rubyArrayArgs)
POINTER_TO_POINTER_WRAPPERS[2],
# argc == -1 # (int argc, VALUE *argv, VALUE obj)
INT_POINTER2_TO_POINTER_WRAPPER
]
end
extend self
T_NONE = 0x00
T_OBJECT = 0x01
T_CLASS = 0x02
T_MODULE = 0x03
T_FLOAT = 0x04
T_STRING = 0x05
T_REGEXP = 0x06
T_ARRAY = 0x07
T_HASH = 0x08
T_STRUCT = 0x09
T_BIGNUM = 0x0a
T_FILE = 0x0b
T_DATA = 0x0c
T_MATCH = 0x0d
T_COMPLEX = 0x0e
T_RATIONAL = 0x0f
T_NIL = 0x11
T_TRUE = 0x12
T_FALSE = 0x13
T_SYMBOL = 0x14
T_FIXNUM = 0x15
T_UNDEF = 0x16
T_IMEMO = 0x1a
T_NODE = 0x1b
T_ICLASS = 0x1c
T_ZOMBIE = 0x1d
T_MASK = 0x1f
RUBY_FIXNUM_MIN = -(1 << 62)
RUBY_FIXNUM_MAX = (1 << 62) - 1
# This list of types is derived from MRI's error.c builtin_types array.
# It has the same indices as the ruby_value_type enum.
BUILTIN_TYPES = [
'',
'Object',
'Class',
'Module',
'Float',
'String',
'Regexp',
'Array',
'Hash',
'Struct',
'Integer',
'File',
'Data',
'MatchData',
'Complex',
'Rational',
'',
'nil',
'true',
'false',
'Symbol',
'Integer',
'undef',
'',
'',
'',
'Memo',
'Node',
'iClass'
]
RUBY_ENC_CODERANGE_UNKNOWN = 0
RUBY_ENC_CODERANGE_7BIT = 1
RUBY_ENC_CODERANGE_VALID = 2
RUBY_ENC_CODERANGE_BROKEN = 4
RUBY_ECONV_INVALID_MASK = Encoding::Converter::INVALID_MASK
RUBY_ECONV_INVALID_REPLACE = Encoding::Converter::INVALID_REPLACE
RUBY_ECONV_UNDEF_MASK = Encoding::Converter::UNDEF_MASK
RUBY_ECONV_UNDEF_REPLACE = Encoding::Converter::UNDEF_REPLACE
RUBY_ECONV_UNDEF_HEX_CHARREF = Encoding::Converter::UNDEF_HEX_CHARREF
RUBY_ECONV_UNIVERSAL_NEWLINE_DECORATOR = Encoding::Converter::UNIVERSAL_NEWLINE_DECORATOR
RUBY_ECONV_CRLF_NEWLINE_DECORATOR = Encoding::Converter::CRLF_NEWLINE_DECORATOR
RUBY_ECONV_CR_NEWLINE_DECORATOR = Encoding::Converter::CR_NEWLINE_DECORATOR
RUBY_ECONV_XML_TEXT_DECORATOR = Encoding::Converter::XML_TEXT_DECORATOR
RUBY_ECONV_XML_ATTR_CONTENT_DECORATOR = Encoding::Converter::XML_ATTR_CONTENT_DECORATOR
RUBY_ECONV_XML_ATTR_QUOTE_DECORATOR = Encoding::Converter::XML_ATTR_QUOTE_DECORATOR
RUBY_ECONV_PARTIAL_INPUT = Encoding::Converter::PARTIAL_INPUT
RUBY_ECONV_AFTER_OUTPUT = Encoding::Converter::AFTER_OUTPUT
# Rails 6 overrides `Time.at` in a way that doesn't delegate keyword arguments to the original `Time.at` method.
# The issue was fixed in Rails 6.1 but wasn't backported.
# It causes ArgumentError exception when `rb_time_timespec_new` function is called in the `pg` gem.
# See https://github.com/rails/rails/issues/47586.
ORIGINAL_TIME_AT = Time.method(:at)
def self.init_libtruffleruby(libtruffleruby)
SET_LIBTRUFFLERUBY.call(libtruffleruby)
libtruffleruby.rb_tr_init(Truffle::CExt)
SETUP_WRAPPERS.call(libtruffleruby) if SULONG
end
def self.init_libtrufflerubytrampoline(libtrampoline)
keep_alive = []
# rb_tr_longwrap_sig = Primitive.interop_eval_nfi('(sint64):pointer')
# rb_tr_longwrap = rb_tr_longwrap_sig.createClosure(self.rb_tr_wrap_function)
#
# globals_args = [
# rb_tr_longwrap
# ]
# keep_alive << globals_args
#
# init_globals = libtrampoline['rb_tr_trampoline_init_globals']
# init_globals = Primitive.interop_eval_nfi("(#{Array.new(globals_args.size, 'pointer').join(',')}):void").bind(init_globals)
# init_globals.call(*globals_args)
init_functions = libtrampoline[:rb_tr_trampoline_init_functions]
init_functions = Primitive.interop_eval_nfi('(env,(string):pointer):void').bind(init_functions)
init_functions.call(-> name { LIBTRUFFLERUBY[name] })
init_constants = libtrampoline[:rb_tr_trampoline_init_global_constants]
init_constants = Primitive.interop_eval_nfi('((string):pointer):void').bind(init_constants)
# TODO: use a Hash instead to be faster? (or Array with fixed indices)
init_constants.call(-> name { value = Truffle::CExt.send(name); keep_alive << value; Primitive.cext_wrap(value) })
LIBTRUFFLERUBY.set_rb_tr_rb_f_notimplement(libtrampoline[:rb_f_notimplement])
SET_LIBTRAMPOLINE.call(libtrampoline)
SETUP_WRAPPERS.call(libtrampoline)
@init_libtrufflerubytrampoline_keep_alive = keep_alive.freeze
end
def init_extension(library, library_path)
name = File.basename(library_path)
# We need the substring before the first dot, for "cool.io_ext.so" -> "Init_cool"
i = name.index('.')
name = name[0...i] if i
function_name = "Init_#{name}"
init_function = library[function_name]
begin
Primitive.call_with_c_mutex_and_frame(VOID_TO_VOID_WRAPPER, [init_function], nil, nil)
ensure
resolve_registered_addresses
end
end
def supported?
Interop.mime_type_supported?('application/x-sulong-library')
end
def check_abi_version(embedded_abi_version, extension_path)
runtime_abi_version = Truffle::GemUtil::ABI_VERSION
if embedded_abi_version != runtime_abi_version
message = "The native extension at #{extension_path} has a different ABI version: #{embedded_abi_version.inspect} " \
"than the running TruffleRuby: #{runtime_abi_version.inspect}"
warn message, uplevel: 1
raise LoadError, message
end
end
def rb_stdin
$stdin
end
def rb_stdout
$stdout
end
def rb_stderr
$stderr
end
def rb_fs
$;
end
def rb_output_fs
$,
end
def rb_rs
$/
end
def rb_output_rs
$\
end
def rb_default_rs
"\n"
end
def rb_to_symbol(name)
case name
when Symbol
name
else
converted = Truffle::Type.rb_check_convert_type(name , String, :to_str)
raise TypeError, "#{name} is not a symbol" unless converted
converted.to_sym
end
end
def rb_type(value)
# TODO CS 23-Jul-16 we could do with making this a kind of specialising case
# that puts never seen cases behind a transfer
value_class = Primitive.class(value)
type = Primitive.object_hidden_var_get(value_class, RB_TYPE)
type ||= Primitive.object_hidden_var_set(value_class, RB_TYPE, rb_tr_find_type(value))
rb_tr_cached_type(value, type)
end
def rb_tr_cached_type(value, type)
if type == T_NONE
if Primitive.object_hidden_var_defined?(value, DATA_STRUCT)
T_DATA
else
T_OBJECT
end
elsif type == T_FIXNUM
if RUBY_FIXNUM_MIN <= value && value <= RUBY_FIXNUM_MAX
T_FIXNUM
else
T_BIGNUM
end
else
type
end
end
def rb_tr_find_type(value)
case value
when Class
T_CLASS
when Module
T_MODULE
when Float
T_FLOAT
when String
T_STRING
when Regexp
T_REGEXP
when Array
T_ARRAY
when Hash
T_HASH
when Struct
T_STRUCT
when IO
T_FILE
when Complex
T_COMPLEX
when Rational
T_RATIONAL
when NilClass
T_NIL
when TrueClass
T_TRUE
when FalseClass
T_FALSE
when Symbol
T_SYMBOL
when Integer
# See #rb_tr_cached_type, the final type must be calculated for each number.
T_FIXNUM
when Time
T_DATA
when BasicObject
# See #rb_tr_cached_type, the final type must be calculated for each object.
T_NONE
else
raise "unknown type #{Primitive.class(value)}"
end
end
def RB_TYPE_P(value, type)
rb_type(value) == type
end
def rb_check_type(value, type)
value_type = rb_type(value)
if value_type != type || (value_type == T_DATA && Primitive.object_hidden_var_defined?(value, DATA_TYPE))
raise TypeError, "wrong argument type #{Truffle::ExceptionOperations.to_class_name(value)} (expected #{BUILTIN_TYPES[type]})"
end
end
def RTYPEDDATA_P(obj)
Primitive.object_hidden_var_defined?(obj, DATA_TYPE)
end
def ensure_class(obj, klass, message = 'expected class %s, but object class is %s')
raise TypeError, format(message, klass, Primitive.class(obj)) unless Primitive.is_a?(obj, klass)
end
def rb_method_boundp(klass, id, ex)
if ex == 0
(klass.method_defined?(id) || klass.private_method_defined?(id) || klass.protected_method_defined?(id)) ? 1 : 0
else
klass.method_defined?(id) ? 1 : 0
end
end
def rb_obj_is_instance_of(object, ruby_class)
Primitive.class(object) == ruby_class
end
def rb_obj_is_kind_of(object, ruby_class)
Primitive.is_a?(object, ruby_class)
end
def SYMBOL_P(value)
Primitive.is_a?(value, Symbol)
end
def rb_to_int(val)
Primitive.rb_to_int(val)
end
def rb_fix2int(value)
Primitive.rb_num2int(value)
end
def rb_fix2uint(value)
Truffle::Type.rb_num2uint(value)
end
def rb_fix2str(value, base)
value.to_s(base)
end
def RB_FLOAT_TYPE_P(value)
Primitive.is_a?(value, Float)
end
def rb_integer_type_p(value)
Primitive.ruby_integer?(value)
end
def rb_require(feature)
require feature
end
def RB_OBJ_TAINTABLE(object)
case object
when TrueClass, FalseClass, NilClass, Integer, Float, Symbol
false
else
true
end
end
def rb_obj_clone(object)
object.clone
end
def rb_obj_dup(object)
object.dup
end
def rb_obj_encoding(object)
object.encoding
end
FREEZE_METHOD = Kernel.instance_method :freeze
def rb_obj_freeze(obj)
FREEZE_METHOD.bind(obj).call
end
def rb_obj_frozen_p(object)
object.frozen?
end
def rb_obj_id(object)
object.object_id
end
def rb_float_new(value)
value.to_f
end
def rb_flt_rationalize(value)
value.rationalize
end
def rb_flt_rationalize_with_prec(value, prec)
value.rationalize(prec)
end
def rb_absint_singlebit_p(val)
Primitive.rb_int_singlebit_p(val.abs)
end
def rb_num2int(val)
Primitive.rb_num2int(val)
end
def rb_num2long(val)
Primitive.rb_num2long(val)
end
def rb_big_sign(val)
val >= 0
end
def rb_big_cmp(x, y)
x <=> y
end
def rb_big2dbl(val)
Truffle::Type.rb_big2dbl(val)
end
def rb_big2long(val)
Truffle::Type.rb_big2long(val)
end
def rb_big2ulong(val)
Truffle::Type.rb_big2long(val)
end
def rb_dbl2big(val)
val.to_i
end
def rb_num_coerce_bin(x, y, func)
a, b = do_coerce(x, y, true)
a.__send__(func, b)
end
def rb_num_coerce_cmp(x, y, func)
ary = do_coerce(x, y, false)
if Primitive.nil?(ary)
nil
else
a, b = ary
a.__send__(func, b)
end
end
def rb_num_coerce_relop(x, y, func)
ary = do_coerce(x, y, false)
unless Primitive.nil?(ary)
a, b = ary
res = a.__send__(func, b)
end
raise ArgumentError, "comparison of #{Primitive.class(x)} with #{Primitive.class(y)} failed" if Primitive.nil?(res)
res
end
private def do_coerce(x, y, raise_error)
unless y.respond_to?(:coerce)
if raise_error
raise TypeError, "#{Primitive.class(y)} can't be coerced to #{Primitive.class(x)}"
else
return nil
end
end
ary = y.coerce(x)
if Primitive.nil?(ary) && !raise_error
return nil
end
if !Primitive.is_a?(ary, Array) || ary.size != 2
raise TypeError, 'coerce must return [x, y]'
end
ary
end
def rb_num2uint(val)
Truffle::Type.rb_num2uint(val)
end
def rb_num2ulong(val)
# We're going to create a signed long here, and rely on the C to
# cast it to an unsigned one.
Truffle::Type.rb_num2ulong(val)
end
def rb_num2dbl(val)
Truffle::Type.rb_num2dbl(val)
end
def rb_Integer(value)
Integer(value)
end
def rb_Float(value)
Float(value)
end
def RFLOAT_VALUE(value)
value
end
def rb_hash_start(h)
Primitive.vm_hash_start(h)
end
def rb_obj_class(object)
Primitive.class(object)
end
def rb_obj_classname(object)
Primitive.class(object).name
end
def rb_class_of(object)
Primitive.metaclass(object)
end
def rb_singleton_class(object)
object.singleton_class
end
def rb_class_real(ruby_class)
while ruby_class.singleton_class?
ruby_class = ruby_class.superclass
end
ruby_class
end
def rb_obj_respond_to(object, name, priv)
object.respond_to?(name, priv != 0)
end
def rb_respond_to(object, name)
object.respond_to?(name, false)
end
def rb_check_convert_type(obj, type_name, method)
Truffle::Type.rb_check_convert_type(obj, Object.const_get(type_name), method.to_sym)
end
def rb_convert_type(obj, type_name, method)
Truffle::Type.rb_convert_type(obj, Object.const_get(type_name), method.to_sym)
end
def rb_check_to_integer(obj, method)
Truffle::Type.rb_check_to_integer(obj, method.to_sym)
end
def rb_obj_method_arity(object, id)
object.method(id).arity
end
def rb_obj_method(object, id)
object.method(id)
end
def rb_ivar_defined(object, id)
Primitive.object_ivar_defined?(object, id)
end
def rb_f_global_variables
Kernel.global_variables
end
def rb_ivar_foreach(object, func, arg)
keys_and_vals = []
if Primitive.is_a?(object, Module)
keys_and_vals << :__classpath__
keys_and_vals << object.name
object.class_variables.each do |key|
keys_and_vals << key
keys_and_vals << object.class_variable_get(key)
end
end
object.instance_variables.each do |key|
keys_and_vals << key
keys_and_vals << object.instance_variable_get(key)
end
keys_and_vals.each_slice(2) do |key, val|
st_result = Primitive.interop_execute(POINTER3_TO_INT_WRAPPER,
[func, Primitive.cext_sym2id(key), Primitive.cext_wrap(val), arg])
case st_result
when ST_CONTINUE
when ST_STOP then break
else raise ArgumentError, "Unknown 'func' return value: #{st_result}"
end
end
end
def rb_obj_instance_variables(object)
object.instance_variables
end
def rb_copy_generic_ivar(clone, original)
Primitive.check_frozen clone
original_ivars = original.instance_variables
rb_free_generic_ivar(clone)
original_ivars.each do |var|
clone.instance_variable_set(var, original.instance_variable_get(var))
end
end
def rb_free_generic_ivar(original)
Primitive.check_frozen original
original_ivars = original.instance_variables
original_ivars.each do |var|
original.__send__ :remove_instance_variable, var
end
end
def rb_inspect(object)
Truffle::Type.rb_inspect(object)
end
def rb_range_new(beg, last, exclude_end)
Range.new(beg, last, exclude_end != 0)
end
def rb_reg_new(pattern, options)
Regexp.new(pattern, options)
end
def rb_reg_compile(pattern, options)
err = nil
result = begin
Regexp.new(pattern, options)
rescue => err
nil
end
if err
Primitive.thread_set_exception(err)
nil
else
result
end
end
def rb_reg_new_str(str, options)
Regexp.new(str, options)
end
def rb_marshal_dump(obj, port)
Marshal.dump(obj, port)
end
def rb_marshal_load(port)
Marshal.load(port)
end
def rb_reg_regcomp(str)
Regexp.compile(str)
end
def rb_reg_match_pre(match)
match.pre_match
end
def rb_reg_nth_match(nth, match)
return nil if Primitive.nil?(match)
match[nth]
end
def rb_reg_options(re)
re.options
end
def ascii8bit_encoding
Encoding::ASCII_8BIT
end
def usascii_encoding
Encoding::US_ASCII
end
def utf8_encoding
Encoding::UTF_8
end
def rb_default_external_encoding
Encoding.find('external')
end
def rb_default_internal_encoding
Encoding.find('internal')
end
def rb_locale_encoding
Encoding::LOCALE
end
def rb_filesystem_encoding
Encoding.filesystem
end
def rb_to_encoding_index(enc)
enc = Truffle::Type.coerce_to_encoding(enc)
return -1 if Primitive.false?(enc)
rb_enc_to_index(enc)
end
def rb_locale_encindex
rb_enc_to_index Encoding::LOCALE
end
def rb_filesystem_encindex
rb_enc_to_index Encoding.filesystem
end
def rb_ascii8bit_encindex
rb_enc_to_index Encoding::ASCII_8BIT
end
def rb_usascii_encindex
rb_enc_to_index Encoding::US_ASCII
end
def rb_utf8_encindex
rb_enc_to_index Encoding::UTF_8
end
def rb_enc_from_index(index)
Primitive.encoding_get_encoding_by_index index
end
def rb_enc_find_index(name)
enc = Encoding.try_convert name
if enc
Primitive.encoding_get_encoding_index(enc)
else
-1
end
end
def rb_enc_to_index(enc)
Primitive.encoding_get_encoding_index enc
end
def rb_define_dummy_encoding(name)
_, idx = Truffle::EncodingOperations.dummy_encoding(name)
idx
end
def rb_str_new_frozen(value)
if value.frozen?
value
else
value.dup.freeze
end
end
def rb_tracepoint_new(events, func, data)
TracePoint.new(*events_to_events_array(events)) do |tp|
Primitive.call_with_c_mutex_and_frame(
POINTER2_TO_VOID_WRAPPER,
[func, Primitive.cext_wrap(tp), data],
Primitive.caller_special_variables_if_available,
nil)
end
end
def events_to_events_array(events)
events_ary = []
parse_event = -> bits, name do
if events.anybits? bits
events ^= bits
if Primitive.is_a?(name, Symbol)
events_ary << name
else
warn "warning: rb_tracepoint_new(#{name}) is not yet implemented" if $VERBOSE
events_ary << :never
end
end
end
parse_event[0x0001, :line]
parse_event[0x0002, :class]
parse_event[0x0004, :end]
parse_event[0x0008, :call]
parse_event[0x0010, :return]
parse_event[0x0020, :c_call]
parse_event[0x0040, :c_return]
parse_event[0x0080, :raise]
parse_event[0x0100, :b_call]
parse_event[0x0200, :b_return]
parse_event[0x0400, :thread_begin]
parse_event[0x0800, :thread_end]
parse_event[0x1000, :fiber_switch]
parse_event[0x2000, :script_compiled]
parse_event[0x100000, 'RUBY_INTERNAL_EVENT_NEWOBJ']
parse_event[0x200000, 'RUBY_INTERNAL_EVENT_FREEOBJ']
raise ArgumentError, "unknown event #{'%#x' % events}" unless events == 0
events_ary
end
def rb_thread_alone
Thread.list.count == 1 ? 1 : 0
end
def rb_intern(str)
Primitive.string_to_symbol(str, true)
end
def rb_int_cmp(a, b)
a <=> b
end
def rb_int_positive_pow(a, b)
a ** b
end
def rb_cstr_to_inum(string, base, raise)
Primitive.string_to_inum string, base, raise != 0, true
end
def rb_cstr_to_dbl(string, badcheck)
result = Primitive.string_to_f string
if Primitive.nil?(result)
if badcheck
raise ArgumentError, "invalid value for Float(): #{string.inspect}"
else
0.0
end
else
result
end
end
def rb_str_new_native(pointer, length)
raise "#{pointer} not a pointer" unless Truffle::Interop.pointer?(pointer)
Truffle::FFI::Pointer.new(pointer).read_string(length)
end
def rb_enc_str_coderange(str)
cr = Primitive.string_get_coderange str
coderange_java_to_rb(cr)
end
def coderange_java_to_rb(cr)
case cr
when 0
RUBY_ENC_CODERANGE_UNKNOWN
when 1
RUBY_ENC_CODERANGE_7BIT
when 2
RUBY_ENC_CODERANGE_VALID
when 3
RUBY_ENC_CODERANGE_BROKEN
else
raise "Cannot convert coderange #{cr} to rb code range"
end
end
def RB_ENC_CODERANGE(obj)
if Primitive.is_a?(obj, String)
rb_enc_str_coderange(obj)
else
raise "Unknown coderange for obj with class `#{Primitive.class(obj)}`"
end
end
def rb_enc_associate_index(obj, idx)
enc = rb_enc_from_index(idx)
case obj
when String
obj.force_encoding(enc)
else
raise "rb_enc_associate_index not implemented for class `#{Primitive.class(obj)}`"
end
end
def rb_enc_set_index(obj, idx)
enc = rb_enc_from_index(idx)
case obj
when String
obj.force_encoding enc
else
obj.instance_variable_set :@encoding, enc
end
end
def rb_enc_get(obj)
case obj
when Encoding
obj
when Symbol
obj.encoding
when String
obj.encoding
when Regexp
obj.encoding
else
obj.instance_variable_get :@encoding
end
end
def rb_enc_get_index(obj)
enc = case obj
when Symbol
obj.encoding
when String
obj.encoding
when Regexp
obj.encoding
when File
obj.internal_encoding || obj.external_encoding
when NilClass, Integer, Float, TrueClass, FalseClass
-1
# TODO BJF Mar-9-2017 Handle T_DATA
else
if obj.instance_variable_defined?(:@encoding)
obj.instance_variable_get(:@encoding)
else
0
end
end
enc = rb_enc_to_index(enc) if Primitive.is_a?(enc, Encoding)
enc
end
def rb_str_append(str, to_append)
Primitive.string_append(str, to_append)