forked from dkimitsa/robovm-bro-gen
-
Notifications
You must be signed in to change notification settings - Fork 5
/
bro-gen.rb
executable file
·5308 lines (4810 loc) · 243 KB
/
bro-gen.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/env ruby
# Copyright (C) 2014 RoboVM AB
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
#
require 'ffi/clang'
require 'yaml'
require 'fileutils'
require 'pathname'
require 'tmpdir'
class String
def camelize
dup.camelize!
end
def camelize!
replace(split('_').each(&:capitalize!).join(''))
end
def downcase_first_camelize
dup.downcase_first_camelize!
end
def downcase_first_camelize!
camelize!
downcase_first
self
end
def underscore
dup.underscore!
end
def underscore!
replace(scan(/[A-Z][a-z]*/).join('_').downcase)
end
def upcase_first
self[0] = self[0].upcase
self
end
def downcase_first
self[0] = self[0].downcase
self
end
end
module Bro
def self.location_to_id(location)
"#{location.file}:#{location.offset}"
end
def self.location_to_s(location)
"#{location.file}:#{location.line}:#{location.column}"
end
def self.read_source_range(sr)
file = sr.start.file
if file
start = sr.start.offset
n = sr.end.offset - start
bytes = nil
open file, 'r' do |f|
f.seek start
bytes = f.read n
end
bytes.to_s
else
'?'
end
end
def self.read_attribute(cursor)
Bro.read_source_range(cursor.extent)
end
class Entity
@@deprecated_version = 6
attr_accessor :id, :location, :name, :framework, :attributes, :cursor
def initialize(model, cursor)
@cursor = cursor
@location = cursor ? cursor.location : nil
@id = cursor ? Bro.location_to_id(@location) : nil
@name = cursor ? cursor.spelling : nil
@model = model
@framework = @location ?
@location.file.to_s.split(File::SEPARATOR).reverse.find_all { |e| e.match(/^.*\.(framework|lib)$/) }.map { |e| e.sub(/(.*)\.(framework|lib)/, '\1') }.first :
nil
@attributes = []
end
def types
[]
end
def java_name
name ? ((@model.get_class_conf(name) || {})['name'] || name) : ''
end
def pointer
Pointer.new self
end
def is_available?
# check if directly unavailable
attrib = @attributes.find { |e| e.is_a?(UnavailableAttribute) }
return false if attrib
# check if available
attrib = @attributes.find { |e| e.is_a?(AvailableAttribute) && e.version != nil && (e.platform == nil || e.platform == $target_platform) }
if attrib
# TODO: there is a mess in platforms (macos, ios, tvos, watchos) so checking only ios now
$ios_version && attrib.version != -1 && attrib.version <= $ios_version.to_f || false
else
# nothing specified so available
true
end
end
def is_outdated?
if deprecated
d_version = deprecated
(d_version > 0 && d_version <= @@deprecated_version) || (d_version < 0 && @model.exclude_deprecated?)
else
false
end
end
def since
attrib = @attributes.find { |e| e.is_a?(AvailableAttribute) && e.version != nil && (e.platform == nil || e.platform == $target_platform) }
attrib.version if attrib
end
def deprecated
attrib = @attributes.find { |e| e.is_a?(AvailableAttribute) && e.dep_version != nil && (e.platform == nil || e.platform == $target_platform) }
attrib.dep_version if attrib
end
def reason
attrib = @attributes.find { |e| e.is_a?(AvailableAttribute) && e.dep_message != nil && (e.platform == nil || e.platform == $target_platform) }
attrib.dep_message if attrib
end
def valueAttributeForKey(key)
attrib = @attributes.find { |e| e.is_a?(KeyValueAttribute) && e.key == key }
attrib.value if attrib
end
end
class Pointer < Entity
attr_accessor :pointee
def initialize(pointee)
super(nil, nil)
@pointee = pointee
end
def types
@pointee.types
end
def java_name
if @pointee.is_a?(Builtin)
if %w(byte short char int long float double boolean void).include?(@pointee.name)
"#{@pointee.name.capitalize}Ptr"
elsif @pointee.name == 'MachineUInt'
'MachineSizedUIntPtr'
elsif @pointee.name == 'MachineSInt'
'MachineSizedSIntPtr'
elsif @pointee.name == 'MachineFloat'
'MachineSizedFloatPtr'
elsif @pointee.name == 'Pointer'
'VoidPtr.VoidPtrPtr'
else
"#{@pointee.java_name}.#{@pointee.java_name}Ptr"
end
elsif @pointee.is_a?(Struct) || @pointee.is_a?(Typedef) && @pointee.is_struct? || @pointee.is_a?(ObjCClass) || @pointee.is_a?(ObjCProtocol)
@pointee.java_name
else
"#{@pointee.java_name}.#{@pointee.java_name}Ptr"
end
end
end
class Array < Entity
attr_accessor :base_type, :dimensions
def initialize(base_type, dimensions)
super(nil, nil)
@base_type = base_type
@dimensions = dimensions
end
def types
@base_type.types
end
def java_name
if @base_type.is_a?(Builtin)
if %w(byte short char int long float double).include?(@base_type.name)
"#{@base_type.name.capitalize}Buffer"
elsif @base_type.name == 'MachineUInt'
'MachineSizedUIntPtr'
elsif @base_type.name == 'MachineSInt'
'MachineSizedSIntPtr'
elsif @base_type.name == 'MachineFloat'
'MachineSizedFloatPtr'
elsif @base_type.name == 'Pointer'
'VoidPtr.VoidPtrPtr'
else
"#{@base_type.java_name}.#{@base_type.java_name}Ptr"
end
elsif @base_type.is_a?(Struct) || @base_type.is_a?(Typedef) && @base_type.is_struct?
@base_type.java_name
else
"#{@base_type.java_name}.#{@base_type.java_name}Ptr"
end
end
end
class Block < Entity
attr_accessor :return_type, :param_types
def initialize(model, return_type, param_types)
super(model, nil)
@return_type = return_type
@param_types = param_types || []
end
def types
[@return_type.types] + @param_types.map(&:types)
end
@@simple_block_types = {'boolean' => 'Boolean', 'byte' => 'Byte',
'short' => 'Short', 'char' => 'Character', 'int' => 'Integer',
'long' => 'Long', 'float' => 'Float', 'double' => 'Double',
# and also annotated types
'@MachineSizedUInt long' => 'Long','@MachineSizedSInt long' => 'Long',
'@MachineSizedFloat double' => 'Double'}
@@simple_block_types_anotat = {'@MachineSizedUInt long' => '@MachineSizedUInt',
'@MachineSizedSInt long' => '@MachineSizedSInt', '@MachineSizedFloat double' => '@MachineSizedFloat'}
def java_name
res = java_name_ex()
return res[0] + ' ' + res[1]
end
# modified to return array tuple to be able create block type param inside block
def java_name_ex
if @return_type.is_a?(Builtin) && @return_type.name == 'void'
if @param_types.empty?
['@Block', 'Runnable']
elsif @param_types.size == 1 && @param_types[0].is_a?(Builtin) && @@simple_block_types[@param_types[0].name]
["@Block", "Void#{@param_types[0].name.capitalize}Block"]
elsif @param_types.size <= 6
by_val_params = to_by_val_params(@param_types).join(",")
by_val_mark = ''
by_val_mark = "(\"(#{by_val_params})\")" if !by_val_params.gsub(',', '').empty?
["@Block#{by_val_mark}", "VoidBlock#{@param_types.size}<" + @param_types.map { |e| to_java_name(e) }.join(", ") + ">"]
else
['', 'ObjCBlock']
end
else
if @param_types.size == 0 && @return_type.is_a?(Builtin) && @@simple_block_types[@return_type.name]
["@Block", "#{@return_type.name.capitalize}Block"]
elsif @param_types.size <= 6
# besides @ByVal it would be required to replace @MachineSized anotated
# types with proper types and add these annotations to by_val_params
by_val_params = to_by_val_params(@param_types).join(",")
by_val_mark = ''
by_val_mark = "(\"(#{by_val_params})\")" if !by_val_params.gsub(',', '').empty?
["@Block#{by_val_mark}", "Block#{@param_types.size}<" + @param_types.map { |e| to_java_name(e) }.push(to_java_name(return_type)).join(", ") + ">"]
else
['', 'ObjCBlock']
end
end
end
def to_by_val_params(p_types)
p_types.map {|e|
if @model.is_byval_type?(e)
'@ByVal'
elsif e.is_a?(Block)
'@Block'
elsif e.is_a?(Builtin)
@@simple_block_types_anotat[e.java_name] || ''
else
''
end
}
end
def to_java_name(type)
if type.respond_to?('each') # Generic type
"#{type[0].java_name}<" + type[1..-1].map{ |e| e.java_name}.join(", ") + ">"
elsif type.is_a?(Block)
type.java_name_ex()[1]
else
@@simple_block_types[type.java_name] || type.java_name
end
end
end
class ObjCId < Entity
attr_accessor :protocols
def initialize(model, protocols)
super(model, nil)
@protocols = protocols
end
def types
@protocols.map(&:types)
end
def java_name
# filter protocols that are only available
pp = @protocols.find_all do |prot|
c = @model.get_protocol_conf(prot.name)
next unless c && !c['skip_implements']
prot
end
pp.map(&:java_name).join(' & ')
end
end
class Builtin < Entity
attr_accessor :name, :type_kinds, :java_name, :storage_type
def initialize(name, type_kinds = [], java_name = nil, storage_type = nil)
super(nil, nil)
@name = name
@type_kinds = type_kinds
@java_name = java_name || name
@storage_type = storage_type || name
end
end
@@builtins = [
Builtin.new('boolean', [:type_bool]),
Builtin.new('byte', [:type_uchar], nil, 'unsigned char'),
Builtin.new('byte', [:type_schar, :type_char_s], nil, 'signed char'),
Builtin.new('short', [:type_short], nil, 'signed short'),
Builtin.new('short', [:type_ushort], nil, 'unsigned short'),
Builtin.new('char', [:type_wchar, :type_char16], nil, 'unsigned short'),
Builtin.new('int', [:type_int], nil, 'signed int'),
Builtin.new('int', [:type_uint, :type_char32], nil, 'unsigned int'),
Builtin.new('long', [:type_longlong], nil, 'signed long'),
Builtin.new('long', [:type_ulonglong], nil, 'unsigned long'),
Builtin.new('float', [:type_float]),
Builtin.new('double', [:type_double]),
Builtin.new('MachineUInt', [:type_ulong], '@MachineSizedUInt long'),
Builtin.new('MachineSInt', [:type_long], '@MachineSizedSInt long'),
Builtin.new('MachineFloat', [], '@MachineSizedFloat double'),
Builtin.new('void', [:type_void]),
Builtin.new('Pointer', [], '@Pointer long'),
Builtin.new('String', [], 'String'),
Builtin.new('__builtin_va_list', [], 'VaList'),
Builtin.new('ObjCBlock', [:type_block_pointer]),
Builtin.new('FunctionPtr', [], 'FunctionPtr'),
Builtin.new('Selector', [:type_obj_c_sel], 'Selector'),
Builtin.new('ObjCObject', [], 'ObjCObject'),
Builtin.new('ObjCClass', [], 'ObjCClass'),
Builtin.new('ObjCProtocol', [], 'ObjCProtocol'),
Builtin.new('BytePtr', [], 'BytePtr')
]
@@builtins_by_name = @@builtins.each_with_object({}) { |b, h| h[b.name] = b; h }
@@builtins_by_type_kind = @@builtins.each_with_object({}) { |b, h| b.type_kinds.each { |e| h[e] = b }; h }
def self.builtins_by_name(name)
@@builtins_by_name[name]
end
def self.builtins_by_type_kind(kind)
@@builtins_by_type_kind[kind]
end
class Attribute
attr_accessor :source
def initialize(source)
@source = source
end
end
class IgnoredAttribute < Attribute
def initialize(source)
super(source)
end
end
# attribute to attach important data
class KeyValueAttribute < Attribute
attr_accessor :key, :value
def initialize(source)
super(source)
source =~ /^(.*?)\("?(.*?)"?\)$/
@key = $1
@value = $2
end
end
class AvailableAttribute < Attribute
attr_accessor :platform, :version, :dep_version, :dep_message
def initialize(source)
super(source)
@dep_message = []
if source.start_with?('availability(')
source =~ /^availability\((.*)\)/
args = $1.split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/).collect{|x| x.strip || x}
@platform = args[0]
args[1..-1].each do |v|
if v == 'unavailable'
@version = -1
elsif v.start_with?('introduced=')
@version = str_to_float(v.sub('introduced=', '').sub('_', '.'))
elsif v.start_with?('deprecated=')
@dep_version = str_to_float(v.sub('deprecated=', '').sub('_', '.'))
elsif v.start_with?('message="') && v.end_with?('"')
m = v.sub('message=', '')[0..-1]
m = eval(m).strip
@dep_message.push m unless m.empty?
elsif v.start_with?('replacement="') && v.end_with?('"')
m = v.sub('replacement=', '')[0..-1]
m = eval(m).strip
@dep_message.push decorate_dep_replacement(m) unless m.empty? || m.downcase.start_with?("Use ")
end
end
else
# deprecated case
@dep_version = -1
source = source.sub('__deprecated__', 'deprecated') if source.start_with?('__deprecated__')
if source.start_with?('deprecated(')
# has message
source =~ /^deprecated\((.*)\)/m
msg = $1.gsub("\n", '')
args = msg.split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/m).collect{|x| eval(x).strip || x}
if args.length == 2
# special case: message + replacement
@dep_message.push args[0] unless args[0].empty?
@dep_message.push decorate_dep_replacement(args[1]) unless args[1].empty?
else
# common case
args.each { |m| @dep_message.push m unless m.empty? }
end
end
end
if @dep_message && !@dep_message.empty?
@dep_message = @dep_message.join(". ")
else
@dep_message = nil
end
end
def decorate_dep_replacement(s)
m = s.downcase
if m.start_with?("use ") || m.start_with?(" instead")
s
else
# using just single "Use" (without instead) to minimize amount of diffs
"Use #{s}"
end
end
def str_to_float(s)
begin
return -1 if s == "NA"
return Float(s).to_f
rescue
return nil
end
end
end
class UnavailableAttribute < Attribute
end
class UnsupportedAttribute < Attribute
def initialize(source)
super(source)
end
end
def self.parse_attribute(cursor)
source = Bro.read_source_range(cursor.extent)
if source.start_with?('availability(') || source.start_with?('deprecated(') || source == 'deprecated' || source.start_with?('__deprecated__(') || source == '__deprecated__'
return AvailableAttribute.new source
elsif source.start_with?('unavailable')
return UnavailableAttribute.new source
# elsif source.start_with?('__DARWIN_ALIAS_C') || source.start_with?('__DARWIN_ALIAS') ||
# source == 'CF_IMPLICIT_BRIDGING_ENABLED' || source.start_with?('DISPATCH_') || source.match(/^(CF|NS)_RETURNS_RETAINED/) ||
# source.match(/^(CF|NS)_INLINE$/) || source.match(/^(CF|NS)_FORMAT_FUNCTION.*/) || source.match(/^(CF|NS)_FORMAT_ARGUMENT.*/) ||
# source == 'NS_RETURNS_INNER_POINTER' || source == 'NS_AUTOMATED_REFCOUNT_WEAK_UNAVAILABLE' || source == 'NS_REQUIRES_NIL_TERMINATION' ||
# source == 'NS_ROOT_CLASS' || source == '__header_always_inline' || source.end_with?('_EXTERN') || source.end_with?('_EXTERN_CLASS') || source == 'NSObject' ||
# source.end_with?('_CLASS_EXPORT') || source.end_with?('_EXPORT') || source == 'NS_REPLACES_RECEIVER' || source == '__objc_exception__' || source == 'OBJC_EXPORT' ||
# source == 'OBJC_ROOT_CLASS' || source == '__ai' || source.end_with?('_EXTERN_WEAK') || source == 'NS_DESIGNATED_INITIALIZER' || source.start_with?('NS_EXTENSION_UNAVAILABLE_IOS') ||
# source == 'NS_REQUIRES_PROPERTY_DEFINITIONS' || source.start_with?('DEPRECATED_MSG_ATTRIBUTE') || source == 'NS_REFINED_FOR_SWIFT' || source.start_with?('NS_SWIFT_NAME') ||
# source.start_with?('NS_SWIFT_UNAVAILABLE') || source == 'UI_APPEARANCE_SELECTOR' || source == 'CF_RETURNS_NOT_RETAINED' || source == 'NS_REQUIRES_SUPER' || source == 'objc_designated_initializer' ||
# source == 'availability' || # clang extends property to methods and attaches this attr without proper specification, ignore it
# source.start_with?('enum_extensibility') || # appeared in ios11
# source.start_with?('ns_error_domain') || source == 'objc_returns_inner_pointer' || # appeared in ios11
# source.start_with?('swift_') || # appeared in ios11, ignore all swift4 attr
# source.start_with?('NS_OPTIONS') # TODO: there is a lot of such outputs once moved to ios11 due pre-processor workaround. currently just ignoring
# return IgnoredAttribute.new source # TODO: lot of these macro are not present anymore as were expanded by pre-clang preprocessor call
elsif source.start_with?('objc_runtime_name(')
return KeyValueAttribute.new source
else
# return UnsupportedAttribute.new source
# TODO: there is nothing special about all tese bunch of attributes listed in IgnoredAttribute
# and UnsupportedAttribute is just making lot of noise in log, just ignore them all
return IgnoredAttribute.new source
end
end
class Macro
attr_accessor :name, :source, :args, :body
def initialize(source)
source = source.split(/\s*\\*\s*\n/).join(" ")
@source = source
# name
@name = source[/^[A-Za-z_][A-Za-z_0-9]*/]
# remove name
s = source.gsub(/^[A-Za-z_][A-Za-z_0-9]*/, '').strip
# check if has params
if s.start_with?("(")
params = s[/^\(.*?\)/][1..-2]
args = params.scan(/(?:"(?:""|.)*?"(?!")|[^,]*?\(.*?\)|[^,]+)/)
@args = args.collect{|x| x.strip || x}
@body = s.sub(/^\(.*?\)\s*/, '')
else
@args = []
@body = s
end
# puts "@Macro: #{@name}: #{@source} #{@args} #{@body}"
# puts "@Macro: #{@name} && #{@body} ::: #{@source}"
end
def subst(params)
return body unless @args.length
params = [] unless params
if params.length != @args.length
return nil
end
res = @body
for idx in [email protected] - 1
res = res.sub(@args[idx], params[idx])
end
return res
end
end
class CallbackParameter
attr_accessor :name, :type
def initialize(cursor)
@name = cursor.spelling
@type = cursor.type
end
end
class Typedef < Entity
attr_accessor :typedef_type, :parameters, :struct, :enum
def initialize(model, cursor, struct_def_name = nil)
super(model, cursor)
@parameters = []
@struct = nil
@enum = nil
if struct_def_name
@name = struct_def_name
@typedef_type = :type_record
@is_structDef = true
return
end
@is_structDef = false
@typedef_type = cursor.typedef_type
enum_without_name = false
cursor.visit_children do |cursor, _parent|
case cursor.kind
when :cursor_integer_literal
when :cursor_obj_c_class_ref
when :cursor_obj_c_protocol_ref
when :cursor_binary_operator
when :cursor_paren_expr
when 427 #CXCursor_ObjCIndependentClass = 427
# ignored
when 441 # CXCursor_AlignedAttr = 441
# ignored as not able to support right now
# example typedef __attribute__((__ext_vector_type__(2),__aligned__(4))) float simd_packed_float2;
when :cursor_parm_decl
@parameters.push CallbackParameter.new cursor
when :cursor_struct, :cursor_union
@struct = Struct.new model, cursor, nil, cursor.kind == :cursor_union
when :cursor_type_ref
if cursor.type.kind == :type_record && @typedef_type.kind != :type_pointer
@struct = Struct.new model, cursor, nil, cursor.spelling.match(/\bunion\b/)
end
when :cursor_enum_decl
# try to find the enum as it should be created already
eid = Bro.location_to_id(cursor.location)
e = model.enums.find { |e| e.id == eid}
@enum = e || (Enum.new model, cursor)
if @enum.name == nil || @enum.name.empty?
# special case: there could be no name in enum typedef declaration
# in this case there is no name attached to enum which will make
# difficulties exporting it, just attach typedef name to enum
# name in this case
enum_without_name = true
end
when :cursor_unexposed_attr
attribute = Bro.parse_attribute(cursor)
if attribute.is_a?(UnsupportedAttribute) && model.is_included?(self)
$stderr.puts "WARN: Typedef #{@name} at #{Bro.location_to_s(@location)} has unsupported attribute '#{attribute.source}'"
end
@attributes.push attribute
else
raise "Unknown cursor kind #{cursor.kind} in typedef at #{Bro.location_to_s(@location)}"
end
next :continue
end
if enum_without_name
# enum without name, attach name to it as well as visibility attributes
@enum.name = @name
@enum.attributes += @attributes
end
end
def is_callback?
end
def is_struct?
@struct != nil || @is_structDef
end
def is_enum?
@enum != nil
end
end
class StructMember
attr_accessor :name, :type
def initialize(cursor: nil, name: nil, type: nil)
if cursor.nil?
@name = name
@type = type
else
@name = cursor.spelling
@type = cursor.type
end
end
end
class Struct < Entity
attr_accessor :members, :children, :parent, :union, :type, :packed_align
def initialize(model, cursor, parent = nil, union = false)
super(model, cursor)
@name = @name.gsub(/\s*\bconst\b\s*/, '')
@name = @name.sub(/^(struct|union)\s*/, '')
@type = cursor.type
@parent = parent
@union = union
# prepare to handle packer attribute
@packed_align = nil
has_packed_attr = false
align_attr_value = nil
# parse members and anonymous structs/unions and put everyting into early_members
# items will be sorted out after parsing
early_members = []
cursor.visit_children do |cursor, _parent|
case cursor.kind
when :cursor_unexposed_expr
# ignored
when 417
# ignored CXCursor_VisibilityAttr = 417,
when 436
# CXCursor_ObjCBoxable = 436
# ignored as no benefits of it
# typedef struct __attribute__((objc_boxable)) CGPoint CGPoint;
when 441
# CXCursor_AlignedAttr = 441
a = Bro.read_attribute(cursor)
if a.start_with?('aligned(') && a.end_with?(')')
align = a.sub('aligned(', '')[0..-2]
align = eval(align).to_i
align_attr_value = align
end
when :cursor_field_decl
m = StructMember.new(cursor: cursor)
early_members.push m
when :cursor_struct, :cursor_union
# add anonymous struct to be flatten, later it either be flatten or extracted as external
s = Struct.new model, cursor, self, cursor.kind == :cursor_union
if s.name.nil? || s.name.empty?
# inner anonymous struct, might be embedded, save for future processing
early_members.push s
else
# struct with tag, make global available
model.structs.push s
end
when :cursor_unexposed_attr, :cursor_packed_attr, :cursor_annotate_attr
a = Bro.read_attribute(cursor)
if model.is_included?(self)
if a == "packed" || a == "__packed__"
has_packed_attr = true
elsif a.start_with?('aligned(') && a.end_with?(')')
align = a.sub('aligned(', '')[0..-2]
align = eval(align).to_i
align_attr_value = align
elsif a != '?'
$stderr.puts "WARN: #{@union ? 'union' : 'struct'} #{@name} at #{Bro.location_to_s(@location)} has unsupported attribute #{a}"
end
end
else
raise "Unknown cursor kind #{cursor.kind} in struct at #{Bro.location_to_s(@location)}"
end
next :continue
end
# save packed attribute
@packed_align = (align_attr_value == nil ? 1 : align_attr_value) if has_packed_attr
# process early members and replace anonymous structs/uniions
@members = []
@children = []
# grandchildren - will contain children from child struct. just to keep own children on top of renaming list
grandchildren = []
idx = 1
early_members.each_with_index do |e, i|
if e.is_a?(Struct)
if i + 1 < early_members.length && early_members[i + 1].is_a?(StructMember) && Bro::location_to_id(early_members[i + 1].type.declaration.location) == e.id
# next item after this is stuct member that points to this anonymous struct/member
# just extract it to external struct (not subject for embedding)
@children.push e
model.structs.push e
# copy all children
grandchildren.concat(e.children)
elsif @union || e.union
# for union we can't expand structures into memebers
# as it is not supported at robovm end.
# logicaly we can't expand unions into structs.
# creating an entry for it, struct will be extracted
# into standalone entry
@members.push StructMember.new(name: "autoMember$#{idx}", type:e.type)
@children.push e
model.structs.push e
else
# anonymous struct
# copy all it members
@members.concat(e.members)
# copy all children
grandchildren.concat(e.children)
end
else
@members.push e
end
idx += 1
end
# now attaching name for extracted structures
@children.concat(grandchildren)
if [email protected]? && [email protected]?
idx = 1
@children.each do |e|
e.name = "#{@name}$InnerStruct$#{idx}"
idx += 1
end
end
end
def types
@members.map(&:type)
end
def is_opaque?
@members.empty?
end
end
class FunctionParameter
attr_accessor :name, :type
def initialize(cursor, def_name)
@name = !cursor.spelling.empty? ? cursor.spelling : def_name
@type = cursor.type
end
def name
# escape names that slashes with Java keyworks
case @name
when 'native'
'_native'
when 'public'
'_public'
when 'private'
'_private'
when 'static'
'_static'
else
@name
end
end
end
class Function < Entity
attr_accessor :return_type, :parameters, :type, :inline_statement
def initialize(model, cursor)
super(model, cursor)
@type = cursor.type
@return_type = cursor.result_type
@parameters = []
param_count = 0
@inline = cursor.extent.text.start_with?("static ") || cursor.extent.text.include?("static ")
@variadic = cursor.variadic?
cursor.visit_children do |cursor, _parent|
case cursor.kind
when :cursor_type_ref, :cursor_obj_c_class_ref, :cursor_obj_c_protocol_ref, :cursor_unexposed_expr, :cursor_ibaction_attr, 409, 410
# Ignored
when 434
# CXCursor_ObjCDesignatedInitializer = 434
# Ignored as not useful
# - (instancetype)init __attribute__((objc_designated_initializer))
when 417
# CXCursor_VisibilityAttr = 417,
# ignored as doesn't provide useful information
# extern __attribute__((visibility("default"))) const char * _Nonnull sel_getName(SEL _Nonnull sel)
when 420
# CXCursor_NSReturnsRetained = 420
# FIXME: use it to attach or add warning about no retain marshaller
# __attribute__((__ns_returns_retained__))
when 423
# CXCursor_NSConsumesSelf = 423,
# ignored as doesn't provide useful information
# - (nullable id)awakeAfterUsingCoder:(NSCoder *)coder __attribute__((ns_consumes_self)) __attribute__((ns_returns_retained));
when 429
# CXCursor_ObjCReturnsInnerPointer = 429
# ignored for now, as no common way to adopt it
# - (nullable const char *)cStringUsingEncoding:(NSStringEncoding)encoding __attribute__((objc_returns_inner_pointer));
when 430
# CXCursor_ObjCRequiresSuper = 430
# TODO: probably shell be added as JavaDoc that super call is requred (or annotation processor)
# - (void)updateConstraints __attribute__((availability(ios,introduced=6.0))) __attribute__((objc_requires_super));
when 440
# TODO: CXCursor_WarnUnusedResultAttr = 440
when :cursor_parm_decl
@parameters.push FunctionParameter.new cursor, "p#{param_count}"
param_count += 1
when :cursor_compound_stmt
@inline = true
@inline_statement = cursor.extent.text
when :cursor_asm_label_attr, :cursor_unexposed_attr, :cursor_annotate_attr
attribute = Bro.parse_attribute(cursor)
if attribute.is_a?(UnsupportedAttribute) && model.is_included?(self)
$stderr.puts "WARN: Function #{@name} at #{Bro.location_to_s(@location)} has unsupported attribute '#{attribute.source}'"
end
@attributes.push attribute
else
raise "Unknown cursor kind #{cursor.kind} in function #{@name} at #{Bro.location_to_s(@location)}"
end
next :continue
end
end
def types
[@return_type] + @parameters.map(&:type)
end
def is_variadic?
@variadic
end
def is_inline?
@inline
end
end
class ObjCVar < Entity
attr_accessor :type
def initialize(model, cursor)
super(model, cursor)
@type = cursor.type
end
def types
[@type]
end
end
class ObjCInstanceVar < ObjCVar
end
class ObjCClassVar < ObjCVar
end
class ObjCMethod < Function
attr_accessor :owner
def initialize(model, cursor, owner)
super(model, cursor)
@owner = owner
end
end
class ObjCInstanceMethod < ObjCMethod
def initialize(model, cursor, owner)
super(model, cursor, owner)
end
end
class ObjCClassMethod < ObjCMethod
def initialize(model, cursor, owner)
super(model, cursor, owner)
s = Bro.read_source_range(cursor.extent)
@class_property = !s.include?('+') # class properties are also recognized as class methods
end
def is_class_property?
@class_property
end
end
class ObjCProperty < Entity
attr_accessor :type, :owner, :getter, :setter, :attrs
def initialize(model, cursor, owner)
super(model, cursor)
@type = cursor.type
@owner = owner
@getter = nil
@setter = nil
@source = Bro.read_source_range(cursor.extent)
/@property\s*(\((?:[^)]+)\))/ =~ @source
@attrs = !$1.nil? ? $1.strip.slice(1..-2).split(/,\s*/) : []
@attrs = @attrs.each_with_object({}) do |o, h|
pair = o.split(/\s*=\s*/)
h[pair[0]] = pair.size > 1 ? pair[1] : true
h
end
cursor.visit_children do |cursor, _parent|
case cursor.kind
when :cursor_type_ref, :cursor_parm_decl, :cursor_obj_c_class_ref, :cursor_obj_c_protocol_ref, :cursor_obj_c_instance_method_decl, :cursor_iboutlet_attr, :cursor_annotate_attr, :cursor_unexposed_expr
# Ignored
when 417
# ignored CXCursor_VisibilityAttr = 417,
when 429
# ignored CXCursor_ObjCReturnsInnerPointer = 429
# @property (readonly) const char *objCType __attribute__((objc_returns_inner_pointer));
when 426
# ignored CXCursor_ObjCNSObject = 426
# @property (nonatomic, readonly, retain, nullable) __attribute__((NSObject)) CGColorRef backgroundColor;
when :cursor_unexposed_attr
attribute = Bro.parse_attribute(cursor)
if attribute.is_a?(UnsupportedAttribute) && model.is_included?(self)
$stderr.puts "WARN: ObjC property #{@name} at #{Bro.location_to_s(@location)} has unsupported attribute '#{attribute.source}'"
end
@attributes.push attribute
else
raise "Unknown cursor kind #{cursor.kind} in ObjC property #{@name} at #{Bro.location_to_s(@location)}"
end
next :continue
end
end
def getter_name
@attrs['getter'] || @name
end
def setter_name
base = @name[0, 1].upcase + @name[1..-1]
@attrs['setter'] || "set#{base}:"
end
def is_static?
@attrs['class']
end
def is_readonly?
@setter.nil? && @attrs['readonly']
end
def types
[@type]
end
end
class ObjCMemberHost < Entity
attr_accessor :instance_methods, :class_methods, :properties
def initialize(model, cursor)
super(model, cursor)
@instance_methods = []
@class_methods = []
@properties = []
end
def resolve_property_accessors
# Properties are also represented as instance methods in the AST. Remove any instance method
# defined on the same position as a property and use the method name as getter/setter.
@instance_methods -= @instance_methods.find_all do |m|
p = @properties.find { |f| f.id == m.id || f.getter_name == m.name || f.setter_name == m.name }