This repository has been archived by the owner on Jan 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathgenerate_jsb.py
executable file
·3067 lines (2514 loc) · 109 KB
/
generate_jsb.py
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/python
# ----------------------------------------------------------------------------
# Generates JavaScript Bindings glue code after C / Objective-C code
#
# Author: Ricardo Quesada
# Copyright 2012 (C) Zynga, Inc
#
# License: MIT
# ----------------------------------------------------------------------------
'''
Generates JavaScript Bindings glue code after C / Objective-C code
'''
__docformat__ = 'restructuredtext'
# python
import sys
import os
import re
import getopt
import ast
import xml.etree.ElementTree as ET
import itertools
import copy
import datetime
import ConfigParser
import string
class MethodNotFoundException(Exception):
pass
class ParseException(Exception):
pass
class ParseOKException(Exception):
pass
#
# Globals
#
BINDINGS_PREFIX = 'jsb_'
PROXY_PREFIX = 'JSB_'
METHOD_CONSTRUCTOR, METHOD_CLASS, METHOD_INIT, METHOD_REGULAR = xrange(4)
JSB_VERSION = 'v0.6'
# get_class from: http://stackoverflow.com/a/452981
def get_class(kls):
parts = kls.split('.')
module = ".".join(parts[:-1])
if len(parts) == 1:
m = sys.modules[__name__]
m = getattr(m, parts[0])
else:
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
# uncapitalize from: http://stackoverflow.com/a/3847369
uncapitalize = lambda s: s[:1].lower() + s[1:] if s else ''
# xml2d recipe copied from here:
# http://code.activestate.com/recipes/577722-xml-to-python-dictionary-and-back/
def xml2d(e):
"""Convert an etree into a dict structure
@type e: etree.Element
@param e: the root of the tree
@return: The dictionary representation of the XML tree
"""
def _xml2d(e):
kids = dict(e.attrib)
for k, g in itertools.groupby(e, lambda x: x.tag):
g = [_xml2d(x) for x in g]
kids[k] = g
return kids
return {e.tag: _xml2d(e)}
class JSBGenerate(object):
def __init__(self, config):
self.config = config
# Generating Object Oriented Functions ?
self.generating_OOF = False
# list of JS functions names that have a C / C++ implementation
# Used to generate 'externs' definitions for Google Closure
self.bound_js_functions = []
#
# UGLY CODE XXX
# This should be accessed using self.config, not the following ugly code
#
self.namespace = config.namespace
self.bs = config.bs
# functions
self.struct_properties = config.struct_properties
self.import_files = config.import_files
self.compatible_with_cpp = config.compatible_with_cpp
self.functions_to_bind = config.functions_to_bind
self.callback_functions = config.callback_functions
self.struct_opaque = config.struct_opaque
self.struct_manual = config.struct_manual
self.function_properties = config.function_properties
self.function_prefix = config.function_prefix
self.function_classes = config.function_classes
# OO Functions
self.c_object_properties = config.c_object_properties
self.manual_bound_methods = config.manual_bound_methods
# classes
self.supported_classes = config.supported_classes
self.class_properties = config.class_properties
self.classes_to_bind = config.classes_to_bind
self.classes_to_ignore = config.classes_to_ignore
self.method_properties = config.method_properties
self.class_properties = config.class_properties
self.complement = config.complement
self.class_manual = config.class_manual
self.parsed_classes = config.parsed_classes
self._inherit_class_methods = config._inherit_class_methods
self.callback_methods = config.callback_methods
self.manual_methods = config.manual_methods
self.class_prefix = config.class_prefix
# constants
self.constant_properties = config.constant_properties
# JS
self.js_new_methods = config.js_new_methods
# Misc
self.bridgesupport_files = config.bridgesupport_files
#
# conversion rules
#
self.init_args_conversion()
def init_args_conversion(self):
#
# Conversion rules
#
# Shared
# Left column: BridgeSupport types
# Right column: JS types
self.supported_declared_types = {
'NSString*': 'S',
'NSArray*': 'array',
'NSMutableArray*': 'array',
'CCArray*': 'array',
'NSSet*': 'set',
'NSDictionary*': 'dict',
'NSMutableDictionary*': 'dict',
'const char*': 'char*',
'const unsigned char*': 'char*',
'char*': 'char*',
'unsigned char*': 'char*',
'void (^)(id)': 'f',
'void (^)(CCNode *)': 'f',
}
self.supported_types = {
'f': 'd', # float
'd': 'd', # double
'i': 'i', # integer
'I': 'u', # unsigned integer
'c': 'c', # char
'C': 'c', # unsigned char
'B': 'b', # BOOL
's': 'c', # short
'v': None, # void (for retval)
'L': 'long', # long (special conversion)
'Q': 'longlong', # long long (special conversion)
}
self.objc_to_js_conversions = {
'i': 'INT_TO_JSVAL((int32_t)%(objc_val)s)',
'u': 'UINT_TO_JSVAL((uint32_t)%(objc_val)s)',
'b': 'BOOLEAN_TO_JSVAL(%(objc_val)s)',
's': 'STRING_TO_JSVAL(%(objc_val)s)',
'd': 'DOUBLE_TO_JSVAL(%(objc_val)s)',
'c': 'INT_TO_JSVAL((int32_t)%(objc_val)s)',
'long': 'JSB_jsval_from_long(cx, %(objc_val)s)', # long: not supported on JS 64-bit
'longlong': 'JSB_jsval_from_longlong(cx, %(objc_val)s)', # long long: not supported on JS
'void': 'JSVAL_VOID',
None: 'JSVAL_VOID',
'o': 'JSB_jsval_from_NSObject(cx, %(objc_val)s)',
'S': 'JSB_jsval_from_NSString( cx, (NSString*) %(objc_val)s )',
'char*': 'JSB_jsval_from_charptr( cx, %(objc_val)s )',
'array': 'JSB_jsval_from_NSArray( cx, (NSArray*) %(objc_val)s )',
'set': 'JSB_jsval_from_NSSet( cx, (NSSet*) %(objc_val)s )',
'dict': 'JSB_jsval_from_NSDictionary( cx, (NSDictionary*) %(objc_val)s )',
}
# Arguments only
# b JSBool Boolean
# c uint16_t/jschar ECMA uint16_t, Unicode char
# i int32_t ECMA int32_t
# u uint32_t ECMA uint32_t
# j int32_t Rounded int32_t (coordinate)
# d double IEEE double
# I double Integral IEEE double
# S JSString * Unicode string, accessed by a JSString pointer
# W jschar * Unicode character vector, 0-terminated (W for wide)
# o JSObject * Object reference
# f JSFunction * Function private
# v jsval Argument value (no conversion)
# * N/A Skip this argument (no vararg)
# / N/A End of required arguments
# More info:
# https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JS_ConvertArguments
self.args_js_types_conversions = {
'b': ['JSBool', 'JS_ValueToBoolean'],
'd': ['double', 'JS_ValueToNumber'],
'I': ['double', 'JS_ValueToNumber'], # double converted to string
'i': ['int32_t', 'JSB_jsval_to_int32'],
'j': ['int32_t', 'JSB_jsval_to_int32'],
'u': ['uint32_t', 'JSB_jsval_to_uint32'],
'c': ['uint16_t', 'JSB_jsval_to_uint16'],
}
self.args_js_special_type_conversions = {
'S': ['JSB_jsval_to_NSString', 'NSString*'],
'dict': ['JSB_jsval_to_NSDictionary', 'NSDictionary*'],
'char*': ['JSB_jsval_to_charptr', 'const char*'],
'o': ['JSB_jsval_to_NSObject', 'id'],
'array': ['JSB_jsval_to_NSArray', 'NSArray*'],
'set': ['JSB_jsval_to_NSSet', 'NSSet*'],
'f': ['JSB_jsval_to_block_1', 'js_block'],
'long': ['JSB_jsval_to_long', 'long'],
'longlong': ['JSB_jsval_to_longlong', 'long long'],
}
#
# BEGIN Helper functions
#
def convert_to_python_type(self, v):
l = v.lower()
if l == 'true':
return True
elif l == 'false':
return False
return v
# whether or not the method is a constructor
def get_function(self, function_name):
'''returns a function from function name'''
funcs = self.bs['signatures']['function']
for f in funcs:
if f['name'] == function_name:
return f
raise ParseException("Function %s not found" % function_name)
def is_class_constructor(self, method):
if self.is_class_method(method) and 'retval' in method:
retval = method['retval']
dt = retval[0]['declared_type']
# Should also check the naming convention. eg: 'spriteWith...'
if dt == 'id':
return True
return False
# whether or not the method is an initializer
def is_method_initializer(self, method):
# Is this is a method ?
if not 'selector' in method:
return False
if 'retval' in method:
retval = method['retval']
dt = retval[0]['declared_type']
if method['selector'].startswith('init') and dt == 'id':
return True
return False
def get_struct_type_and_num_of_elements(self, struct):
# PRECOND: Structure must be valid
# BridgeSupport to TypedArray
bs_to_type_array = {'c': 'js::ArrayBufferView::TYPE_INT8',
'C': 'js::ArrayBufferView::TYPE_UINT8',
's': 'js::ArrayBufferView::TYPE_INT16',
'S': 'js::ArrayBufferView::TYPE_UINT16',
'i': 'js::ArrayBufferView::TYPE_INT32',
'I': 'js::ArrayBufferView::TYPE_UINT32',
'f': 'js::ArrayBufferView::TYPE_FLOAT32',
'd': 'js::ArrayBufferView::TYPE_FLOAT64',
}
inner = struct.replace('{', '')
inner = inner.replace('{', '')
inner = inner.replace('}', '')
key, value = inner.split('=')
k = value[0]
if not k in bs_to_type_array:
raise Exception('Structure cannot be converted')
# returns type of structure and len
return (bs_to_type_array[k], len(value))
def get_name_for_manual_struct(self, struct_name):
value = self.get_struct_property(struct_name, 'manual')
if not value:
return struct_name
return value
def get_struct_property(self, struct_name, property):
try:
return self.struct_properties[struct_name][property]
except KeyError:
return None
def is_valid_structure(self, struct):
# Only support non-nested structures of only one type
# valids:
# {xxx=CCC}
# {xxx=ff}
# invalids:
# {xxx=CC{yyy=C}}
# {xxx=fC}
if not struct:
return False
if struct[0] == '{' and struct[-1] == '}' and len(struct.split('{')) == 2:
inner = struct.replace('{', '')
inner = inner.replace('{', '')
inner = inner.replace('}', '')
key, value = inner.split('=')
# values should be of the same type
previous = None
for c in value:
if previous != None:
if previous != c:
return False
previous = c
return True
return False
def get_class_property(self, property, class_name):
try:
return self.class_properties[class_name][property]
except KeyError:
return None
def is_class_method(self, method):
return 'class_method' in method and method['class_method'] == 'true'
def get_constant_property(self, property, default=None):
try:
v = self.constant_properties[property]
v = self.convert_to_python_type(v)
return v
except KeyError:
return default
def get_number_of_arguments(self, function):
ret = 0
if 'arg' in function:
return len(function['arg'])
return ret
#
# END helper functions
#
def generate_pragma_mark(self, class_name, fd):
pragm_mark = '''
/*
* %s
*/
#pragma mark - %s
'''
fd.write(pragm_mark % (class_name, class_name))
def generate_autogenerated_prefix(self, fd):
autogenerated_template = '''/*
* AUTOGENERATED FILE. DO NOT EDIT IT
* Generated by "%s -c %s" on %s
* Script version: %s
*/
#%s "jsb_config.h"
#if JSB_INCLUDE_%s
'''
if self.compatible_with_cpp:
import_name = 'include'
else:
import_name = 'import'
name = self.namespace.upper()
fd.write(autogenerated_template % (os.path.basename(sys.argv[0]), os.path.basename(sys.argv[2]), datetime.date.today(), JSB_VERSION, import_name, name))
# Possible Imported files
for i in self.import_files:
if i and i != '':
fd.write('#%s "%s"\n' % (import_name, i))
def generate_autogenerate_suffix(self, fd):
autogenerated_template = '''
#endif // JSB_INCLUDE_%s
'''
name = self.namespace.upper()
fd.write(autogenerated_template % name)
def generate_retval(self, declared_type, js_type, method=None):
if method and self.is_method_initializer(method):
return '\tJS_SET_RVAL(cx, vp, JSVAL_TRUE);'
conversion = self.convert_objc_to_js(declared_type, js_type)
conversion = conversion % ({'objc_val': 'ret_val'})
template = '''
\tJS_SET_RVAL(cx, vp, %s);
'''
return template % (conversion)
def validate_retval(self, method, class_name=None):
# parse ret value
if 'retval' in method:
# Special case for initializer methods
if self.is_method_initializer(method):
return (None, None)
# Special case for class constructors
elif self.is_class_constructor(method):
return ('o', class_name + '*')
retval = method['retval'][0]
return self.validate_argument(retval)
return (None, None)
def validate_argument(self, arg):
t = arg['type']
dt = arg['declared_type']
# Treat 'id' as NSObject*
if dt == 'id':
dt = 'NSObject*'
# Treat 'int64_t' as long long
if dt == 'int64_t':
t='Q';
dt_class_name = dt.replace('*', '')
# IMPORTANT: 1st search on declared types.
# NSString should be treated as a special case, not as a generic object
if dt in self.supported_declared_types:
return (self.supported_declared_types[dt], dt)
elif t in self.supported_types:
return (self.supported_types[t], dt)
# special case for Objects
elif t == '@' and dt_class_name in self.supported_classes:
return ('o', dt)
# valid 'opaque' struct ?
elif dt in self.struct_opaque:
return ('N/A', dt)
# valid manual struct ?
elif dt in self.struct_manual:
return ('N/A', dt)
# valid automatic struct ?
elif self.is_valid_structure(t):
return (t, dt)
raise ParseException("Unsupported argument: %s" % dt)
def validate_arguments(self, method):
args_js_type = []
args_declared_type = []
# parse arguments
if 'arg' in method:
args = method['arg']
for arg in args:
js_type, dt = self.validate_argument(arg)
# Skip argument if they are none
if js_type is not None and dt is not None:
args_js_type.append(js_type)
args_declared_type.append(dt)
return (args_js_type, args_declared_type)
def generate_argument_variadic_2_nsarray(self):
template = '\tok &= JSB_jsvals_variadic_to_NSArray( cx, argvp, argc, &arg0 );\n'
self.fd_mm.write(template)
def convert_js_to_objc(self, js_type, objc_type):
if objc_type in self.function_classes and self.generating_OOF:
return 'JSB_jsval_to_c_class( cx, %(jsval)s, (void**)%(retval)s, NULL )'
elif objc_type in self.struct_opaque:
return 'JSB_jsval_to_opaque( cx, %(jsval)s, (void**)%(retval)s )'
elif objc_type in self.struct_manual:
new_name = self.get_name_for_manual_struct(objc_type)
return 'JSB_jsval_to_%s( cx, %%(jsval)s, (%s*) %%(retval)s )' % (new_name, new_name)
elif self.is_valid_structure(js_type):
return 'JSB_jsval_to_struct( cx, %%(jsval)s, %%(retval)s, sizeof(%s) )' % (objc_type)
elif js_type in self.args_js_types_conversions:
js_convert = self.args_js_types_conversions[js_type][1]
return js_convert + '( cx, %(jsval)s, %(retval)s )'
elif js_type in self.args_js_special_type_conversions:
js_convert = self.args_js_special_type_conversions[js_type][0]
if js_type == 'f':
return js_convert + '( cx, %(jsval)s, JS_THIS_OBJECT(cx, vp), %(retval)s )'
else:
return js_convert + '( cx, %(jsval)s, %(retval)s )'
else:
raise ParseException('Unsupported argument type: %s' % js_type)
def convert_objc_to_js(self, objc_type, js_type):
if objc_type in self.function_classes and self.generating_OOF:
# remove '*' from class name
klass = objc_type[:-1]
template = 'JSB_jsval_from_c_class( cx, %%(objc_val)s, %s, %s, "%s" )'
return template % ('JSB_%s_object' % klass, 'JSB_%s_class' % klass, klass)
elif objc_type in self.struct_opaque:
return 'JSB_jsval_from_opaque( cx, %(objc_val)s )'
elif objc_type in self.struct_manual:
new_name = self.get_name_for_manual_struct(objc_type)
template = 'JSB_jsval_from_%s( cx, (%s)%%(objc_val)s )'
return template % (new_name, objc_type)
elif self.is_valid_structure(js_type):
t, l = self.get_struct_type_and_num_of_elements(js_type)
template = 'JSB_jsval_from_struct( cx, %d, &%%(objc_val)s, %s )'
return template % (l, t)
elif js_type in self.objc_to_js_conversions:
return self.objc_to_js_conversions[js_type]
else:
raise Exception("Invalid key: %s" % js_type)
def generate_argument(self, i, arg_js_type, arg_declared_type):
template = self.convert_js_to_objc(arg_js_type, arg_declared_type)
template = template % ({
"jsval": "*argvp++",
"retval": "&arg%d" % i
})
return "\tok &= %s;\n" % template
# The type of the value returned by the JS conversion function
def get_conversion_return_type(self, js_type, objc_type):
if objc_type in self.struct_opaque or objc_type in self.function_classes:
return objc_type
elif objc_type in self.struct_manual:
return objc_type
elif self.is_valid_structure(js_type):
return objc_type
elif js_type in self.args_js_types_conversions:
return self.args_js_types_conversions[js_type][0]
elif js_type in self.args_js_special_type_conversions:
return self.args_js_special_type_conversions[js_type][1]
else:
raise ParseException('Unsupported argument type: %s' % js_type)
def generate_arguments(self, args_declared_type, args_js_type, properties={}):
# First time
self.fd_mm.write('\tjsval *argvp = JS_ARGV(cx,vp);\n')
self.fd_mm.write('\tJSBool ok = JS_TRUE;\n')
# first_arg is used by "OO Functions". The first argument should be "self", so argv[0] is skipped in those cases
first_arg = properties.get('first_arg', 0)
# Declare variables
declared_vars = '\t'
for i, arg in enumerate(args_js_type):
if i < first_arg:
continue
arg_type = self.get_conversion_return_type(arg, args_declared_type[i])
declared_vars += '%s arg%d;' % (arg_type, i)
declared_vars += ' '
self.fd_mm.write('%s\n\n' % declared_vars)
# Optional Arguments ? Used when merging methods
min_args = properties.get('min_args', None)
max_args = properties.get('max_args', None)
if min_args != max_args:
optional_args = min_args
else:
optional_args = None
# Use variables
# Special case for variadic_2_nsarray
if 'variadic_2_array' in properties:
self.generate_argument_variadic_2_nsarray()
else:
for i, arg in enumerate(args_js_type):
if i < first_arg:
continue
if optional_args != None and i >= optional_args:
self.fd_mm.write('\tif (argc >= %d) {\n\t' % (i + 1))
self.fd_mm.write(self.generate_argument(i, arg, args_declared_type[i]))
if optional_args != None and i >= optional_args:
self.fd_mm.write('\t}\n')
self.fd_mm.write('\tJSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments");\n')
#
# Externs related
#
def externs_create_file(self):
self.externs_fd = open('%s_externs.js' % (self.namespace), 'w')
def externs_close_file(self):
self.externs_fd.close()
def externs_write_function(self, func_name):
js_body = 'function %s(){};\n'
self.externs_fd.write(js_body % func_name)
def generate_externs(self):
if len(self.bound_js_functions) > 0:
self.externs_create_file()
for function_name in self.bound_js_functions:
self.externs_write_function(function_name)
self.externs_close_file()
#
#
# Generates Classes
#
#
class JSBGenerateClasses(JSBGenerate):
def __init__(self, config):
super(JSBGenerateClasses, self).__init__(config)
#
# BEGIN helper functions
#
def create_files(self):
self.fd_h = open('%s%s_classes.h' % (BINDINGS_PREFIX, self.namespace), 'w')
self.generate_class_header_prefix()
self.fd_mm = open('%s%s_classes.mm' % (BINDINGS_PREFIX, self.namespace), 'w')
def convert_class_name_to_js(self, class_name):
# rename rule ?
if class_name in self.class_properties and 'name' in self.class_properties[class_name]:
name = self.class_properties[class_name]['name']
name = name.replace('"', '')
return name
# Prefix rule ?
if class_name.startswith(self.class_prefix):
class_name = class_name[len(self.class_prefix):]
return class_name
def convert_selector_name_to_native(self, name):
return name.replace(':', '_')
def convert_selector_name_to_js(self, class_name, selector):
# Does it have a rename rule ?
try:
return self.method_properties[class_name][selector]['name']
except KeyError:
pass
# Is it a property ?
try:
if selector in self.complement[class_name]['properties']:
# Does it have a properties ?
# props = self.complement[class_name]['properties'][selector]
# print selector
# props = self.parse_objc_properties(props)
# print props
# if 'getter' in props:
# ret = props['getter']
# print ret
# xxxx
# else
ret = 'get%s%s' % (selector[0].capitalize(), selector[1:])
return ret
except KeyError:
pass
name = ''
parts = selector.split(':')
for i, arg in enumerate(parts):
if i == 0:
name += arg
elif arg:
name += arg[0].capitalize() + arg[1:]
return name
def parse_objc_properties(self, props):
ret = {}
# only get first element of array
p = props[0].split(',')
for k in p:
key_value = k.split('=')
key = key_value[0].strip()
if len(key_value) > 1:
value = key_value[1].strip()
else:
value = None
ret[key] = value
return ret
def get_method(self, class_name, method_name):
for klass in self.bs['signatures']['class']:
if klass['name'] == class_name:
for m in klass['method']:
if m['selector'] == method_name:
return m
# Not found... search in protocols
if 'informal_protocol' in self.bs['signatures'] and 'protocols' in self.complement[class_name]:
list_of_protocols = self.bs['signatures']['informal_protocol']
protocols = self.complement[class_name]['protocols']
for protocol in protocols:
for ip in list_of_protocols:
# protocol match ?
if ip['name'] == protocol:
# traverse method then
for m in ip['method']:
if m['selector'] == method_name:
return m
raise MethodNotFoundException("Method not found for %s # %s" % (class_name, method_name))
def get_method_type(self, method):
if self.is_class_constructor(method):
method_type = METHOD_CONSTRUCTOR
elif self.is_class_method(method):
method_type = METHOD_CLASS
elif self.is_method_initializer(method):
method_type = METHOD_INIT
else:
method_type = METHOD_REGULAR
return method_type
def get_callback_args_for_method(self, method):
method_name = method['selector']
method_args = method_name.split(':')
full_args = []
args = []
if 'arg' in method:
for i, arg in enumerate(method['arg']):
full_args.append(method_args[i] + ':')
full_args.append('(' + arg['declared_type'] + ')')
full_args.append(arg['name'] + ' ')
args.append(method_args[i] + ':')
args.append(arg['name'] + ' ')
return [''.join(full_args), ''.join(args)]
return method_name, method_name
def get_parent_class(self, class_name):
try:
parent = self.complement[class_name]['subclass']
except KeyError:
return None
return parent
def get_class_method(self, class_name):
class_methods = []
klass = None
list_of_classes = self.bs['signatures']['class']
for k in list_of_classes:
if k['name'] == class_name:
klass = k
if not klass:
raise Exception("Base class not found: %s" % class_name)
for m in klass['method']:
if self.is_class_method(m):
class_methods.append(m)
return class_methods
def inherits_class_methods(self, class_name, methods_to_parse=[]):
i = self.get_class_property('inherit_class_methods', class_name)
if i != None:
return i
inherit = self._inherit_class_methods.lower()
if inherit == 'false':
return False
elif inherit == 'true':
return True
elif inherit == 'auto':
for m in methods_to_parse:
if self.is_class_constructor(m):
return False
else:
raise Exception("Unknown value for inherit_class_methods: %s", self._inherit_class_methods)
return True
def requires_swizzle(self, class_name):
if class_name in self.callback_methods:
for m in self.callback_methods[class_name]:
if not self.get_method_property(class_name, m, 'no_swizzle'):
return True
return False
def get_method_property(self, class_name, method_name, prop):
try:
return self.method_properties[class_name][method_name][prop]
except KeyError:
return None
#
# END helper functions
#
#
# "class" constructor and destructor
#
def generate_constructor(self, class_name):
# Global Variables
# JSB_CCNode
# JSB_CCNode
constructor_globals = '''
JSClass* %s_class = NULL;
JSObject* %s_object = NULL;
'''
# 1: JSB_CCNode,
# 2: JSB_CCNode,
# 8: possible callback code
constructor_template = '''// Constructor
JSBool %s_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
\tJSObject *jsobj = [%s createJSObjectWithRealObject:nil context:cx];
\tJS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj));
\treturn JS_TRUE;
}
'''
proxy_class_name = '%s%s' % (PROXY_PREFIX, class_name)
self.fd_mm.write(constructor_globals % (proxy_class_name, proxy_class_name))
self.fd_mm.write(constructor_template % (proxy_class_name, proxy_class_name))
def generate_destructor(self, class_name):
destructor_template = '''
// Destructor
void %s_finalize(JSFreeOp *fop, JSObject *obj)
{
\tCCLOGINFO(@"jsbindings: finalizing JS object %%p (%s)", obj);
//\tJSB_NSObject *proxy = (JSB_NSObject*) JSB_get_proxy_for_jsobject(obj);
//\tif (proxy) {
//\t\t[[proxy realObj] release];
//\t}
\tJSB_del_proxy_for_jsobject( obj );
}
'''
proxy_class_name = '%s%s' % (PROXY_PREFIX, class_name)
self.fd_mm.write(destructor_template % (proxy_class_name,
class_name))
def generate_ctor_method(self, klass_name):
template = '''
// 'ctor' method. Needed for subclassing native objects in JS
JSBool JSB_%s_ctor(JSContext *cx, uint32_t argc, jsval *vp) {
\tJSObject* obj = (JSObject *)JS_THIS_OBJECT(cx, vp);
\tJSB_PRECONDITION2( !JSB_get_proxy_for_jsobject(obj), cx, JS_FALSE, "Object already initialzied. error" );
\tJSB_%s *proxy = [[JSB_%s alloc] initWithJSObject:obj class:[%s class]];
\t[[proxy class] swizzleMethods];
\tJS_SET_RVAL(cx, vp, JSVAL_TRUE);
\treturn JS_TRUE;
}
'''
self.fd_mm.write(template % (klass_name, klass_name, klass_name, klass_name))
#
# Method generator functions
#
def generate_method_call_to_real_object(self, selector_name, num_of_args, ret_js_type, args_declared_type, args_js_type, class_name, method_type):
args = selector_name.split(':')
if method_type == METHOD_INIT:
prefix = '\t%s *real = [(%s*)[proxy.klass alloc] ' % (class_name, class_name)
suffix = '\n\t[proxy setRealObj: real];\n\t[real autorelease];\n'
suffix += '\n\tobjc_setAssociatedObject(real, &JSB_association_proxy_key, proxy, OBJC_ASSOCIATION_RETAIN);'
suffix += '\n\t[proxy release];'
elif method_type == METHOD_REGULAR:
prefix = '\t%s *real = (%s*) [proxy realObj];\n\t' % (class_name, class_name)
suffix = ''
if ret_js_type:
prefix = prefix + 'ret_val = '
prefix = prefix + '[real '
elif method_type == METHOD_CONSTRUCTOR:
prefix = '\tret_val = [%s ' % (class_name)
suffix = ''
elif method_type == METHOD_CLASS:
if not ret_js_type:
prefix = '\t[%s ' % (class_name)
else:
prefix = '\tret_val = [%s ' % (class_name)
suffix = ''
else:
raise Exception('Invalid method type')
call = ''
for i, arg in enumerate(args):
if num_of_args == 0:
call += arg
elif i + 1 > num_of_args:
break
elif arg: # empty arg?
if args_js_type[i] == 'o':
call += '%s:arg%d ' % (arg, i)
else:
# cast needed to prevent compiler errors
call += '%s:(%s)arg%d ' % (arg, args_declared_type[i], i)
call += ' ];'
return '%s%s%s' % (prefix, call, suffix)
def generate_method_prefix(self, class_name, method, num_of_args, method_type):
# JSB_CCNode, setPosition
# "!" or ""
# proxy.initialized = YES (or nothing)
template_methodname = '''
JSBool %s_%s%s(JSContext *cx, uint32_t argc, jsval *vp) {
'''
template_init = '''
\tJSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp);
\tJSB_NSObject *proxy = (JSB_NSObject*) JSB_get_proxy_for_jsobject(jsthis);
\tJSB_PRECONDITION2( proxy && %s[proxy realObj], cx, JS_FALSE, "Invalid Proxy object");
'''
selector = method['selector']
converted_name = self.convert_selector_name_to_native(selector)
# method name
class_method = '_static' if self.is_class_method(self.current_method) else ''
self.fd_mm.write(template_methodname % (PROXY_PREFIX + class_name, converted_name, class_method))
# method asserts for instance methods
if method_type == METHOD_INIT or method_type == METHOD_REGULAR:
assert_init = '!' if method_type == METHOD_INIT else ''
self.fd_mm.write(template_init % assert_init)
try:
# Does it have optional arguments ?
properties = self.method_properties[class_name][selector]
min_args = properties.get('min_args', None)
max_args = properties.get('max_args', None)
if min_args != max_args:
method_assert_on_arguments = '\tJSB_PRECONDITION2( argc >= %d && argc <= %d , cx, JS_FALSE, "Invalid number of arguments" );\n' % (min_args, max_args)
elif 'variadic_2_array' in properties:
method_assert_on_arguments = '\tJSB_PRECONDITION2( argc >= 0, cx, JS_FALSE, "Invalid number of arguments" );\n'
else:
# default
method_assert_on_arguments = '\tJSB_PRECONDITION2( argc == %d, cx, JS_FALSE, "Invalid number of arguments" );\n' % num_of_args
except KeyError:
# No, it only has required arguments
method_assert_on_arguments = '\tJSB_PRECONDITION2( argc == %d, cx, JS_FALSE, "Invalid number of arguments" );\n' % num_of_args
self.fd_mm.write(method_assert_on_arguments)
def generate_method_suffix(self):
end_template = '''
\treturn JS_TRUE;
}