forked from mobiruby/BridgeSupport
-
Notifications
You must be signed in to change notification settings - Fork 6
/
gen_bridge_metadata.rb
executable file
·2535 lines (2354 loc) · 80.5 KB
/
gen_bridge_metadata.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
#!/usr/bin/ruby
# -*- coding: utf-8; mode: ruby; indent-tabs-mode: true; ruby-indent-level: 4; tab-width: 8 -*-
# Copyright (c) 2006-2012, Apple Inc. All rights reserved.
# Copyright (c) 2005-2006 FUJIMOTO Hisakuni
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of Apple Inc. ("Apple") nor the names of
# its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# If we have a <ROOT>/System/Library/BridgeSupport/ruby-{version} path in
# the module search path, then set $slb to <ROOT>/System/Library/BridgeSupport.
# Otherwise, if this script is called as <ROOT>/usr/bin/gen_bridge_metadata,
# then set $slb to <ROOT>/System/Library/BridgeSupport.
$slb = $_slb_ = '/System/Library/BridgeSupport'
_slbr_ = "#{$slb}/ruby-#{RUBY_VERSION.sub(/^(\d+\.\d+)(\..*)?$/, '\1')}"
$:.unshift(_slbr_) unless $:.any? do |p|
if %r{#{_slbr_}$} =~ p
$slb = File.dirname(p)
true
end
end
if $slb == $_slb_
rel = $0.dup
if rel.sub!(%r{/usr/bin/gen_bridge_metadata$}, '') and !rel.empty?
$slb = "#{rel}/#{$_slb_}"
end
end
def getcc(sdkroot = '/')
return $_cc if $_cc
if File.exists?('/usr/bin/xcrun')
out = `/usr/bin/xcrun -sdk #{sdkroot} -find cc`.chomp
return $_cc = out unless out.empty?
end
return $_cc = 'cc'
end
require 'rexml/document'
require 'fileutils'
require 'optparse'
require 'tmpdir'
require 'pathname'
require 'ostruct'
require 'shellwords'
require 'bridgesupportparser'
class OCHeaderAnalyzer
CPP = ['/usr/bin/cpp-4.2', '/usr/bin/cpp-4.0', '/usr/bin/cpp'].find { |x| File.exist?(x) }
raise "Can't find cpp: have you installed Xcode and the command-line tools?" if CPP.nil?
CPPFLAGS = "-D__APPLE_CPP__ -D__BLOCKS__ -include /usr/include/AvailabilityMacros.h"
CPPFLAGS << " -D__GNUC__" unless /^cpp-4/.match(File.basename(CPP))
def self.data(data)
new(data)
end
def self.path(path, fails_on_error=true, do_64=false, flags='')
complete, filtered = OCHeaderAnalyzer.do_cpp(path, fails_on_error, do_64, flags)
new(filtered, complete, path)
end
def initialize(data, complete_data=nil, path=nil)
@externname = 'extern'
@cpp_result = data
@complete_cpp_result = complete_data
@path = path
end
# Get the list of C enumerations, as a Hash object (keys are the enumeration
# names and values are their values.
def enums
if @enums.nil?
re = /\benum\b\s*(\w+\s+)?\{([^}]*)\}/
@enums = {}
@cpp_result.scan(re).each do |m|
m[1].split(',').map do |i|
name, val = i.split('=', 2).map { |x| x.strip }
@enums[name] = val unless name.empty? or name[0] == ?#
end
end
end
@enums
end
def file_content
if @file_content.nil?
@file_content = File.read(@path)
# This is very naive, and won't work with embedded comments, but it
# should be enough for now.
@file_content.gsub!(%r{/\*([^*]+)\*/}, '')
@file_content.gsub!(%r{//.+$}, '')
end
@file_content
end
# Get the list of `#define KEY VAL' macros, as an Hash object.
def defines
if @defines.nil?
re = /#define\s+([^\s]+)\s+(\([^)]+\)|[^\s]+)\s*$/
@defines = {}
file_content.scan(re).each do |m|
next unless !m[0].include?('(') and m[1] != '\\'
@defines[m[0]] = m[1]
end
end
@defines
end
# Get the list of C structure names, as an Array.
def struct_names
re = /typedef\s+struct\s*\w*\s*((\w+)|\{([^{}]*(\{[^}]+\})?)*\}\s*([^\s]+))\s*(__attribute__\(.+\))?\s*;/ # Ouch...
@struct_names ||= @cpp_result.scan(re).map { |m|
a = m.compact
a.pop if /^__attribute__/.match(a.last)
a.last
}.flatten
end
# Get the list of CoreFoundation types, as an Array.
def cftype_names
re = /typedef\s+(const\s+)?struct\s*\w+\s*\*\s*([^\s]+Ref)\s*;/
@cftype_names ||= @cpp_result.scan(re).map { |m| m.compact[-1] }.flatten
end
# Get the list of function pointer types, as an Hash object (keys are the
# type names and values are their C declaration.
def function_pointer_types
unless @func_ptr_types
@func_ptr_types = {}
re = /typedef\s+([\w\s]+)\s*\(\s*\*\s*(\w+)\s*\)\s*\(([^)]*)\)\s*;/
data = @cpp_result.scan(re)
re = /typedef\s+([\w\s]+)\s*\(([^)]+)\)\s*;/
data |= @cpp_result.scan(re).map do |m|
ary = m[0].split(/(\w+)$/)
ary[1] << ' *'
ary << m[1]
ary
end
data.each do |m|
name = m[1]
args = m[2].split(',').map do |x|
x.strip!
if x.include?(' ')
ptr = x.sub!(/\[\]\s*$/, '')
x = x.sub(/\w+\s*$/, '').strip
ptr ? x + '*' : x
else
x
end
end
type = "#{m[0]}(*)(#{args.join(', ')})"
@func_ptr_types[name] = type
end
end
@func_ptr_types
end
def typedefs
if @typedefs.nil?
re = /^\s*typedef\s+(.+)\s+(\w+)\s*;$/
@typedefs = {}
data = (@complete_cpp_result or @cpp_result)
data.scan(re).each { |m| @typedefs[m[1]] = m[0] }
end
@typedefs
end
def externs
re = /^\s*#{@externname}\s+\b(.*)\s*;.*$/
@externs ||= @cpp_result.scan(re).map { |m| m[0].strip }
end
def constants
@constants ||= externs.map { |i| constant?(i, true) }.flatten.compact
end
def functions(inline=false)
if inline
return @inline_functions if @inline_functions
inline_func_re = /(inline|__inline__)\s+((__attribute__\(\([^)]*\)\)\s+)?([\w\s\*<>]+)\s*\(([^)]*)\)\s*)\{/
res = @cpp_result.scan(inline_func_re)
res.each { |x| x.delete_at(0); x.delete_at(1) }
else
return @functions if @functions
skip_inline_re = /(static)?\s(inline|__inline__)[^{;]+(;|\{([^{}]*(\{[^}]+\})?)*\})\s*/
skip_attributes_re = /__attribute__\((\([^()]*(\([^()]*\)|\))+)+\)/
func_re = /(^([\w\s\*<>]+)\s*\(([^)]*)\)\s*);/
res = @cpp_result.gsub(skip_inline_re, '').gsub(skip_attributes_re, '').scan(func_re)
end
funcs = res.map do |m|
orig, base, args = m
base.sub!(/^.*extern\s+/, '')
func = constant?(base)
if func
args = args.strip.split(',').map { |i| constant?(i) }
next if args.any? { |x| x.nil? }
args = [] if args.size == 1 and args[0].rettype == 'void'
FuncInfo.new(func, args, orig, inline)
end
end.compact
if inline
@inline_functions = funcs
else
@functions = funcs
end
funcs
end
def informal_protocols
self.ocmethods # to generate @inf_protocols
@inf_protocols
end
def ocmethods
if @ocmethods.nil?
@inf_protocols ||= {}
interface_re = /^@(interface|protocol)\s+(\w+)\s*([(<][^)>]+[)>])?/
end_re = /^@end/
body_re = /^\s*[-+]\s*(\([^)]+\))?\s*([^:\s;]+)/
args_re = /\w+\s*:/
prop_re = /^@property\s*(\([^)]+\))?\s*([^;]+);$/
current_interface = current_category = nil
@ocmethods = {}
i = 0
@cpp_result.each_line do |line|
size = line.size
line.strip!
if md = interface_re.match(line)
current_interface = md[1] == 'protocol' ? 'NSObject' : md[2]
current_category = md[3].delete('()<>').strip if md[3]
elsif end_re.match(line)
current_interface = current_category = nil
elsif current_interface and md = prop_re.match(line)
# Parsing Objective-C 2.0 properties.
if (a = md[2].split(/\s/)).length >= 2 \
and /^\w+$/.match(name = a[-1]) \
and (type = a[0..-2].join(' ')).index(',').nil?
getter, setter = name, "set#{name[0].chr.upcase + name[1..-1]}"
readonly = false
if attributes = md[1]
if md = /getter\s*=\s*(\w+)/.match(attributes)
getter = md[1]
end
if md = /setter\s*=\s*(\w+)/.match(attributes)
setter = md[1]
end
readonly = true if attributes.index('readonly')
end
typeinfo = VarInfo.new(type, '', '')
methods = (@ocmethods[current_interface] ||= [])
methods << MethodInfo.new(typeinfo, getter, false, [], line)
unless readonly
methods << MethodInfo.new(VarInfo.new('void', '', ''), setter + ':', false, [typeinfo], line)
end
end
elsif current_interface and (line[0] == ?+ or line[0] == ?-)
mtype = line[0]
data = @cpp_result[i..-1]
body_md = body_re.match(data)
next if body_md.nil?
rettype = body_md[1] ? body_md[1].delete('()') : 'id'
retval = VarInfo.new(rettype, '', '')
args = []
selector = ''
data = data[0..data.index(';')]
args_data = []
data.scan(args_re) { |x| args_data << [$`, x.delete(' '), $'] }
variadic = false
args_data.each_with_index do |ary, n|
before, argname, argtype = ary
arg_nameless = (n > 0 and /\)\s*$/.match(before))
argname = ':' if arg_nameless
realargname = nil
if n < args_data.length - 1
argtype.sub!(args_data[n + 1][2], '')
if arg_nameless
argtype.sub!(/(\w+\s*)?\w+\s*:\s*$/, '')
else
unless argtype.sub!(/(\w+)\s+\w+\s*:\s*$/) { |s| realargname = $1; '' }
# maybe the next argument is nameless
argtype.sub!(/\w+\s*:\s*$/, '')
end
end
else
argtype.sub!(/\s+__attribute__\(\(.+\)\)/, '')
if arg_nameless
argtype.sub!(/\w+\s*;$/, '')
else
unless argtype.sub!(/(\w+)\s*;$/) { |s| realargname = $1; '' }
variadic = argtype.sub!(/,\s*\.\.\.\s*;/, '') != nil
argtype.sub!(/\w+\s*$/, '') if variadic
end
end
end
selector << argname
realargname ||= argname.sub(/:/, '')
argtype = 'id' if argtype.strip.empty?
args << VarInfo.new(argtype, realargname, '') unless argtype.empty?
end
selector = body_md[2] if selector.empty?
args << VarInfo.new('...', 'vararg', '') if variadic
method = MethodInfo.new(retval, selector, line[0] == ?+, args, data)
if current_category and current_interface == 'NSObject'
(@inf_protocols[current_category] ||= []) << method
end
(@ocmethods[current_interface] ||= []) << method
end
i += size
end
end
return @ocmethods
end
#######
private
#######
def constant?(str, multi=false)
str.strip!
return nil if str.empty?
if str == '...'
VarInfo.new('...', '...', str)
else
str << " dummy" if str[-1].chr == '*' or str.index(/\s/).nil?
tokens = multi ? str.split(',') : [str]
part = tokens.first
part.sub!(/\s*__attribute__\(.+\)\s*$/, '')
re = /^([^()]*)\b(\w+)\b\s*(\[[^\]]*\])*$/
m = re.match(part)
if m
return nil if m[1].split(/\s+/).any? { |x| ['end', 'typedef'].include?(x) }
m = m.to_a[1..-1].compact.map { |i| i.strip }
m[0] += m[2] if m.size == 3
m[0] = 'void' if m[1] == 'void'
m[0] = m.join(' ') if m[0] == 'const'
var = begin
VarInfo.new(m[0], m[1], part)
rescue
return nil
end
if tokens.size > 1
[var, *tokens[1..-1].map { |x| constant?(m[0] + x.strip.sub(/^\*+/, '')) }]
else
var
end
end
end
end
def self.do_cpp(path, fails_on_error=true, do_64=false, flags='')
f_on = false
err_file = '/tmp/.cpp.err'
cpp_line = "#{CPP} #{CPPFLAGS} #{flags} #{do_64 ? '-D__LP64__' : ''} \"#{path}\" 2>#{err_file}"
complete_result = `#{cpp_line}`
if $?.to_i != 0 and fails_on_error
$stderr.puts File.read(err_file)
File.unlink(err_file)
raise "#{CPP} returned #{$?.to_int/256} exit status\nline was: #{cpp_line}"
end
result = complete_result.select { |s|
# First pass to only grab non-empty lines and the pre-processed lines
# only from the target header (and not the entire pre-processing result).
next if s.strip.empty?
m = %r{^#\s*\d+\s+"([^"]+)"}.match(s)
f_on = (File.basename(m[1]) == File.basename(path)) if m
f_on
}.select { |s|
# Second pass to ignore all pro-processor comments that were left.
/^#/.match(s) == nil
}.join
File.unlink(err_file)
return [complete_result, result]
end
class VarInfo
attr_reader :rettype, :stripped_rettype, :name, :orig
attr_accessor :octype
def initialize(type, name, orig)
@rettype = type
@name = name
@orig = orig
@rettype.gsub!( /\[[^\]]*\]/, '*' )
t = type.gsub(/\b(__)?const\b/,'')
t.gsub!(/<[^>]*>/, '')
t.gsub!(/\b(in|out|inout|oneway|const)\b/, '')
t.gsub!(/\b__private_extern__\b/, '')
re = /^\s*\(\s*/
if re.match(t)
parenAtBeginning = 1
end
t.gsub!(/^\s*\(?\s*/, '')
if parenAtBeginning
t.gsub!(/\s*\)?\s*$/, '')
else
t.gsub!(/\s*$/, '')
end
t.gsub!(/\n/, ' ')
raise "empty type (was '#{type}')" if t.empty?
@stripped_rettype = t
end
def function_pointer?(func_ptr_types)
type = (func_ptr_types[@stripped_rettype] or @stripped_rettype)
@function_pointer ||= FuncPointerInfo.new_from_type(type)
end
def <=>(x)
self.name <=> x.name
end
def hash
@name.hash
end
def eql?(o)
@name == o.name
end
end
class FuncInfo < VarInfo
attr_reader :args, :argc
def initialize(func, args, orig, inline=false)
super(func.rettype, func.name, orig)
@args = args
@argc = @args.size
if @args[-1] && @args[-1].rettype == '...'
@argc -= 1
@variadic = true
@args.pop
end
@inline = inline
self
end
def variadic?
@variadic
end
def inline?
@inline
end
end
class FuncPointerInfo < FuncInfo
def self.new_from_type(type)
@cache ||= {}
info = @cache[type]
return info if info
tokens = type.split(/\(\*\)/)
return nil if tokens.size != 2
rettype = tokens.first.strip
rest = tokens.last.sub(/^\s*\(\s*/, '').sub(/\s*\)\s*$/, '')
argtypes = rest.split(/,/).map { |x| x.strip }
@cache[type] = self.new(rettype, argtypes, type)
end
def initialize(rettype, argtypes, orig)
args = argtypes.map { |x| VarInfo.new(x, '', '') }
super(VarInfo.new(rettype, '', ''), args, orig)
end
end
class MethodInfo < FuncInfo
attr_reader :selector
def initialize(method, selector, is_class, args, orig)
super(method, args, orig)
@selector, @is_class = selector, is_class
self
end
def class_method?
@is_class
end
def <=>(o)
@selector <=> o.selector
end
def hash
@selector.hash
end
def eql?(o)
@selector == o.selector
end
end
end
# class to print xml with attributes in a fixed order, so that diff-ing
# .bridgesupport files is more meaningful. From:
# http://stackoverflow.com/questions/574724/rexml-preserve-attributes-order
class OrderedAttributes < REXML::Formatters::Pretty
def write_element(elm, out)
att = elm.attributes
class <<att
alias _each_attribute each_attribute
def each_attribute(&b)
to_enum(:_each_attribute).sort_by {|x| x.name}.each(&b)
end
end
super(elm, out)
end
end
PRODUCTVERSION = `sw_vers -productVersion`.strip.to_f
TIGER_OR_BELOW = PRODUCTVERSION <= 10.4
SNOWLEOPARD_OR_BELOW = PRODUCTVERSION <= 10.6
IS_PPC = `arch`.strip == 'ppc'
OBJC_GC_COMPACTION = SNOWLEOPARD_OR_BELOW ? '': '-Wl,-objc_gc_compaction'
class BridgeSupportGenerator
VERSION = '1.0'
ARCH = 'i386'
ARCH64 = 'x86_64'
FORMATS = ['final', 'exceptions-template', 'dylib', 'complete']
FORMAT_FINAL, FORMAT_TEMPLATE, FORMAT_DYLIB, FORMAT_COMPLETE = FORMATS
attr_accessor :headers, :generate_format, :private, :frameworks,
:exception_paths, :compiler_flags, :enable_32, :enable_64, :out_file,
:emulate_ppc, :install_name
attr_reader :resolved_structs, :resolved_cftypes, :resolved_enums,
:types_encoding, :defines, :resolved_inf_protocols_encoding
OAH_TRANSLATE = '/usr/libexec/oah/translate'
def initialize
@parser = nil
@headers = []
@imports = []
@incdirs = []
@exception_paths = []
@out_file = nil
@install_name = nil
@generate_format = FORMAT_FINAL
@private = false
@compiler_flags = nil
@frameworks = []
@enable_32 = false
@enable_64 = false
@emulate_ppc = false # PPC support is disabled since SnowLeopard
end
# def duplicate
# g = BridgeSupportGenerator.new
# g.headers = @headers
# g.exception_paths = @exception_paths
# g.out_file = @out_file
# g.generate_format = @generate_format
# g.private = @private
# g.compiler_flags = @compiler_flags
# g.frameworks = @frameworks
# g.enable_64 = @enable_64
# g.emulate_ppc = @emulate_ppc
# return g
# end
def add_header(path)
h = (Pathname.new(path).absolute? || File.exists?(path)) ? File.basename(path) : path
@headers << path
@imports << h
@import_directive ||= ''
@import_directive << "\n#include <#{h}>"
end
# Encodes the 4 include path pieces into a single string.
# "group" should be 'A', 'Q' or 'S' for Angled, Quoted or System.
# "isUserSupplied" and "isFramework" are booleans
def encode_includes(path, group, isUserSupplied, isFramework)
group + (isUserSupplied ? 'T' : 'F') + (isFramework ? 'T' : 'F') + path
end
def _parse(args, arch, ignore_merge_errors = false)
bool_sel_types = []
@all_sel_types.each_index { |i| bool_sel_types[i] = @all_sel_types[i].gsub(/\b(?:BOOL|Boolean)\b/, 'bool') }
bool_types = []
@method_exception_types.each_index { |i| bool_types[i] = @method_exception_types[i].gsub(/\b(?:BOOL|Boolean)\b/, 'bool') }
parser = Bridgesupportparser::Parser.new(args.imports, @headers, bool_sel_types, bool_types, args.defines, args.incdirs, args.defaultincs, args.sysroot)
case @generate_format
when FORMAT_DYLIB
parser.only_parse_class(Bridgesupportparser::AFunction)
end
target_triple = "#{arch}-apple-darwin#{args.darwinvers}"
if m = compiler_flags.match(/-m(.+)-version-min=([\d\.]+)/)
platform = m[1]
version = m[2]
case platform
when 'ios', 'ios-simulator', 'iphoneos'
target_triple = "#{arch}-apple-ios#{version}"
when 'macosx'
target_triple = "#{arch}-apple-macosx#{version}"
when 'tvos', 'tvos-simulator'
target_triple = "#{arch}-apple-tvos#{version}"
when 'watchos', 'watchos-simulator'
target_triple = "#{arch}-apple-watchos#{version}"
end
end
$stderr.puts "### _parse(\"#{target_triple}\")" if $DEBUG
parser.parse(target_triple)
@sel_types = {}
@all_sel_types.each_index do |i|
t = parser.special_method_encodings[i]
raise "No sel_of_type corresponding to #{@all_sel_types[i]}" if t.nil?
@sel_types[@all_sel_types[i]] = t
end
@types = {}
@method_exception_types.each_index do |i|
t = parser.special_type_encodings[i]
raise "No type corresponding to #{@method_exception_types[i]}" if t.nil?
@types[@method_exception_types[i]] = t
end
# structs
@structs.each do |name, ary|
s = parser.all_structs[name]
raise "No struct corresponding to #{name}" if s.nil?
s[:opaque] = true if s && ary[0]
end
# Note that struct names (k below) may either be "struct xxx" or just
# "xxx" if due to a typedef. Thus, we need to use the actual name
# (v.name below) if we want to test for a leading underscore.
parser.all_structs.delete_if { |k, v| v.name[0] == ?_ }
# cftypes
@cftypes.each do |name, ary|
c = parser.all_cftypes[name]
if c.nil?
$stderr.puts "No cftype \"#{name}\" to apply exceptions"
else
c[:gettypeid_func] = ary[0] unless ary[0].nil?
c[:_ignore_tollfree] = true if ary[1] == 'true'
end
end
add_tollfree(parser)
# If a cftype doesn't have either tollfree or a gettypeid function,
# it probably an opaque; convert it.
cfdel = []
parser.all_cftypes.each do |name, cf|
if cf.tollfree.nil? and cf.gettypeid_func.nil?
cfdel << name
type = cf.type || "^{#{name}=}"
parser.all_opaques[name] = Bridgesupportparser::OpaqueInfo.new(parser, name, type)
end
end
cfdel.each { |c| parser.all_cftypes.delete(c) }
# opaques
@opaques_to_ignore.each { |o| parser.all_opaques.delete(o) }
@opaques.each do |name, type|
next if type.nil?
parser.all_structs.delete(name)
parser.all_opaques[name] = Bridgesupportparser::OpaqueInfo.new(parser, name, type)
end
#enums
parser.all_enums.delete_if { |k, v| k[0] == ?_ }
# vars
parser.all_vars.delete_if { |k, v| k[0] == ?_ }
# macrostrings
parser.all_macrostrings.delete_if do |k, v|
next true if k[0] == ?_
@ignored_defines_regexps.any? { |re| re.match(k) }
end
# macronumbers (eventually merged with enums)
parser.all_macronumbers.delete_if do |k, v|
next true if k[0] == ?_
@ignored_defines_regexps.any? { |re| re.match(k) }
end
# evaluate mumeric macros that call functions
add_numberfunccall(parser)
# enums
parser.all_enums.delete_if { |k, v| k[0] == ?_ }
# funcs and func_aliases
keepfunc = {}
parser.all_func_aliases.each_value { |v| keepfunc[v.original] = true }
parser.all_funcs.delete_if { |k, v| !keepfunc[k] && k[0] == ?_ }
# Merge with exceptions.
@exceptions.each { |x| merge_with_exceptions(parser, x, ignore_merge_errors) }
parser
end
protected :_parse
def makedarwinvers(vers)
pieces = vers.split('.')
raise "Version \"#{vers}\" not 10.x[.y]" if pieces.length < 2 || pieces.length > 3 || pieces[0] != '10' || pieces[1] !~ /^\d+$/ || (pieces.length == 3 && pieces[2] !~ /^\d+$/)
pieces << '0' if pieces.length == 2
return sprintf('%d.%s', pieces[1].to_i + 4, pieces[2])
end
protected :makedarwinvers
# parse cc flags, and return defines, include directories, include files
# and the sysroot. For clang, system directories get sysroot applied,'
# but for gcc, -isystem directories don't get sysroot applied. So we
# collect -isystem directories separately, and combined them with the
# regular incdirs directories (so they are in the Angled group, but follow
# all -I and -F directories.
def parse_cc_args(args)
darwinvers = nil
defines = []
incdirs = []
incsys = []
includes = []
sysroot = ENV['SDKROOT'] || '/'
words = Shellwords.shellwords(args)
until words.empty?
o = words.shift
case o
when o.sub!(/^-D/, '') then defines << (o.empty? ? words.shift : o)
when o.sub!(/^-I/, '') then incdirs << encode_includes(o.empty? ? words.shift : o, 'A', false, true)
when o.sub!(/^-F/, '') then incdirs << encode_includes(o.empty? ? words.shift : o, 'A', true, true)
when o.sub!(/^--sysroot=/, '') then sysroot = o
when '-isystem' then incsys << encode_includes(words.shift, 'A', true, false)
when '-iquote' then incdirs << encode_includes(words.shift, 'Q', true, false)
when '-isysroot' then sysroot = words.shift
when '-include' then includes << words.shift
when o.sub!(/^-mmacosx-version-min=/, '') then darwinvers = makedarwinvers(o)
end
end
return darwinvers, defines, incdirs + incsys, includes, sysroot
end
protected :parse_cc_args
def parse(enable_32, enable_64, compiler_flags_64 = nil)
_darwinvers = makedarwinvers(ENV.has_key?('MACOSX_DEPLOYMENT_TARGET') ? ENV['MACOSX_DEPLOYMENT_TARGET'] : `sw_vers -productVersion`)
darwinvers = nil
defines = []
incdirs = []
includes = []
sysroot = ENV['SDKROOT'] || '/'
unless compiler_flags.nil?
darwinvers, defines, incdirs, includes, sysroot = parse_cc_args(compiler_flags)
end
getcc(sysroot) #initialize cached value
defaultincs = []
IO.popen("#{getcc()} -print-search-dirs") do |io|
io.each do |line|
if m = line.chomp.match(/^libraries: =(.*)/)
m[1].split(':').each do |path|
i = File.join(path, 'include')
defaultincs << i if File.directory?(i)
end
end
end
end
prepare(sysroot == '/' ? '' : sysroot, enable_32, enable_64)
@incdirs << encode_includes("#{$slb}/include", 'A', false, true)
@incdirs << encode_includes('/System/Library/Frameworks/CoreServices.framework/Frameworks', 'S', false, true)
@imports.unshift('AvailabilityMacros.h')
@imports.unshift('_BS_bool.h')
args = OpenStruct.new
args.darwinvers = darwinvers.nil? ? _darwinvers : darwinvers
args.imports = includes + @imports
args.defines = defines + %w{__APPLE_CPP__=1} + %w{__BLOCKS__=1}
args.incdirs = incdirs + @incdirs
args.defaultincs = defaultincs
args.sysroot = sysroot
@parser = _parse(args, ARCH) if @enable_32
if @enable_64
unless compiler_flags_64.nil? || compiler_flags == compiler_flags_64
darwinvers, defines, incdirs, includes, sysroot = parse_cc_args(compiler_flags_64)
args.darwinvers = darwinvers.nil? ? _darwinvers : darwinvers
args.imports = includes + @imports
args.defines = defines + %w{__APPLE_CPP__=1} + %w{__BLOCKS__=1}
args.incdirs = incdirs + @incdirs
args.defaultincs = defaultincs
args.sysroot = sysroot
end
parser64 = _parse(args, ARCH64, true)
if @parser.nil?
parser64.rename64!
@parser = parser64
else
@parser.mergeWith64!(parser64)
end
end
end
def write
case @generate_format
when FORMAT_DYLIB
generate_dylib
when FORMAT_TEMPLATE
generate_template
else
generate_xml
end
end
def cleanup
end
def xml_document
@xml_document ||= generate_xml_document
end
def generate_format=(format)
if @generate_format != format
@generate_format = format
@xml_document = nil
end
end
def merge_64_metadata(g)
raise "given generator isn't 64-bit" unless g.enable_64
[:types_encoding, :resolved_structs, :resolved_enums,
:defines, :resolved_inf_protocols_encoding].each do |sym|
hash = send(sym)
g.send(sym).each do |name, val64|
if val = hash[name]
hash[name] = [val, val64]
else
hash[name] = [nil, val64]
end
end
end
g.resolved_cftypes.each do |name, ary64|
type64 = ary64.first
if ary = @resolved_cftypes[name]
ary << type64
else
ary = ary64.dup
ary[0] = nil
ary << type64
@resolved_cftypes[name] = ary
end
end
end
def has_inline_functions?
@parser.all_funcs.values.any? { |x| x.inline? }
end
def self.dependencies_of_framework(path)
@dependencies ||= {}
name = File.basename(path, '.framework')
path = File.join(path, name)
deps = @dependencies[path]
if deps.nil?
if File.exist?(path)
deps = `otool -L "#{path}"`.scan(/\t([^\s]+)/).map { |m|
dpath = m[0]
next if File.basename(dpath) == name
next if dpath.include?('PrivateFrameworks')
unless dpath.sub!(%r{\.framework/Versions/\w+/\w+$}, '') # OS X
next unless dpath.sub!(%r{\.framework/\w+$}, '') # iOS
end
dpath.sub!('//', '/')
dpath + '.framework'
}.compact
@dependencies[path] = deps
elsif File.exist?(path + ".tbd")
# FIXME
# ".tbd" files does not contains correct framework dependencies.
end
end
deps
end
def self.doc_for_dependency(fpath)
@dep_docs ||= {}
doc = @dep_docs[fpath]
if doc.nil?
fname = File.basename(fpath, '.framework')
paths = []
if bsroot = ENV['BSROOT']
paths << File.join(bsroot, "#{fname}.bridgesupport")
end
path = File.join(fpath, "Resources/BridgeSupport/#{fname}.bridgesupport")
alt_path = "/Library/BridgeSupport/#{fname}.bridgesupport"
if dstroot = ENV['DSTROOT']
path = File.join(dstroot, path)
alt_path = File.join(dstroot, alt_path)
end
paths << path
paths << alt_path
a = Dir.glob(File.join(fpath, '**', '*.bridgesupport'))
if a.length == 1
paths << a.first
end
bspath = paths.find { |p| File.exist?(p) }
return nil if bspath.nil?
doc = REXML::Document.new(File.read(bspath))
@dep_docs[fpath] = doc
end
doc
end
#######
private
#######
def proto_to_sel(proto)
sel = proto.strip
sel.sub!(/^[-+]\s*/, '')
sel.sub!(/\s*;$/, '')
sel.sub!(/^\([^)]+\)\s*/, '')
sel.gsub!(/\([^)]+\)\s*\w+/, '')
sel.gsub!(/\s+/, '')
sel
end
def prepare(prefix_sysroot, enable_32, enable_64)
# Clear previously-harvested stuff.
[ @resolved_structs,
@resolved_inf_protocols_encoding,
@resolved_enums,
@resolved_cftypes,
@collect_types_encoding ].compact.each { |h| h.clear }
return if @prepared
@cpp_flags = @compiler_flags ? @compiler_flags.scan(/-[ID][^\s]+/).join(' ') + ' ' : ''
framework_paths = []
@frameworks.each { |f| framework_paths << handle_framework(prefix_sysroot, f) }
# set @enable_32 and @enable_64 depending on what is requested (via
# enable_32 and enable_64), and what architectures are actually
# available in the frameworks, if any.
if framework_paths.empty?
@enable_32 = enable_32
@enable_64 = enable_64
else
no_32 = false
no_64 = false
framework_paths.each do |fp|
p = File.join(fp, File.basename(fp, '.framework'))
if File.exist?(p)
lipo = `lipo -info "#{p}"`
raise "Couldn't determine architectures in #{p}" unless $?.exited? and $?.exitstatus == 0
lipo.chomp!
lipo.sub!(/^.*: /, '')
have32 = have64 = false
lipo.split.each do |arch|
if /64$/ =~ arch
have64 = true
else
have32 = true
end
end
elsif File.exist?(p + ".tbd")
require 'yaml'
yml = YAML.load(File.read(p + ".tbd"))
yml['exports'].each do |items|
items['archs'].each do |arch|
have64 = true if arch.include?('x86_64')
have32 = true if arch.include?('i386')
end