-
Notifications
You must be signed in to change notification settings - Fork 153
/
generator.py
executable file
·1802 lines (1552 loc) · 73 KB
/
generator.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/env python
# generator.py
# simple C++ generator, originally targetted for Spidermonkey bindings
#
# Copyright (c) 2011 - Zynga Inc.
from clang import cindex
import sys
import ConfigParser
import yaml
import re
import os
import inspect
import traceback
from Cheetah.Template import Template
type_map = {
cindex.TypeKind.VOID : "void",
cindex.TypeKind.BOOL : "bool",
cindex.TypeKind.CHAR_U : "unsigned char",
cindex.TypeKind.UCHAR : "unsigned char",
cindex.TypeKind.CHAR16 : "char",
cindex.TypeKind.CHAR32 : "char",
cindex.TypeKind.USHORT : "unsigned short",
cindex.TypeKind.UINT : "unsigned int",
cindex.TypeKind.ULONG : "unsigned long",
cindex.TypeKind.ULONGLONG : "unsigned long long",
cindex.TypeKind.CHAR_S : "char",
cindex.TypeKind.SCHAR : "char",
cindex.TypeKind.WCHAR : "wchar_t",
cindex.TypeKind.SHORT : "short",
cindex.TypeKind.INT : "int",
cindex.TypeKind.LONG : "long",
cindex.TypeKind.LONGLONG : "long long",
cindex.TypeKind.FLOAT : "float",
cindex.TypeKind.DOUBLE : "double",
cindex.TypeKind.LONGDOUBLE : "long double",
cindex.TypeKind.NULLPTR : "NULL",
cindex.TypeKind.OBJCID : "id",
cindex.TypeKind.OBJCCLASS : "class",
cindex.TypeKind.OBJCSEL : "SEL",
# cindex.TypeKind.ENUM : "int"
}
INVALID_NATIVE_TYPE = "??"
default_arg_type_arr = [
# An integer literal.
cindex.CursorKind.INTEGER_LITERAL,
# A floating point number literal.
cindex.CursorKind.FLOATING_LITERAL,
# An imaginary number literal.
cindex.CursorKind.IMAGINARY_LITERAL,
# A string literal.
cindex.CursorKind.STRING_LITERAL,
# A character literal.
cindex.CursorKind.CHARACTER_LITERAL,
# [C++ 2.13.5] C++ Boolean Literal.
cindex.CursorKind.CXX_BOOL_LITERAL_EXPR,
# [C++0x 2.14.7] C++ Pointer Literal.
cindex.CursorKind.CXX_NULL_PTR_LITERAL_EXPR,
cindex.CursorKind.GNU_NULL_EXPR,
# An expression that refers to some value declaration, such as a function,
# varible, or enumerator.
cindex.CursorKind.DECL_REF_EXPR
]
stl_type_map = {
'std_function_args': 1000,
'std::unordered_map': 2,
'std::unordered_multimap': 2,
'std::map': 2,
'std::multimap': 2,
'std::vector': 1,
'std::list': 1,
'std::forward_list': 1,
'std::priority_queue': 1,
'std::set': 1,
'std::multiset': 1,
'std::unordered_set': 1,
'std::unordered_multiset': 1,
'std::stack': 1,
'std::queue': 1,
'std::deque': 1,
'std::array': 1,
'unordered_map': 2,
'unordered_multimap': 2,
'map': 2,
'multimap': 2,
'vector': 1,
'list': 1,
'forward_list': 1,
'priority_queue': 1,
'set': 1,
'multiset': 1,
'unordered_set': 1,
'unordered_multiset': 1,
'stack': 1,
'queue': 1,
'deque': 1,
'array': 1
}
def find_sub_string_count(s, start, end, substr):
count = 0
pos = s.find(substr, start, end)
if pos != -1:
next_count = find_sub_string_count(s, pos + 1, end, substr)
count = next_count + 1
return count
def split_container_name(name):
name = name.strip()
left = name.find('<')
right = -1
if left != -1:
right = name.rfind('>')
if left == -1 or right == -1:
return [name]
first = name[:left]
results = [first]
comma = name.find(',', left + 1, right)
if comma == -1:
results.append(name[left+1:right].strip())
return results
left += 1
while comma != -1:
lt_count = find_sub_string_count(name, left, comma, '<')
gt_count = find_sub_string_count(name, left, comma, '>')
if lt_count == gt_count:
results.append(name[left:comma].strip())
left = comma + 1
comma = name.find(',', comma + 1, right)
if left < right:
results.append(name[left:right].strip())
name_len = len(name)
if right < name_len - 1:
results.append(name[right+1:].strip())
return results
def normalize_type_name_by_sections(sections):
container_name = sections[0]
suffix = ''
index = len(sections) - 1
while sections[index] == '*' or sections[index] == '&':
suffix += sections[index]
index -= 1
name_for_search = container_name.replace('const ', '').replace('&', '').replace('*', '').strip()
if name_for_search in stl_type_map:
normalized_name = container_name + '<' + ', '.join(sections[1:1+stl_type_map[name_for_search]]) + '>' + suffix
else:
normalized_name = container_name + '<' + ', '.join(sections[1:]) + '>'
return normalized_name
def normalize_std_function_by_sections(sections):
normalized_name = ''
if sections[0] == 'std_function_args':
normalized_name = '(' + ', '.join(sections[1:]) + ')'
elif sections[0] == 'std::function' or sections[0] == 'function':
normalized_name = 'std::function<' + sections[1] + ' ' + sections[2] + '>'
else:
assert(False)
return normalized_name
def normalize_type_str(s, depth=1):
if s.find('std::function') == 0 or s.find('function') == 0:
start = s.find('<')
assert(start > 0)
sections = [s[:start]] # std::function
start += 1
ret_pos = s.find('(', start)
sections.append(s[start:ret_pos].strip()) # return type
end = s.find(')', ret_pos + 1)
sections.append('std_function_args<' + s[ret_pos+1:end].strip() + '>')
else:
sections = split_container_name(s)
section_len = len(sections)
if section_len == 1:
return sections[0]
# for section in sections:
# print('>' * depth + section)
if sections[0] == 'const std::basic_string' or sections[0] == 'const basic_string':
last_section = sections[len(sections) - 1]
if last_section == '&' or last_section == '*' or last_section.startswith('::'):
return 'const std::string' + last_section
else:
return 'const std::string'
elif sections[0] == 'std::basic_string' or sections[0] == 'basic_string':
last_section = sections[len(sections) - 1]
if last_section == '&' or last_section == '*' or last_section.startswith('::'):
return 'std::string' + last_section
else:
return 'std::string'
for i in range(1, section_len):
sections[i] = normalize_type_str(sections[i], depth+1)
if sections[0] == 'std::function' or sections[0] == 'function' or sections[0] == 'std_function_args':
normalized_name = normalize_std_function_by_sections(sections)
else:
normalized_name = normalize_type_name_by_sections(sections)
return normalized_name
class BaseEnumeration(object):
"""
Common base class for named enumerations held in sync with Index.h values.
Subclasses must define their own _kinds and _name_map members, as:
_kinds = []
_name_map = None
These values hold the per-subclass instances and value-to-name mappings,
respectively.
"""
def __init__(self, value):
if value >= len(self.__class__._kinds):
self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1)
if self.__class__._kinds[value] is not None:
raise ValueError('{0} value {1} already loaded'.format(
str(self.__class__), value))
self.value = value
self.__class__._kinds[value] = self
self.__class__._name_map = None
def from_param(self):
return self.value
@property
def name(self):
"""Get the enumeration name of this cursor kind."""
if self._name_map is None:
self._name_map = {}
for key, value in self.__class__.__dict__.items():
if isinstance(value, self.__class__):
self._name_map[value] = key
return self._name_map[self]
@classmethod
def from_id(cls, id):
if id >= len(cls._kinds) or cls._kinds[id] is None:
raise ValueError('Unknown template argument kind %d' % id)
return cls._kinds[id]
def __repr__(self):
return '%s.%s' % (self.__class__, self.name,)
### Availability Kinds ###
class AvailabilityKind(BaseEnumeration):
"""
Describes the availability of an entity.
"""
# The unique kind objects, indexed by id.
_kinds = []
_name_map = None
def __repr__(self):
return 'AvailabilityKind.%s' % (self.name,)
AvailabilityKind.AVAILABLE = AvailabilityKind(0)
AvailabilityKind.DEPRECATED = AvailabilityKind(1)
AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2)
AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3)
def get_availability(cursor):
"""
Retrieves the availability of the entity pointed at by the cursor.
"""
if not hasattr(cursor, '_availability'):
cursor._availability = cindex.conf.lib.clang_getCursorAvailability(cursor)
return AvailabilityKind.from_id(cursor._availability)
def native_name_from_type(ntype, underlying=False):
kind = ntype.kind #get_canonical().kind
const = "" #"const " if ntype.is_const_qualified() else ""
if not underlying and kind == cindex.TypeKind.ENUM:
decl = ntype.get_declaration()
return get_namespaced_name(decl)
elif kind in type_map:
return const + type_map[kind]
elif kind == cindex.TypeKind.RECORD:
# might be an std::string
decl = ntype.get_declaration()
parent = decl.semantic_parent
cdecl = ntype.get_canonical().get_declaration()
cparent = cdecl.semantic_parent
if decl.spelling == "string" and parent and parent.spelling == "std":
return "std::string"
elif cdecl.spelling == "function" and cparent and cparent.spelling == "std":
return "std::function"
else:
# print >> sys.stderr, "probably a function pointer: " + str(decl.spelling)
return const + decl.spelling
else:
# name = ntype.get_declaration().spelling
# print >> sys.stderr, "Unknown type: " + str(kind) + " " + str(name)
return INVALID_NATIVE_TYPE
# pdb.set_trace()
def build_namespace(cursor, namespaces=[]):
'''
build the full namespace for a specific cursor
'''
if cursor:
parent = cursor.semantic_parent
if parent:
if parent.kind == cindex.CursorKind.NAMESPACE or parent.kind == cindex.CursorKind.CLASS_DECL:
namespaces.append(parent.displayname)
build_namespace(parent, namespaces)
return namespaces
def get_namespaced_name(declaration_cursor):
ns_list = build_namespace(declaration_cursor, [])
ns_list.reverse()
ns = "::".join(ns_list)
display_name = declaration_cursor.displayname.replace("::__ndk1", "")
if len(ns) > 0:
ns = ns.replace("::__ndk1", "")
return ns + "::" + display_name
return display_name
def generate_namespace_list(cursor, namespaces=[]):
'''
build the full namespace for a specific cursor
'''
if cursor:
parent = cursor.semantic_parent
if parent:
if parent.kind == cindex.CursorKind.NAMESPACE or parent.kind == cindex.CursorKind.CLASS_DECL:
if parent.kind == cindex.CursorKind.NAMESPACE:
namespaces.append(parent.displayname)
generate_namespace_list(parent, namespaces)
return namespaces
def get_namespace_name(declaration_cursor):
ns_list = generate_namespace_list(declaration_cursor, [])
ns_list.reverse()
ns = "::".join(ns_list)
if len(ns) > 0:
ns = ns.replace("::__ndk1", "")
return ns + "::"
return declaration_cursor.displayname
class NativeType(object):
def __init__(self):
self.is_object = False
self.is_function = False
self.is_enum = False
self.is_numeric = False
self.not_supported = False
self.param_types = []
self.ret_type = None
self.namespaced_name = "" # with namespace and class name
self.namespace_name = "" # only contains namespace
self.name = ""
self.whole_name = None
self.is_const = False
self.is_pointer = False
self.canonical_type = None
@staticmethod
def from_type(ntype):
if ntype.kind == cindex.TypeKind.POINTER:
nt = NativeType.from_type(ntype.get_pointee())
if None != nt.canonical_type:
nt.canonical_type.name += "*"
nt.canonical_type.namespaced_name += "*"
nt.canonical_type.whole_name += "*"
nt.name += "*"
nt.namespaced_name += "*"
nt.whole_name = nt.namespaced_name
nt.is_enum = False
nt.is_const = ntype.get_pointee().is_const_qualified()
nt.is_pointer = True
if nt.is_const:
nt.whole_name = "const " + nt.whole_name
elif ntype.kind == cindex.TypeKind.LVALUEREFERENCE:
nt = NativeType.from_type(ntype.get_pointee())
nt.is_const = ntype.get_pointee().is_const_qualified()
nt.whole_name = nt.namespaced_name + "&"
if nt.is_const:
nt.whole_name = "const " + nt.whole_name
if None != nt.canonical_type:
nt.canonical_type.whole_name += "&"
else:
nt = NativeType()
decl = ntype.get_declaration()
nt.namespaced_name = get_namespaced_name(decl).replace('::__ndk1', '')
if decl.kind == cindex.CursorKind.CLASS_DECL \
and not nt.namespaced_name.startswith('std::function') \
and not nt.namespaced_name.startswith('std::string') \
and not nt.namespaced_name.startswith('std::basic_string'):
nt.is_object = True
displayname = decl.displayname.replace('::__ndk1', '')
nt.name = normalize_type_str(displayname)
nt.namespaced_name = normalize_type_str(nt.namespaced_name)
nt.namespace_name = get_namespace_name(decl)
nt.whole_name = nt.namespaced_name
else:
if decl.kind == cindex.CursorKind.NO_DECL_FOUND:
nt.name = native_name_from_type(ntype)
else:
nt.name = decl.spelling
nt.namespace_name = get_namespace_name(decl)
if len(nt.namespaced_name) > 0:
nt.namespaced_name = normalize_type_str(nt.namespaced_name)
if nt.namespaced_name.startswith("std::function"):
nt.name = "std::function"
if len(nt.namespaced_name) == 0 or nt.namespaced_name.find("::") == -1:
nt.namespaced_name = nt.name
nt.whole_name = nt.namespaced_name
nt.is_const = ntype.is_const_qualified()
if nt.is_const:
nt.whole_name = "const " + nt.whole_name
# Check whether it's a std::function typedef
cdecl = ntype.get_canonical().get_declaration()
if None != cdecl.spelling and 0 == cmp(cdecl.spelling, "function"):
nt.name = "std::function"
if nt.name != INVALID_NATIVE_TYPE and nt.name != "std::string" and nt.name != "std::function":
if ntype.kind == cindex.TypeKind.UNEXPOSED or ntype.kind == cindex.TypeKind.TYPEDEF or ntype.kind == cindex.TypeKind.ELABORATED:
ret = NativeType.from_type(ntype.get_canonical())
if ret.name != "":
if decl.kind == cindex.CursorKind.TYPEDEF_DECL:
ret.canonical_type = nt
return ret
nt.is_enum = ntype.get_canonical().kind == cindex.TypeKind.ENUM
if nt.name == "std::function":
nt.is_object = False
lambda_display_name = get_namespaced_name(cdecl)
lambda_display_name = lambda_display_name.replace("::__ndk1", "")
lambda_display_name = normalize_type_str(lambda_display_name)
nt.namespaced_name = lambda_display_name
r = re.compile('function<([^\s]+).*\((.*)\)>').search(nt.namespaced_name)
(ret_type, params) = r.groups()
params = filter(None, params.split(", "))
nt.is_function = True
nt.ret_type = NativeType.from_string(ret_type)
nt.param_types = [NativeType.from_string(string) for string in params]
# mark argument as not supported
if nt.name == INVALID_NATIVE_TYPE:
nt.not_supported = True
if re.search("(short|int|double|float|long|size_t)$", nt.name) is not None:
nt.is_numeric = True
return nt
@staticmethod
def from_string(displayname):
displayname = displayname.replace(" *", "*")
nt = NativeType()
nt.name = displayname.split("::")[-1]
nt.namespaced_name = displayname
nt.whole_name = nt.namespaced_name
nt.is_object = True
return nt
@property
def lambda_parameters(self):
params = ["%s larg%d" % (str(nt), i) for i, nt in enumerate(self.param_types)]
return ", ".join(params)
@staticmethod
def dict_has_key_re(dict, real_key_list):
for real_key in real_key_list:
for (k, v) in dict.items():
if k.startswith('@'):
k = k[1:]
match = re.match("^" + k + "$", real_key)
if match:
return True
else:
if k == real_key:
return True
return False
@staticmethod
def dict_get_value_re(dict, real_key_list):
for real_key in real_key_list:
for (k, v) in dict.items():
if k.startswith('@'):
k = k[1:]
match = re.match("^" + k + "$", real_key)
if match:
return v
else:
if k == real_key:
return v
return None
@staticmethod
def dict_replace_value_re(dict, real_key_list):
for real_key in real_key_list:
for (k, v) in dict.items():
if k.startswith('@'):
k = k[1:]
match = re.match('.*' + k, real_key)
if match:
return re.sub(k, v, real_key)
else:
if k == real_key:
return v
return None
def from_native(self, convert_opts):
assert(convert_opts.has_key('generator'))
generator = convert_opts['generator']
keys = []
if self.canonical_type != None:
keys.append(self.canonical_type.name)
keys.append(self.name)
from_native_dict = generator.config['conversions']['from_native']
if self.is_object:
if not NativeType.dict_has_key_re(from_native_dict, keys):
keys.append("object")
elif self.is_enum:
keys.append("int")
if NativeType.dict_has_key_re(from_native_dict, keys):
tpl = NativeType.dict_get_value_re(from_native_dict, keys)
tpl = Template(tpl, searchList=[convert_opts])
return str(tpl).rstrip()
return "#pragma warning NO CONVERSION FROM NATIVE FOR " + self.name
def to_native(self, convert_opts):
assert('generator' in convert_opts)
generator = convert_opts['generator']
keys = []
if self.canonical_type != None:
keys.append(self.canonical_type.name)
keys.append(self.name)
to_native_dict = generator.config['conversions']['to_native']
if self.is_object:
if not NativeType.dict_has_key_re(to_native_dict, keys):
keys.append("object")
elif self.is_enum:
keys.append("int")
if self.is_function:
tpl = Template(file=os.path.join(generator.target, "templates", "lambda.c"),
searchList=[convert_opts, self])
indent = convert_opts['level'] * "\t"
return str(tpl).replace("\n", "\n" + indent)
if NativeType.dict_has_key_re(to_native_dict, keys):
tpl = NativeType.dict_get_value_re(to_native_dict, keys)
tpl = Template(tpl, searchList=[convert_opts])
return str(tpl).rstrip()
return "#pragma warning NO CONVERSION TO NATIVE FOR " + self.name + "\n" + convert_opts['level'] * "\t" + "ok = false"
def to_string(self, generator):
conversions = generator.config['conversions']
if conversions.has_key('native_types'):
native_types_dict = conversions['native_types']
if NativeType.dict_has_key_re(native_types_dict, [self.namespaced_name]):
return NativeType.dict_get_value_re(native_types_dict, [self.namespaced_name])
name = self.namespaced_name
to_native_dict = generator.config['conversions']['to_native']
from_native_dict = generator.config['conversions']['from_native']
use_typedef = False
typedef_name = self.canonical_type.name if None != self.canonical_type else None
if None != typedef_name:
if NativeType.dict_has_key_re(to_native_dict, [typedef_name]) or NativeType.dict_has_key_re(from_native_dict, [typedef_name]):
use_typedef = True
if use_typedef and self.canonical_type:
name = self.canonical_type.namespaced_name
return "const " + name if (self.is_pointer and self.is_const) else name
def get_whole_name(self, generator):
conversions = generator.config['conversions']
to_native_dict = conversions['to_native']
from_native_dict = conversions['from_native']
use_typedef = False
name = self.whole_name
typedef_name = self.canonical_type.name if None != self.canonical_type else None
if None != typedef_name:
if NativeType.dict_has_key_re(to_native_dict, [typedef_name]) or NativeType.dict_has_key_re(from_native_dict, [typedef_name]):
use_typedef = True
if use_typedef and self.canonical_type:
name = self.canonical_type.whole_name
to_replace = None
if conversions.has_key('native_types'):
native_types_dict = conversions['native_types']
to_replace = NativeType.dict_replace_value_re(native_types_dict, [name])
if to_replace:
name = to_replace
return name
def object_can_convert(self, generator, is_to_native = True):
if self.is_object:
keys = []
if self.canonical_type != None:
keys.append(self.canonical_type.name)
keys.append(self.name)
if is_to_native:
to_native_dict = generator.config['conversions']['to_native']
if NativeType.dict_has_key_re(to_native_dict, keys):
return True
else:
from_native_dict = generator.config['conversions']['from_native']
if NativeType.dict_has_key_re(from_native_dict, keys):
return True
return False
def __str__(self):
return self.canonical_type.whole_name if None != self.canonical_type else self.whole_name
class NativeField(object):
def __init__(self, cursor):
cursor = cursor.canonical
self.cursor = cursor
self.name = cursor.displayname
self.kind = cursor.type.kind
self.location = cursor.location
member_field_re = re.compile('m_(\w+)')
match = member_field_re.match(self.name)
self.signature_name = self.name
self.ntype = NativeType.from_type(cursor.type)
if match:
self.pretty_name = match.group(1)
else:
self.pretty_name = self.name
@staticmethod
def can_parse(ntype):
native_type = NativeType.from_type(ntype)
if ntype.kind == cindex.TypeKind.UNEXPOSED and native_type.name != "std::string":
return False
return True
def generate_code(self, current_class = None, generator = None):
gen = current_class.generator if current_class else generator
config = gen.config
if config['definitions'].has_key('public_field'):
tpl = Template(config['definitions']['public_field'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "public_field.c"),
searchList=[current_class, self])
gen.impl_file.write(str(tpl))
# return True if found default argument.
def iterate_param_node(param_node, depth=1):
for node in param_node.get_children():
# print(">"*depth+" "+str(node.kind))
if node.kind in default_arg_type_arr:
return True
if iterate_param_node(node, depth + 1):
return True
return False
class NativeFunction(object):
def __init__(self, cursor):
self.cursor = cursor
self.func_name = cursor.spelling
self.signature_name = self.func_name
self.arguments = []
self.argumtntTips = []
self.static = cursor.kind == cindex.CursorKind.CXX_METHOD and cursor.is_static_method()
self.implementations = []
self.is_overloaded = False
self.is_constructor = False
self.not_supported = False
self.is_override = False
self.ret_type = NativeType.from_type(cursor.result_type)
self.comment = self.get_comment(cursor.raw_comment)
# parse the arguments
# if self.func_name == "spriteWithFile":
# pdb.set_trace()
for arg in cursor.get_arguments():
self.argumtntTips.append(arg.spelling)
for arg in cursor.type.argument_types():
nt = NativeType.from_type(arg)
self.arguments.append(nt)
# mark the function as not supported if at least one argument is not supported
if nt.not_supported:
self.not_supported = True
found_default_arg = False
index = -1
for arg_node in self.cursor.get_children():
if arg_node.kind == cindex.CursorKind.CXX_OVERRIDE_ATTR:
self.is_override = True
if arg_node.kind == cindex.CursorKind.PARM_DECL:
index += 1
if iterate_param_node(arg_node):
found_default_arg = True
break
self.min_args = index if found_default_arg else len(self.arguments)
def get_comment(self, comment):
replaceStr = comment
if comment is None:
return ""
regular_replace_list = [
("(\s)*//!",""),
("(\s)*//",""),
("(\s)*/\*\*",""),
("(\s)*/\*",""),
("\*/",""),
("\r\n", "\n"),
("\n(\s)*\*", "\n"),
("\n(\s)*@","\n"),
("\n(\s)*","\n"),
("\n(\s)*\n", "\n"),
("^(\s)*\n",""),
("\n(\s)*$", ""),
("\n","<br>\n"),
("\n", "\n-- ")
]
for item in regular_replace_list:
replaceStr = re.sub(item[0], item[1], replaceStr)
return replaceStr
def generate_code(self, current_class=None, generator=None, is_override=False, is_ctor=False):
self.is_ctor = is_ctor
gen = current_class.generator if current_class else generator
config = gen.config
if not is_ctor:
tpl = Template(file=os.path.join(gen.target, "templates", "function.h"),
searchList=[current_class, self])
if not is_override:
gen.head_file.write(str(tpl))
if self.static:
if config['definitions'].has_key('sfunction'):
tpl = Template(config['definitions']['sfunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "sfunction.c"),
searchList=[current_class, self])
else:
if not self.is_constructor:
if config['definitions'].has_key('ifunction'):
tpl = Template(config['definitions']['ifunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
else:
if config['definitions'].has_key('constructor'):
if not is_ctor:
tpl = Template(config['definitions']['constructor'],
searchList=[current_class, self])
else:
tpl = Template(config['definitions']['ctor'],
searchList=[current_class, self])
self.signature_name = str(tpl)
if self.is_constructor and gen.script_type == "spidermonkey" :
if not is_ctor:
tpl = Template(file=os.path.join(gen.target, "templates", "constructor.c"),
searchList=[current_class, self])
else:
tpl = Template(file=os.path.join(gen.target, "templates", "ctor.c"),
searchList=[current_class, self])
else :
tpl = Template(file=os.path.join(gen.target, "templates", "ifunction.c"),
searchList=[current_class, self])
if not is_override:
gen.impl_file.write(str(tpl))
# if not is_ctor:
# apidoc_function_script = Template(file=os.path.join(gen.target,
# "templates",
# "apidoc_function.script"),
# searchList=[current_class, self])
# if gen.script_type == "spidermonkey":
# gen.doc_file.write(str(apidoc_function_script))
# else:
# if gen.script_type == "lua" and current_class != None :
# current_class.doc_func_file.write(str(apidoc_function_script))
class NativeOverloadedFunction(object):
def __init__(self, func_array):
self.implementations = func_array
self.func_name = func_array[0].func_name
self.signature_name = self.func_name
self.min_args = 100
self.is_constructor = False
self.is_overloaded = True
self.is_ctor = False
for m in func_array:
self.min_args = min(self.min_args, m.min_args)
self.comment = self.get_comment(func_array[0].cursor.raw_comment)
def get_comment(self, comment):
replaceStr = comment
if comment is None:
return ""
regular_replace_list = [
("(\s)*//!",""),
("(\s)*//",""),
("(\s)*/\*\*",""),
("(\s)*/\*",""),
("\*/",""),
("\r\n", "\n"),
("\n(\s)*\*", "\n"),
("\n(\s)*@","\n"),
("\n(\s)*","\n"),
("\n(\s)*\n", "\n"),
("^(\s)*\n",""),
("\n(\s)*$", ""),
("\n","<br>\n"),
("\n", "\n-- ")
]
for item in regular_replace_list:
replaceStr = re.sub(item[0], item[1], replaceStr)
return replaceStr
def append(self, func):
self.min_args = min(self.min_args, func.min_args)
self.implementations.append(func)
def generate_code(self, current_class=None, is_override=False, is_ctor=False):
self.is_ctor = is_ctor
gen = current_class.generator
config = gen.config
static = self.implementations[0].static
if not is_ctor:
tpl = Template(file=os.path.join(gen.target, "templates", "function.h"),
searchList=[current_class, self])
if not is_override:
gen.head_file.write(str(tpl))
if static:
if config['definitions'].has_key('sfunction'):
tpl = Template(config['definitions']['sfunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "sfunction_overloaded.c"),
searchList=[current_class, self])
else:
if not self.is_constructor:
if config['definitions'].has_key('ifunction'):
tpl = Template(config['definitions']['ifunction'],
searchList=[current_class, self])
self.signature_name = str(tpl)
else:
if config['definitions'].has_key('constructor'):
if not is_ctor:
tpl = Template(config['definitions']['constructor'],
searchList=[current_class, self])
else:
tpl = Template(config['definitions']['ctor'],
searchList=[current_class, self])
self.signature_name = str(tpl)
tpl = Template(file=os.path.join(gen.target, "templates", "ifunction_overloaded.c"),
searchList=[current_class, self])
if not is_override:
gen.impl_file.write(str(tpl))
# if current_class != None and not is_ctor:
# if gen.script_type == "lua":
# apidoc_function_overload_script = Template(file=os.path.join(gen.target,
# "templates",
# "apidoc_function_overload.script"),
# searchList=[current_class, self])
# current_class.doc_func_file.write(str(apidoc_function_overload_script))
# else:
# if gen.script_type == "spidermonkey":
# apidoc_function_overload_script = Template(file=os.path.join(gen.target,
# "templates",
# "apidoc_function_overload.script"),
# searchList=[current_class, self])
# gen.doc_file.write(str(apidoc_function_overload_script))
class NativeClass(object):
def __init__(self, cursor, generator):
# the cursor to the implementation
self.cursor = cursor
self.class_name = cursor.displayname
self.is_ref_class = self.class_name == "Ref"
self.namespaced_class_name = self.class_name
self.parents = []
self.fields = []
self.public_fields = []
self.methods = {}
self.static_methods = {}
self.generator = generator
self.is_abstract = self.class_name in generator.abstract_classes
self._current_visibility = cindex.AccessSpecifier.PRIVATE
#for generate lua api doc
self.override_methods = {}
self.has_constructor = False
self.namespace_name = ""
registration_name = generator.get_class_or_rename_class(self.class_name)
if generator.remove_prefix:
self.target_class_name = re.sub('^' + generator.remove_prefix, '', registration_name)
else:
self.target_class_name = registration_name
self.namespaced_class_name = get_namespaced_name(cursor)
self.namespace_name = get_namespace_name(cursor)
self.parse()
@property
def underlined_class_name(self):
return self.namespaced_class_name.replace("::", "_")
def parse(self):
'''
parse the current cursor, getting all the necesary information
'''
self._deep_iterate(self.cursor)
def methods_clean(self):
'''
clean list of methods (without the ones that should be skipped)
'''
ret = []
for name, impl in self.methods.iteritems():
should_skip = False