forked from zeromq/zproject
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zproject_ruby.gsl
616 lines (559 loc) · 21 KB
/
zproject_ruby.gsl
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
# Generate minimal Ruby language bindings.
#
# These are not meant to be idiomatic, but to provide a minimal platform
# of FFI function bindings on which to base idiomatic Ruby classes.
#
# This is a code generator built using the iMatix GSL code generation
# language. See https://github.com/zeromq/gsl for details.
#
# Copyright (c) the Contributors as noted in the AUTHORS file.
# This file is part of zproject.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
register_target ("ruby", "Ruby binding")
# Target provides name space isolation for its functions
function target_ruby
# Work out Ruby name based on container.name and and set it as
# container.ruby_name.
function sanitize_ruby_container_name(container)
my.container.ruby_name = "$(my.container.name:c)"
# Replace default value from resolve_c_container().
if my.container.ruby_name = "_"
my.container.ruby_name = my.container.variadic ?? "args" ? "result"
endif
# Sanitize if it matches a Ruby keyword.
# Ruby keywords. The only keyword not listed here is 'defined?', but that
# won't be possible because of the 'c' pretty-print modifier above.
my.ruby_keywords_regexp = "^(BEGIN|END|__ENCODING__|__END__|__FILE__|__LINE__|alias|and|begin|break|case|class|def|do|else|elsif|end|ensure|false|for|if|in|module|next|nil|not|or|redo|rescue|retry|return|self|super|then|true|undef|unless|until|when|while|yield)$"
if regexp.match (my.ruby_keywords_regexp, my.container.ruby_name)
my.container.ruby_name += "_"
endif
endfunction
function resolve_ruby_container (container)
sanitize_ruby_container_name(my.container)
# Defaults
my.container.ruby_ffi_type = ":pointer"
my.container.ruby_doc_type = "::FFI::Pointer, #to_ptr"
# All C types should be transformed to a type name recognized by FFI.
# To handle more C types, add support for them here.
if my.container.variadic
my.container.ruby_doc_type = "Array<Object>"
my.container.ruby_ffi_type = ":varargs"
elsif my.container.c_type = "void"
my.container.ruby_doc_type = "void"
my.container.ruby_ffi_type = ":void"
elsif my.container.c_type = "size_t"
my.container.ruby_doc_type = "Integer, #to_int, #to_i"
my.container.ruby_ffi_type = ":size_t"
my.container.coerce_to_c = "Integer($(my.container.ruby_name:))"
elsif my.container.c_type = "int"
my.container.ruby_doc_type = "Integer, #to_int, #to_i"
my.container.ruby_ffi_type = ":int"
my.container.coerce_to_c = "Integer($(my.container.ruby_name:))"
elsif regexp.match ("^(uint[0-9]+)_t$", my.container.c_type, match)
my.container.ruby_doc_type = "Integer, #to_int, #to_i"
my.container.ruby_ffi_type = ":$(match:)"
my.container.coerce_to_c = "Integer($(my.container.ruby_name:))"
elsif my.container.c_type = "float"
my.container.ruby_doc_type = "Float, #to_f"
my.container.ruby_ffi_type = ":float"
my.container.coerce_to_c = "Float($(my.container.ruby_name:))"
elsif my.container.c_type = "double"
my.container.ruby_doc_type = "Float, #to_f"
my.container.ruby_ffi_type = ":double"
my.container.coerce_to_c = "Float($(my.container.ruby_name:))"
elsif my.container.c_type = "bool"
my.container.ruby_doc_type = "Boolean"
my.container.ruby_ffi_type = ":bool"
my.container.coerce_to_c = "!(0==$(my.container.ruby_name:)||!$(my.container.ruby_name:)) # boolean"
elsif my.container.c_type = "const char *"
my.container.ruby_doc_type = "String, #to_s, nil"
my.container.ruby_ffi_type = ":string"
elsif my.container.c_type = "char *"
if my.container.fresh
my.container.ruby_doc_return_type = "::FFI::AutoPointer"
# if it's a fresh string that we have to free() when done with it,
# wrap pointer in an FFI::AutoPointer
my.container.coerce_to_ruby = "::FFI::AutoPointer.new($(my.container.ruby_name:), LibC.method(:free))"
endif
elsif my.container.c_type = "byte"
my.container.ruby_doc_type = "Integer, #to_int, #to_i"
my.container.ruby_ffi_type = ":char"
my.container.coerce_to_c = "Integer($(my.container.ruby_name:))"
elsif my.container.c_type = "SOCKET"
my.container.ruby_doc_type = "Integer or FFI::Pointer"
my.container.ruby_ffi_type = "(::FFI::Platform.unix? ? :int : :uint64)" # support for Unix & Win64
elsif count (project.class, defined (class.RubyName) & (my.container.type = class.c_name))
for project.class where (defined (class.RubyName) & (my.container.type = class.c_name))
if my.container.by_reference
if defined (my.container.destructor_self)
my.container.coerce_to_c = "__ptr_give_ref"
else
my.container.ruby_doc_type = "#__ptr_give_ref"
my.container.coerce_to_c = "$(my.container.ruby_name:).__ptr_give_ref"
endif
else
my.container.ruby_doc_type = "$(class.RubyName:), #__ptr"
my.container.coerce_to_c = "$(my.container.ruby_name:).__ptr if $(my.container.ruby_name:)"
my.container.coerce_to_ruby = "$(class.RubyName:).__new $(my.container.ruby_name:), "
my.container.coerce_to_ruby += my.container.fresh ?? "true" ? "false"
endif
endfor
endif
endfunction
function resolve_ruby_method (method)
my.method.ruby_name = "$(my.method.name:c)"
for my.method.argument
resolve_ruby_container (argument)
endfor
for my.method.return as ret
resolve_ruby_container (ret)
endfor
endfunction
# The line that attaches the function to the project's FFI module
# like: attach_function my_project_method, [:pointer], :int, **opts
function ruby_ffi_attach_definition(method)
my.attach_definition = "attach_function :$(class.c_name)_$(method.c_name:), ["
if !my.method.singleton
my.attach_definition += ":pointer"
if count (my.method.argument)
my.attach_definition += ", "
endif
endif
for my.method.argument
my.attach_definition += "$(argument.ruby_ffi_type:)"
if !last ()
my.attach_definition += ", "
endif
endfor
my.attach_definition += "], $(method->return.ruby_ffi_type:), **opts"
return my.attach_definition
endfunction
# Returns the Ruby method call without arguments,
# like: ::MyProject::FFI.my_class_my_method
function ruby_method_call_without_arguments(method)
# must not contain newline at the end
my.call = "::$(project.RubyName:)::FFI.$(class.c_name:)_$(my.method.c_name:)"
return my.call
endfunction
# The arguments passed to the inner method call,
# like: arg1, arg2, args*
#
# If it's a singleton method, or the class method of a polymorphic method, make
# sure to set self_p first (before the call).
function ruby_method_call_arguments(method)
my.args = ""
if !my.method.singleton
my.args += "self_p"
if count(my.method.argument)
my.args += ", "
endif
endif
for my.method.argument
my.args += argument.variadic ?? "*" ? ""
my.args += argument.ruby_name
if !last ()
my.args += ", "
endif
endfor
return my.args
endfunction
function ruby_method_signature_arguments(method)
my.args = ""
for my.method.argument
if !(my.method.is_destructor & first())
my.args += argument.variadic ?? "*" ? ""
my.args += argument.ruby_name
if !last ()
my.args += ", "
endif
endif
endfor
return my.args
endfunction
# The first line of the monomorphic method definition (either class or instance method)
# like: def my_method(arg1, arg2)
# or: def self.my_method(arg1, arg2)
function ruby_monomorphic_method_signature(method)
my.def_line = ""
if my.method.singleton & !my.method.is_destructor
my.def_line += "self."
endif
my.def_line += "$(my.method.c_name:)($(ruby_method_signature_arguments(my.method)))"
return my.def_line
endfunction
# Ruby methods, which take a pointer to the receiving object,
# like: def self.my_method(self_p, arg1, arg2)
function ruby_polymorphic_method_signature(method)
my.def_line = "self.$(my.method.c_name:)(self_p"
my.def_line += count(my.method.argument) ?? ", " ? ""
my.def_line += ruby_method_signature_arguments(my.method)
my.def_line += ")"
return my.def_line
endfunction
function ruby_doc_return_type (method)
if defined(my.method->return.ruby_doc_return_type)
return my.method->return.ruby_doc_return_type
endif
if defined(string.locate (my.method->return.ruby_doc_type, ","))
# turn "Integer, #to_int, #to_i" into "Integer"
return string.prefix (my.method->return.ruby_doc_type, ",")
else
return my.method->return.ruby_doc_type
endif
endfunction
function ruby_doc_arg_description (argument)
if my.argument.variadic
return " see https://github.com/ffi/ffi/wiki/examples#using-varargs"
else
return ""
endif
endfunction
function resolve_ruby_class (class)
for my.class.constructor as method
resolve_ruby_method (method)
endfor
for my.class.destructor as method
resolve_ruby_method (method)
endfor
for my.class.method
resolve_ruby_method (method)
endfor
for my.class.callback_type as method
resolve_ruby_method (method)
endfor
endfunction
.macro generate_ruby_binding
.directory.create ("bindings/ruby/lib/$(project.name:c)/ffi")
.output "bindings/ruby/lib/$(project.name:c)/ffi/version.rb"
$(project.GENERATED_WARNING_HEADER:)
module $(project.RubyName:)
module FFI
VERSION = '$(project->version.major).$(project->version.minor).$(project->version.patch)'
end
end
$(project.GENERATED_WARNING_HEADER:)
.#
.output "bindings/ruby/lib/$(project.name:c)/ffi.rb"
$(project.GENERATED_WARNING_HEADER:)
require 'ffi'
require_relative 'ffi/version'
module $(project.RubyName:)
module FFI
module LibC
extend ::FFI::Library
ffi_lib ::FFI::Platform::LIBC
attach_function :free, [ :pointer ], :void, blocking: true
end
extend ::FFI::Library
def self.available?
@available
end
begin
lib_name = '$(project.libname)'
lib_dirs = ['/usr/local/lib', '/opt/local/lib', '/usr/lib64']
env_name = "#{lib_name.upcase}_PATH"
lib_dirs = [*ENV[env_name].split(':'), *lib_dirs] if ENV[env_name]
lib_paths = lib_dirs.map { |path| "#{path}/#{lib_name}.#{::FFI::Platform::LIBSUFFIX}" }
ffi_lib lib_paths + [lib_name]
@available = true
rescue LoadError
warn ""
warn "WARNING: ::$(project.RubyName:)::FFI is not available without $(project.libname)."
warn ""
@available = false
end
def self.attach_function(name, *rest)
super
rescue ::FFI::NotFoundError
define_singleton_method name do |*|
raise NotImplementedError, "The function #{name}() is not provided by the $(project.name:) library installed. Upgrade the library or compile it with --enable-drafts."
end
return unless $VERBOSE || $DEBUG
warn "The function #{name}() is not provided by the installed $(project.name:) library."
end
if available?
opts = {
blocking: true # only necessary on MRI to deal with the GIL.
}
.for class where defined (class.api) & class.private = "0"
.for constructor as method
$(ruby_ffi_attach_definition (method))
.endfor
.for destructor as method
$(ruby_ffi_attach_definition (method))
.endfor
.for method
$(ruby_ffi_attach_definition (method))
.endfor
require_relative 'ffi/$(class.ruby_require:)'
.endfor
end
end
end
$(project.GENERATED_WARNING_HEADER:)
.#
.for class where defined (class.api) & class.private = "0"
.output "bindings/ruby/lib/$(project.name:c)/ffi/$(class.ruby_require:).rb"
$(project.GENERATED_WARNING_HEADER:)
module $(project.RubyName:)
module FFI
# $(class.description:no,block)
# @note This class is 100% generated using zproject.
. # TODO: extract boilerplate into a reusable module
class $(class.RubyName:)
.for class.constant
# $(constant.description:no,block)
$(CONSTANT.NAME:c) = $(constant.value)
.endfor
# Raised when one tries to use an instance of {$(class.RubyName:)} after
# the internal pointer to the native object has been nullified.
class DestroyedError < RuntimeError; end
# Boilerplate for self pointer, initializer, and finalizer
class << self
alias :__new :new
end
# Attaches the pointer _ptr_ to this instance and defines a finalizer for
# it if necessary.
# @param ptr [::FFI::Pointer]
# @param finalize [Boolean]
def initialize(ptr, finalize = true)
@ptr = ptr
if @ptr.null?
. # TODO: extract to method #attach_native(ptr)
@ptr = nil # Remove null pointers so we don't have to test for them.
elsif finalize
@finalizer = self.class.create_finalizer_for @ptr
ObjectSpace.define_finalizer self, @finalizer
end
end
.for class.destructor where count (destructor.argument) = 1
. if first ()
. class.has_ruby_finalizer = 1
# @param ptr [::FFI::Pointer]
# @return [Proc]
def self.create_finalizer_for(ptr)
Proc.new do
ptr_ptr = ::FFI::MemoryPointer.new :pointer
ptr_ptr.write_pointer ptr
::$(project.RubyName:)::FFI.$(class.c_name)_$(destructor.c_name) ptr_ptr
end
end
. endif
.endfor
.if !defined (class.has_ruby_finalizer)
.# TODO: just raise an ImplicitDestroyError
# @return [Proc]
def self.create_finalizer_for(ptr)
Proc.new do
"WARNING: "\\
"Objects of type #{self} cannot be destroyed implicitly. "\\
"Please call the correct destroy method with the relevant arguments."
end
end
.endif
# @return [Boolean]
def null?
!@ptr or @ptr.null?
end
# Return internal pointer
# @return [::FFI::Pointer]
def __ptr
raise DestroyedError unless @ptr
@ptr
end
# So external Libraries can just pass the Object to a FFI function which expects a :pointer
alias_method :to_ptr, :__ptr
# Nullify internal pointer and return pointer pointer.
# @note This detaches the current instance from the native object
# and thus makes it unusable.
# @return [::FFI::MemoryPointer] the pointer pointing to a pointer
# pointing to the native object
def __ptr_give_ref
raise DestroyedError unless @ptr
ptr_ptr = ::FFI::MemoryPointer.new :pointer
ptr_ptr.write_pointer @ptr
__undef_finalizer if @finalizer
@ptr = nil
ptr_ptr
end
# Undefines the finalizer for this object.
# @note Only use this if you need to and can guarantee that the native
# object will be freed by other means.
# @return [void]
def __undef_finalizer
ObjectSpace.undefine_finalizer self
@finalizer = nil
end
.for callback_type
# Create a new callback of the following type:
# $(callback_type.description:no,block)
# $(c_callback_typedef (callback_type):no,block)
#
# @note WARNING: If your Ruby code doesn't retain a reference to the
# FFI::Function object after passing it to a C function call,
# it may be garbage collected while C still holds the pointer,
# potentially resulting in a segmentation fault.
def self.$(callback_type.name)
::FFI::Function.new $(callback_type->return.ruby_ffi_type:), [\
. for callback_type.argument
$(argument.ruby_ffi_type:)\
. if !last ()
, \
. endif
. endfor
], blocking: true do \|\
. for callback_type.argument
$(argument.ruby_name)\
. if !last ()
, \
. endif
. endfor
\|
. for callback_type.argument where defined (argument.coerce_to_ruby)
$(argument.ruby_name) = $(argument.coerce_to_ruby:)
. endfor
result = yield \
. for callback_type.argument
$(argument.ruby_name)\
. if !last ()
, \
. endif
. endfor
.if defined (callback_type->return.coerce_to_c)
result = $(callback_type->return.coerce_to_c:)
.endif
result
end
end
.endfor
.for constructor as method
# $(method.description:no,block)
.for method.argument
# @param $(argument.ruby_name:) [$(argument.ruby_doc_type:)]
.endfor
# @return [$(project.RubyName:)::$(class.RubyName:)]
def $(ruby_monomorphic_method_signature(method))
.for method.argument where defined (argument.coerce_to_c)
$(argument.ruby_name:) = $(argument.coerce_to_c:)
.endfor
ptr = $(ruby_method_call_without_arguments(method))($(ruby_method_call_arguments(method)))
__new ptr
end
.endfor
.for destructor as method
# $(method.description:no,block)
#
# @return [void]
def $(ruby_monomorphic_method_signature(method))
return unless @ptr
.for method.argument where defined (argument.coerce_to_c)
$(argument.ruby_name:) = $(argument.coerce_to_c:)
.endfor
result = $(ruby_method_call_without_arguments(method))($(ruby_method_call_arguments(method)))
.if defined (method->return.coerce_to_ruby)
result = $(method->return.coerce_to_ruby:)
.endif
result
end
.endfor
.for method
# $(method.description:no,block)
#
.for method.argument
# @param $(argument.ruby_name:) [$(argument.ruby_doc_type:)]$(ruby_doc_arg_description (argument):)
.endfor
# @return [$(ruby_doc_return_type (method):)]
def $(ruby_monomorphic_method_signature(method))
.if !method.singleton
raise DestroyedError unless @ptr
.# we do this so actuall FFI call of monomorphic and polymorphic methods is the same
self_p = @ptr
.endif
.for method.argument where defined (argument.coerce_to_c)
$(argument.ruby_name:) = $(argument.coerce_to_c:)
.endfor
result = $(ruby_method_call_without_arguments(method))($(ruby_method_call_arguments(method)))
.if defined (method->return.coerce_to_ruby)
result = $(method->return.coerce_to_ruby:)
.endif
result
end
.if method.polymorphic & !method.singleton # only methods that aren't already singletons
.#
.# NOTE: polymorphic methods will result in 2 Ruby methods:
.# * a normal instance method (already produced above)
.# * a class ("singleton") method, which takes a polymorphic reference
# $(method.description:no,block)
#
# This is the polymorphic version of #$(method.ruby_name:).
#
# @param self_p [$(project.RubyName:)::$(class.RubyName:), #__ptr, ::FFI::Pointer, nil]
# object reference to use this method on
.for method.argument
# @param $(argument.ruby_name:) [$(argument.ruby_doc_type:)]$(ruby_doc_arg_description (argument):)
.endfor
# @return [$(ruby_doc_return_type (method):)]
def $(ruby_polymorphic_method_signature(method))
self_p = self_p.__ptr if self_p.respond_to?(:__ptr)
.for method.argument where defined (argument.coerce_to_c)
$(argument.ruby_name:) = $(argument.coerce_to_c:)
.endfor
result = $(ruby_method_call_without_arguments(method))($(ruby_method_call_arguments(method)))
.if defined (method->return.coerce_to_ruby)
result = $(method->return.coerce_to_ruby:)
.endif
result
end
.endif
.endfor
end
end
end
$(project.GENERATED_WARNING_HEADER:)
.endfor
.#
.if !file.exists ("bindings/ruby/Rakefile")
.output "bindings/ruby/Rakefile"
require 'rspec/core/rake_task'
task :default => :test
# Run tests.
RSpec::Core::RakeTask.new :test do |c|
end
.else
. echo "NOT regenerating an existing bindings/ruby/Rakefile file; you might want to move yours out of the way and re-generate the project again to get updated settings"
.endif
.#
.directory.create ("bindings/ruby/spec")
.if !file.exists ("bindings/ruby/spec/spec_helper.rb")
.output "bindings/ruby/spec/spec_helper.rb"
require '$(project.name)/ffi'
RSpec.configure do |c|
# Enable 'should' syntax
c.expect_with(:rspec) { |c| c.syntax = [:should, :expect] }
c.mock_with(:rspec) { |c| c.syntax = [:should, :expect] }
end
.else
. echo "NOT regenerating an existing bindings/ruby/spec/spec_helper.rb file; you might want to move yours out of the way and re-generate the project again to get updated settings"
.endif
.#
.output "bindings/ruby/spec/ffi_spec.rb"
$(project.GENERATED_WARNING_HEADER:)
require 'spec_helper'
describe ::$(project.RubyName:)::FFI do
it { should be }
end
$(project.GENERATED_WARNING_HEADER:)
.endmacro
project.RubyName = "$(project.name:Pascal)"
for class where defined (class.api) & class.private = "0"
class.ruby_require = string.replace (class.c_name, "$(project.name)_|")
class.RubyName = "$(class.ruby_require:Pascal)"
endfor
for class where defined (class.api) & class.private = "0"
resolve_ruby_class (class)
endfor
generate_ruby_binding ()
endfunction