-
Notifications
You must be signed in to change notification settings - Fork 28
/
bro-gen.rb
executable file
·3186 lines (2925 loc) · 121 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>.
#
$LOAD_PATH.unshift File.dirname(__FILE__) + "/ffi-clang/lib"
require "ffi/clang"
require 'yaml'
require 'fileutils'
require 'pathname'
class String
def camelize
self.dup.camelize!
end
def camelize!
self.replace(self.split("_").each {|s| s.capitalize! }.join(""))
end
def underscore
self.dup.underscore!
end
def underscore!
self.replace(self.scan(/[A-Z][a-z]*/).join("_").downcase)
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 = 5
attr_accessor :id, :location, :name, :framework, :attributes
def initialize(model, 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}".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?(mac_version, ios_version)
attrib = @attributes.find {|e| e.is_a?(AvailableAttribute)}
if attrib
mac_version && attrib.mac_version && attrib.mac_version.to_f <= mac_version.to_f ||
ios_version && attrib.ios_version && attrib.ios_version.to_f <= ios_version.to_f || false
else
true
end
end
def is_outdated?
if deprecated
d_version = deprecated[0..2].to_f
d_version <= @@deprecated_version
else
false
end
end
def since
attrib = @attributes.find {|e| e.is_a?(AvailableAttribute)}
if attrib
attrib.ios_version
else
nil
end
end
def deprecated
attrib = @attributes.find {|e| e.is_a?(AvailableAttribute)}
if attrib
attrib.ios_dep_version
else
nil
end
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 ['byte', 'byte', 'short', 'char', 'int', 'long', 'float', 'double', '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.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 ['byte', 'byte', 'short', 'char', 'int', 'long', 'float', 'double', 'void'].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.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(return_type, param_types)
super(nil, nil)
@return_type = return_type
@param_types = param_types
end
def types
[@return_type.types] + @param_types.map {|e| e.types}
end
def java_name
if @return_type.is_a?(Builtin) && @return_type.name == 'void' && @param_types.empty?
"@Block Runnable"
elsif @return_type.is_a?(Builtin) && @return_type.name == 'void' &&
@param_types.size == 1 && @param_types[0].is_a?(Builtin) && @param_types[0].name == 'boolean'
"@Block VoidBooleanBlock"
else
"ObjCBlock"
end
end
end
class ObjCId < Entity
attr_accessor :protocols
def initialize(protocols)
super(nil, nil)
@protocols = protocols
end
def types
@protocols.map {|e| e.types}
end
def java_name
@protocols.map {|e| e.java_name}.join(' & ')
end
end
class Builtin < Entity
attr_accessor :name, :type_kinds, :java_name
def initialize(name, type_kinds = [], java_name = nil)
super(nil, nil)
@name = name
@type_kinds = type_kinds
@java_name = java_name || name
end
end
@@builtins = [
Builtin.new('boolean', [:type_bool]),
Builtin.new('byte', [:type_uchar, :type_schar, :type_char_s]),
Builtin.new('short', [:type_ushort, :type_short]),
Builtin.new('char', [:type_wchar, :type_char16]),
Builtin.new('int', [:type_uint, :type_int, :type_char32]),
Builtin.new('long', [:type_ulonglong, :type_longlong]),
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.inject({}) {|h, b| h[b.name] = b ; h}
@@builtins_by_type_kind = @@builtins.inject({}) {|h, b| 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
class AvailableAttribute < Attribute
attr_accessor :mac_version, :ios_version, :mac_dep_version, :ios_dep_version
def initialize(source)
super(source)
s = source.sub(/^[A-Z_]+\s*\(/, '')
s = s.sub(/\)$/, '')
args = s.split(/\s*,\s*/)
@mac_version = nil
@ios_version = nil
@mac_dep_version = nil
@ios_dep_version = nil
args = args.map {|e| e.sub(/^[A-Z_]+/, '')}
args = args.map {|e| e.gsub(/_/, '.')}
if source.match(/_AVAILABLE_IOS\s*\(/)
@ios_version = args[0]
elsif source.match(/_AVAILABLE_MAC\s*\(/)
@mac_version = args[0]
elsif source.match(/_AVAILABLE\s*\(/)
if args.length == 1
# E.g. MP_EXTERN_CLASS_AVAILABLE(version) = NS_CLASS_AVAILABLE(NA, version).
# Just set both versions to the specified value
@mac_version = @ios_version = args[0]
else
@mac_version = args[0]
@ios_version = args[1]
end
elsif source.match(/_DEPRECATED_MAC\s*\(/)
@mac_version = args[0]
@mac_dep_version = args[1]
elsif source.match(/_DEPRECATED_IOS\s*\(/)
@ios_version = args[0]
@ios_dep_version = args[1]
elsif source.match(/_AVAILABLE_STARTING\s*\(/)
@mac_version = args[0]
@ios_version = args[1]
elsif source.match(/_AVAILABLE_BUT_DEPRECATED\s*\(/)
@mac_version = args[0]
@mac_dep_version = args[1]
@ios_version = args[2]
@ios_dep_version = args[3]
elsif source.match(/_DEPRECATED\s*\(/)
@mac_version = args[0]
@mac_dep_version = args[1]
@ios_version = args[2]
@ios_dep_version = args[3]
end
@mac_version = @mac_version == '' ? nil : @mac_version
@mac_dep_version = @mac_version == '' ? nil : @mac_dep_version
@ios_version = @ios_version == '' ? nil : @ios_version
@ios_dep_version = @ios_version == '' ? nil : @ios_dep_version
end
end
class UnavailableAttribute < Attribute
end
class UnsupportedAttribute < Attribute
def initialize(source)
super(source)
end
end
def self.parse_attribute(cursor)
source = Bro::read_attribute(cursor)
if 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')
return IgnoredAttribute.new source
elsif source == 'NS_UNAVAILABLE' || source == 'UNAVAILABLE_ATTRIBUTE'
return UnavailableAttribute.new source
elsif source.match(/_AVAILABLE/) || source.match(/_DEPRECATED/) ||
source.match(/_AVAILABLE_STARTING/) || source.match(/_AVAILABLE_BUT_DEPRECATED/)
return AvailableAttribute.new source
else
return UnsupportedAttribute.new source
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)
super(model, cursor)
@typedef_type = cursor.typedef_type
@parameters = []
@struct = nil
@enum = nil
cursor.visit_children do |cursor, parent|
case cursor.kind
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
@enum = Enum.new model, cursor
end
next :continue
end
end
def is_callback?
end
def is_struct?
@struct != nil
end
def is_enum?
@enum != nil
end
end
class StructMember
attr_accessor :name, :type
def initialize(cursor)
@name = cursor.spelling
@type = cursor.type
end
end
class Struct < Entity
attr_accessor :members, :children, :parent, :union
def initialize(model, cursor, parent = nil, union = false)
super(model, cursor)
@name = @name.gsub(/\s*\bconst\b\s*/, '')
@name = @name.sub(/^(struct|union)\s*/, '')
@members = []
@children = []
@parent = parent
@union = union
cursor.visit_children do |cursor, parent|
case cursor.kind
when :cursor_unexposed_expr
# ignored
when :cursor_field_decl
@members.push StructMember.new cursor
when :cursor_struct, :cursor_union
s = Struct.new model, cursor, self, cursor.kind == :cursor_union
model.structs.push s
@children.push s
when :cursor_unexposed_attr, :cursor_packed_attr, :cursor_annotate_attr
a = Bro::read_attribute(cursor)
if a != '?' && model.is_included?(self)
$stderr.puts "WARN: #{@union ? 'union' : 'struct'} #{@name} at #{Bro::location_to_s(@location)} has unsupported attribute #{a}"
end
else
raise "Unknown cursor kind #{cursor.kind} in struct at #{Bro::location_to_s(@location)}"
end
next :continue
end
end
def types
@members.map {|m| m.type}
end
def is_opaque?
@members.empty?
end
end
class FunctionParameter
attr_accessor :name, :type
def initialize(cursor, def_name)
@name = cursor.spelling.size > 0 ? cursor.spelling : def_name
@type = cursor.type
end
end
class Function < Entity
attr_accessor :return_type, :parameters, :type
def initialize(model, cursor)
super(model, cursor)
@type = cursor.type
@return_type = cursor.result_type
@parameters = []
param_count = 0
@inline = false
@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, 410, 409
# Ignored
when :cursor_parm_decl
@parameters.push FunctionParameter.new cursor, "p#{param_count}"
param_count = param_count + 1
when :cursor_compound_stmt
@inline = true
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 {|e| e.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)
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.inject(Hash.new) do |h, o|
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 :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_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 - @instance_methods.find_all do |m|
p = @properties.find {|f| f.id == m.id || f.getter_name == m.name || f.setter_name == m.name}
if p
if m.name.end_with?(':')
p.setter = m
else
p.getter = m
end
m
else
nil
end
end
end
end
class ObjCClass < ObjCMemberHost
attr_accessor :superclass, :protocols, :instance_vars, :class_vars
def initialize(model, cursor)
super(model, cursor)
@superclass = nil
@protocols = []
@instance_vars = []
@class_vars = []
@opaque = false
cursor.visit_children do |cursor, parent|
case cursor.kind
when :cursor_unexposed_expr, :cursor_struct
# ignored
when :cursor_obj_c_class_ref
@opaque = @name == cursor.spelling
when :cursor_obj_c_super_class_ref
@superclass = cursor.spelling
when :cursor_obj_c_protocol_ref
@protocols.push(cursor.spelling)
when :cursor_obj_c_instance_var_decl
# @instance_vars.push(ObjCInstanceVar.new(model, cursor))
when :cursor_obj_c_class_var_decl
# @class_vars.push(ObjCClassVar.new(model, cursor))
when :cursor_obj_c_instance_method_decl
@instance_methods.push(ObjCInstanceMethod.new(model, cursor, self))
when :cursor_obj_c_class_method_decl
@class_methods.push(ObjCClassMethod.new(model, cursor, self))
when :cursor_obj_c_property_decl
@properties.push(ObjCProperty.new(model, cursor, self))
when :cursor_unexposed_attr
attribute = Bro::parse_attribute(cursor)
if attribute.is_a?(UnsupportedAttribute) && model.is_included?(self)
$stderr.puts "WARN: ObjC class #{@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 class at #{Bro::location_to_s(@location)}"
end
next :continue
end
resolve_property_accessors
end
def types
(@instance_vars.map {|m| m.types} + @class_vars.map {|m| m.types} + @instance_methods.map {|m| m.types} + @class_methods.map {|m| m.types} + @properties.map {|m| m.types}).flatten
end
def is_opaque?
@opaque
end
end
class ObjCProtocol < ObjCMemberHost
attr_accessor :protocols, :owner
def initialize(model, cursor)
super(model, cursor)
@protocols = []
@opaque = false
@owner = nil
cursor.visit_children do |cursor, parent|
case cursor.kind
when :cursor_unexposed_expr
# ignored
when :cursor_obj_c_protocol_ref
@opaque = @name == cursor.spelling
@protocols.push(cursor.spelling)
when :cursor_obj_c_class_ref
@owner = cursor.spelling
when :cursor_obj_c_instance_method_decl
@instance_methods.push(ObjCInstanceMethod.new(model, cursor, self))
when :cursor_obj_c_class_method_decl
@class_methods.push(ObjCClassMethod.new(model, cursor, self))
when :cursor_obj_c_property_decl
@properties.push(ObjCProperty.new(model, cursor, self))
when :cursor_unexposed_attr
attribute = Bro::parse_attribute(cursor)
if attribute.is_a?(UnsupportedAttribute) && model.is_included?(self)
$stderr.puts "WARN: ObjC protocol #{@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 protocol at #{Bro::location_to_s(@location)}"
end
next :continue
end
resolve_property_accessors
end
def is_informal?
!!@owner
end
def types
(@instance_methods.map {|m| m.types} + @class_methods.map {|m| m.types} + @properties.map {|m| m.types}).flatten
end
def is_opaque?
@opaque
end
def java_name
name ? ((@model.get_protocol_conf(name) || {})['name'] || name) : ''
end
end
class ObjCCategory < ObjCMemberHost
attr_accessor :owner, :protocols
def initialize(model, cursor)
super(model, cursor)
@protocols = []
@owner = nil
cursor.visit_children do |cursor, parent|
case cursor.kind
when :cursor_unexposed_expr
# ignored
when :cursor_obj_c_class_ref
@owner = cursor.spelling
when :cursor_obj_c_protocol_ref
@protocols.push(cursor.spelling)
when :cursor_obj_c_instance_method_decl
@instance_methods.push(ObjCInstanceMethod.new(model, cursor, self))
when :cursor_obj_c_class_method_decl
@class_methods.push(ObjCClassMethod.new(model, cursor, self))
when :cursor_obj_c_property_decl
@properties.push(ObjCProperty.new(model, cursor, self))
when :cursor_unexposed_attr
attribute = Bro::parse_attribute(cursor)
if attribute.is_a?(UnsupportedAttribute) && model.is_included?(self)
$stderr.puts "WARN: ObjC category #{@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 category at #{Bro::location_to_s(@location)}"
end
next :continue
end
resolve_property_accessors
end
def java_name
#name ? ((@model.get_category_conf(name) || {})['name'] || name) : ''
"#{@owner}Extensions"
end
def types
(@instance_vars.map {|m| m.types} + @class_vars.map {|m| m.types} + @instance_methods.map {|m| m.types} + @class_methods.map {|m| m.types} + @properties.map {|m| m.types}).flatten
end
end
class GlobalValueDictionaryWrapper < Entity
attr_accessor :name, :values
def initialize(model, name, enum, first)
super(model, nil)
@name = name
@enum = enum
@type = first.type
vconf = model.get_value_conf(first.name)
@java_type = vconf['type'] || model.resolve_type(@type)
@mutable = vconf['mutable'].nil? ? true : vconf['mutable']
@methods = vconf['methods']
@generate_marshalers = vconf['marshalers'] || true
@extends = vconf['dictionary_extends'] || vconf['extends'] || (is_foundation? ? "NSDictionaryWrapper" : "CFDictionaryWrapper")
@constructor_visibility = vconf['constructor_visibility']
@values = [first]
end
def is_foundation?
!["CFType", "CFString", "CFNumber"].include? @java_type
end
def is_mutable?
@mutable
end
def generate_template_data(data)
data['name'] = @name
data['extends'] = @extends
data['annotations'] = (data['annotations'] || []).push("@Library(#{$library})")
if @generate_marshalers
marshaler_lines = []
append_marshalers(marshaler_lines)
marshalers_s = marshaler_lines.flatten.join("\n ")
data['marshalers'] = "\n #{marshalers_s}\n "
end
constructor_lines = []
append_constructors(constructor_lines)
constructors_s = constructor_lines.flatten.join("\n ")
data['constructors'] = "\n #{constructors_s}\n "
method_lines = []
append_basic_methods(method_lines)
append_convenience_methods(method_lines) if [email protected]?
methods_s = method_lines.flatten.join("\n ")
data['methods'] = "\n #{methods_s}\n "
if @enum.nil?
key_lines = []
append_key_class(key_lines)
keys_s = key_lines.flatten.join("\n ")
data['keys'] = "\n #{keys_s}\n "
end
data
end
def append_marshalers(lines)
dict_type = is_foundation? ? "NSDictionary" : "CFDictionary"
base_type = is_foundation? ? "NSObject" : "CFType"
lines << "public static class Marshaler {"
lines << " @MarshalsPointer"
lines << " public static #{@name} toObject(Class<#{@name}> cls, long handle, long flags) {"
lines << " #{dict_type} o = (#{dict_type}) #{base_type}.Marshaler.toObject(#{dict_type}.class, handle, flags);"
lines << " if (o == null) {"
lines << " return null;"
lines << " }"
lines << " return new #{name}(o);"
lines << " }"
lines << " @MarshalsPointer"
lines << " public static long toNative(#{name} o, long flags) {"
lines << " if (o == null) {"
lines << " return 0L;"
lines << " }"
lines << " return #{base_type}.Marshaler.toNative(o.data, flags);"
lines << " }"
lines << "}"
array_type = is_foundation? ? "NSArray<#{dict_type}>" : "CFArray"
array_class = is_foundation? ? "NSArray.class" : "CFArray.class"
lines << "public static class AsListMarshaler {"
lines << " @MarshalsPointer"
lines << " public static List<#{@name}> toObject(Class<? extends #{base_type}> cls, long handle, long flags) {"
lines << " #{array_type} o = (#{array_type}) #{base_type}.Marshaler.toObject(#{array_class}, handle, flags);"
lines << " if (o == null) {"
lines << " return null;"
lines << " }"
lines << " List<#{@name}> list = new ArrayList<>();"
lines << " for (int i = 0; i < o.size(); i++) {"
lines << " list.add(new #{@name}(o.get(i)));" if is_foundation?
lines << " list.add(new #{@name}(o.get(i, CFDictionary.class)));" if !is_foundation?
lines << " }"
lines << " return list;"
lines << " }"
lines << " @MarshalsPointer"
lines << " public static long toNative(List<#{@name}> l, long flags) {"
lines << " if (l == null) {"
lines << " return 0L;"
lines << " }"
lines << " NSArray<NSDictionary> array = new NSMutableArray<>();" if is_foundation?
lines << " CFArray array = CFMutableArray.create();" if !is_foundation?
lines << " for (#{@name} i : l) {"
lines << " array.add(i.getDictionary());"
lines << " }"
lines << " return #{base_type}.Marshaler.toNative(array, flags);"
lines << " }"
lines << "}"
end
def append_constructors(lines)
dict_type = is_foundation? ? "NSDictionary" : "CFDictionary"
constructor_visibility = @constructor_visibility.nil? ? '' : "#{@constructor_visibility} "
lines << "#{constructor_visibility}#{@name}(#{dict_type} data) {"
lines << " super(data);"
lines << "}"
lines << "public #{@name}() {}" if is_mutable?
end
def append_basic_methods(lines)
key_type = @enum ? @enum.name : @java_type
key_value = @enum ? "key.value()" : "key"
base_type = is_foundation? ? "NSObject" : "NativeObject"
lines << "public boolean has(#{key_type} key) {"
lines << " return data.containsKey(#{key_value});"
lines << "}"
lines << "public NSObject get(#{key_type} key) {" if is_foundation?
lines << "public <T extends NativeObject> T get(#{key_type} key, Class<T> type) {" if !is_foundation?
lines << " if (has(key)) {"
lines << " return data.get(#{key_value});" if is_foundation?
lines << " return data.get(#{key_value}, type);" if !is_foundation?
lines << " }"
lines << " return null;"
lines << "}"
if is_mutable?
lines << "public #{@name} set(#{key_type} key, #{base_type} value) {"
lines << " data.put(#{key_value}, value);"
lines << " return this;"
lines << "}"
end
end
def append_convenience_methods(lines)
lines << "\n"
@values.find_all {|v| v.is_available?($mac_version, $ios_version) && !v.is_outdated?}.each do |v|
vconf = @model.get_value_conf(v.name)
vname = vconf['name'] || v.name
method = @methods.detect {|m| vname == m[0] || v.name == m[0] }
if method
mconf = method[1]
name = mconf['name'] || method[0]
param_name = mconf['param_name'] || name[0].downcase + name[1..-1]
omit_prefix = mconf['omit_prefix'] || false
type = mconf['type'] || 'boolean'
getter = @model.getter_for_name(param_name, type, omit_prefix)
default_value = mconf['default'] || @model.default_value_for_type(type)
key_accessor = @enum ? "#{@enum.name}.#{vname}" : "Keys.#{vname}()"
annotations = mconf['annotations'] && !mconf['annotations'].empty? ? mconf['annotations'].uniq.join(' ') : nil
@model.push_availability(v, lines)
lines << "#{annotations}" if annotations
lines << "public #{type} #{getter}() {"
lines << " if (has(#{key_accessor})) {"
lines << convenience_getter_value(type, mconf['hint'], key_accessor)
lines << " }"
lines << " return #{default_value};"
lines << "}"
mutable = is_mutable?
unless mconf['mutable'].nil?
mutable = mconf['mutable']
end
if mutable
setter = @model.setter_for_name(name, omit_prefix)
convenience_setter = convenience_setter_value(type, mconf['hint'], param_name)
if convenience_setter.respond_to?('each')
convenience_setter << " set(#{key_accessor}, val);"
convenience_setter = convenience_setter.flatten.join("\n ")
else
convenience_setter = " set(#{key_accessor}, #{convenience_setter});"
end
@model.push_availability(v, lines)
lines << "#{annotations}" if annotations
lines << "public #{@name} #{setter}(#{type} #{param_name}) {"
lines << convenience_setter
lines << " return this;"
lines << "}"
end
end
end
end
def convenience_getter_value(type, type_hint, key_accessor)
s = []
resolved_type = @model.resolve_type_by_name(type)
type_no_generics = type.partition("<").first
if type_hint
hint_parts = type_hint.partition("<")
type_generic_hint = hint_parts[2].partition(">").first
type_hint = hint_parts.first
end
name = resolved_type ? resolved_type.name : type
java_type = type
if is_foundation?
if resolved_type.is_a?(GlobalValueEnumeration) || type_hint == 'GlobalValueEnumeration'
java_type = resolved_type ? resolved_type.java_type : type_generic_hint
case java_type
when 'int', 'long', 'float', 'double'
s << "NSNumber val = (NSNumber) get(#{key_accessor});"
s << "return #{name}.valueOf(val.#{java_type}Value());"