-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathgen.py
1662 lines (1233 loc) · 51 KB
/
gen.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
# FABGen - The FABulous binding Generator for CPython and Lua
# Copyright (C) 2018 Emmanuel Julien
from pypeg2 import re, flag, name, Plain, optional, attr, K, parse, Keyword, Enum, List, csl, some, maybe_some
from collections import OrderedDict
import zlib
import copy
#
api_prefix = 'gen'
def apply_api_prefix(symbol):
return '%s_%s' % (api_prefix, symbol) if api_prefix else symbol
def get_fabgen_api():
return '''\
// FABgen .h
#pragma once
enum OwnershipPolicy { NonOwning, Copy, Owning };
'''
#
def get_fully_qualified_function_signature(func):
out = ''
if hasattr(func, 'void_rval'):
out += 'void'
else:
out += str(func.rval)
if hasattr(func, 'args'):
args = [str(arg) for arg in func.args]
out += '(%s)' % ', '.join(args)
else:
out += '()'
return out
def get_fully_qualified_ctype_name(ctype):
parts = []
if ctype.const:
parts.append('const')
if ctype.signed:
parts.append('signed')
if ctype.unsigned:
parts.append('unsigned')
if hasattr(ctype, 'template'):
if hasattr(ctype.template, 'args'):
parts.append(ctype.name + '<%s>' % ', '.join([str(arg) for arg in ctype.template.args]))
elif hasattr(ctype.template, 'function'):
parts.append(ctype.name + '<%s>' % get_fully_qualified_function_signature(ctype.template.function))
else:
parts.append(repr(ctype.scoped_typename))
if ctype.const_ref:
parts.append('const')
if hasattr(ctype, 'ref'):
parts.append(ctype.ref)
return ' '.join(parts)
def ref_to_string(ref):
parts = []
for e in ref:
if ref == '*':
parts.append('ptr')
elif ref == '&':
parts.append('ref')
return '_'.join(parts)
def ctype_to_plain_string(ctype):
parts = []
if ctype.const:
parts.append('const')
if ctype.signed:
parts.append('signed')
if ctype.unsigned:
parts.append('unsigned')
_ctype = ctype.scoped_typename.parts[-1] # ignore namespace entries (only consider last type in chain)
_name = _ctype.name.replace('::', '_').replace(':', '_')
parts.append(_name)
if hasattr(_ctype, 'template'):
if hasattr(_ctype.template, 'function'):
function = _ctype.template.function
parts.append('returning')
if hasattr(function, 'void_rval'):
parts.append('void')
else:
parts.append(ctype_to_plain_string(function.rval))
if hasattr(function, 'args'):
parts.append('taking')
for arg in function.args:
parts.append(ctype_to_plain_string(arg))
else:
parts.append('of_' + '_and_'.join([ctype_to_plain_string(arg) for arg in _ctype.template.args]))
if ctype.const_ref:
parts.append('const')
if hasattr(ctype, 'ref'):
parts.append(ref_to_string(ctype.ref))
return '_'.join(parts)
def get_ctype_default_bound_name(ctype):
ctype = copy.deepcopy(ctype)
ctype.scoped_typename.explicit_global = False
return ctype_to_plain_string(ctype)
#
symbol_clean_rules = OrderedDict()
symbol_clean_rules['::'] = '__' # namespace
symbol_clean_rules['+='] = 'inplace_add'
symbol_clean_rules['*='] = 'inplace_mul'
symbol_clean_rules['/='] = 'inplace_div'
symbol_clean_rules['-='] = 'inplace_sub'
symbol_clean_rules['+'] = 'add'
symbol_clean_rules['*'] = 'mul'
symbol_clean_rules['/'] = 'div'
symbol_clean_rules['-'] = 'sub'
symbol_clean_rules['||'] = 'logicor'
symbol_clean_rules['&&'] = 'logicand'
symbol_clean_rules['|'] = 'pipe'
symbol_clean_rules['&'] = 'and'
symbol_clean_rules['<'] = 'lt'
symbol_clean_rules['<='] = 'le'
symbol_clean_rules['=='] = 'eq'
symbol_clean_rules['!='] = 'ne'
symbol_clean_rules['>'] = 'gt'
symbol_clean_rules['>='] = 'ge'
def strip_namespace(name):
parts = name.split('::')
return parts[-1] if len(parts) > 1 else name
def get_clean_symbol_name(name):
""" Return a string cleaned so that it may be used as a valid symbol name in the generator output."""
parts = name.split(' ')
def clean_symbol_name_part(part):
for f_o, f_d in symbol_clean_rules.items():
part = part.replace(f_o, f_d)
return part
parts = [clean_symbol_name_part(part) for part in parts]
return '_'.join(parts)
def get_symbol_default_bound_name(name):
if isinstance(name, str): # no namespace
name = strip_namespace(name)
else:
name = name.naked_name()
return get_clean_symbol_name(name)
def clean_name_with_title(name):
new_name = ""
if "_" in name:
# redo a special string.title()
next_is_forced_uppercase = True
for c in name:
if c in ["*", "&"]:
new_name += c
elif c in ["_", "-"]:
next_is_forced_uppercase = True
else:
if next_is_forced_uppercase:
next_is_forced_uppercase = False
new_name += c.capitalize()
else:
new_name += c
else:
# make sur the first letter is captialize
first_letter_checked = False
for c in name:
if c in ["*", "&"] or first_letter_checked:
new_name += c
elif not first_letter_checked:
first_letter_checked = True
new_name += c.capitalize()
return new_name.strip().replace("_", "").replace(":", "")
#
typename = re.compile(r"(_|[A-z])[A-z0-9_]*")
ref_re = re.compile(r"[&*]+")
#
class _CType:
def __repr__(self):
return get_fully_qualified_ctype_name(self)
def get_ref(self):
return (self.ref if hasattr(self, 'ref') else '')
def add_ref(self, ref):
t = copy.deepcopy(self)
if hasattr(self, 'ref'):
t.ref += ref
else:
setattr(t, 'ref', ref)
return t
def is_pointer(self):
return self.get_ref() == '*'
def is_const(self):
if self.get_ref() == '':
return self.const
return self.const_ref
def non_const(self):
t = copy.deepcopy(self)
t.const = False
return t
def dereference_once(self):
t = copy.deepcopy(self)
if hasattr(t, 'ref'):
t.ref = t.ref[:-1]
if t.ref == '':
delattr(t, 'ref')
return t
def ref_stripped(self): # pragma: no cover
t = copy.deepcopy(self)
if hasattr(t, 'ref'):
delattr(t, 'ref')
return t
class _FunctionSignature:
grammar = [attr("void_rval", "void"), attr("rval", _CType)], "(", optional(attr("args", csl(_CType))), ")"
def __repr__(self):
return get_fully_qualified_function_signature(self)
class _TemplateParameters:
grammar = "<", [attr("function", _FunctionSignature), attr("args", csl(_CType))], ">"
def __repr__(self):
if hasattr(self, "function"):
args = [repr(self.function)]
else:
args = [repr(arg) for arg in self.args]
return '<' + ','.join(args) + '>'
class _Typename:
grammar = attr("name", typename), optional(attr("template", _TemplateParameters))
def __repr__(self):
out = self.name
if hasattr(self, 'template'):
out += repr(self.template)
return out
class _ScopedTypename:
grammar = flag("explicit_global", K("::")), attr("parts", csl(_Typename, separator="::"))
def naked_name(self):
return self.parts[-1].name
def __eq__(self, other):
return repr(self) == repr(other)
def __repr__(self):
out = ''
if self.explicit_global:
out += '::'
parts = []
for part in self.parts:
parts.append(repr(part))
out += '::'.join(parts)
return out
_CType.grammar = flag("const"), flag("signed"), flag("unsigned"), attr("scoped_typename", _ScopedTypename), optional(attr("ref", ref_re)), flag("const_ref", K("const"))
#
class _NamedCType:
grammar = attr("ctype", _CType), attr("name", _ScopedTypename)
def __repr__(self): # pragma: no cover
return ' '.join([repr(self.ctype), self.name.naked_name()])
#
def ctype_ref_to(src_ref, dst_ref):
i = 0
while i < len(src_ref) and i < len(dst_ref):
if src_ref[i] != dst_ref[i]:
break
i += 1
src_ref = src_ref[i:]
dst_ref = dst_ref[i:]
if src_ref == '&':
if dst_ref == '&':
return '' # ref to ref
elif dst_ref == '*':
return '&' # ref to ptr
else:
return '' # ref to value
elif src_ref == '*':
if dst_ref == '&':
return '*' # ptr to ref
elif dst_ref == '*':
return '' # ptr to ptr
else:
return '*' # ptr to value
else:
if dst_ref == '&':
return '' # value to ref
elif dst_ref == '*':
return '&' # value to ptr
else:
return '' # value to value
def transform_var_ref_to(var, from_ref, to_ref):
if isinstance(var, _ScopedTypename):
var = var.naked_name()
return ctype_ref_to(from_ref, to_ref) + var
def add_list_unique(lst, val, dlg):
for ent in lst:
if dlg(val, ent):
return
lst.append(val)
def collect_attr_from_conv_recursive(out, conv, attr, dlg):
for entry in getattr(conv, attr):
add_list_unique(out, entry, dlg)
for base in conv._bases:
collect_attr_from_conv_recursive(out, base, attr, dlg)
return out
class TypeConverter:
def __init__(self, type, to_c_storage_type=None, bound_name=None, from_c_storage_type=None, needs_c_storage_class=False):
self.ctype = parse(type, _CType)
self.to_c_storage_ctype = parse(to_c_storage_type, _CType) if to_c_storage_type is not None else self.ctype.non_const()
self.bound_name = get_ctype_default_bound_name(self.ctype) if bound_name is None else bound_name
self.from_c_storage_ctype = parse(from_c_storage_type, _CType) if from_c_storage_type is not None else None # if None the prototype return value type will be used to determine adequate storage at binding time
if needs_c_storage_class:
self.c_storage_class = 'storage_%s' % self.bound_name
else:
self.c_storage_class = None
self.type_tag = 'type_tag_' + self.bound_name
self.constructor = None
self.members = []
self.static_members = []
self.methods = []
self.static_methods = []
self.arithmetic_ops = []
self.comparison_ops = []
self._non_copyable = False
self._moveable = False
self._inline = False
self._supports_deep_compare = False
self._is_pointer = False
self._features = {}
self._casts = [] # valid casts
self._bases = [] # bases
self.nobind = False
self.check_func = apply_api_prefix('check_%s' % self.bound_name)
self.to_c_func = apply_api_prefix('to_c_%s' % self.bound_name)
self.from_c_func = apply_api_prefix('from_c_%s' % self.bound_name)
def is_type_class(self):
return False
def get_operator(self, op):
for arithmetic_op in self.arithmetic_ops:
if arithmetic_op['op'] == op:
return arithmetic_op
def get_type_api(self, module_name):
return ''
def finalize_type(self):
return ''
def to_c_call(self, out_var, expr):
assert 'not implemented in this converter' # pragma: no cover
def from_c_call(self, out_var, expr, ownership):
assert 'not implemented in this converter' # pragma: no cover
def prepare_var_for_conv(self, var, input_ref):
"""Transform a variable for use with the converter from_c/to_c methods."""
return transform_var_ref_to(var, input_ref, self.to_c_storage_ctype.get_ref())
def prepare_var_from_conv(self, var, target_ref):
"""Transform a converted variable back to its ctype reference."""
return transform_var_ref_to(var, self.to_c_storage_ctype.get_ref(), target_ref)
def get_all_members(self):
return collect_attr_from_conv_recursive([], self, 'members', lambda a,b: a['name'] == b['name'])
def get_all_static_members(self):
return collect_attr_from_conv_recursive([], self, 'static_members', lambda a,b: a['name'] == b['name'])
def get_all_methods(self):
return collect_attr_from_conv_recursive([], self, 'methods', lambda a,b: a['bound_name'] == b['bound_name'])
def get_all_static_methods(self):
return collect_attr_from_conv_recursive([], self, 'static_methods', lambda a,b: a['bound_name'] == b['bound_name'])
def add_feature(self, key, val):
self._features[key] = val
def format_list_for_comment(lst):
ln = len(lst)
if ln == 0:
return ''
if ln == 1:
return lst[0]
if ln == 2:
return '%s or %s' % (lst[0], lst[1])
return ', '.join(lst[:-1]) + ' or ' + lst[-1]
#
class FABGen:
def __init__(self):
self.verbose = True
self.embedded = False
self.check_self_type_in_ops = False
self.defines = []
def apply_api_prefix(self, symbol):
return apply_api_prefix(symbol)
def get_language(self):
assert 'not implemented in this generator' # pragma: no cover
def parse_ctype(self, type):
return parse(type, _CType)
def parse_named_ctype(self, type):
type = type.replace('* *', '**')
return parse(type, _NamedCType)
def ctype_to_plain_string(self, ctype):
return ctype_to_plain_string(ctype)
get_symbol_doc_hook = lambda gen, name: ""
def get_symbol_doc(self, name):
return self.get_symbol_doc_hook(name)
def output_header(self):
common = "// This file is automatically generated, do not modify manually!\n\n"
self._source += "// FABgen output .cpp\n"
self._source += common
self._source += '#include "fabgen.h"\n\n'
self._header += '// FABgen output .h\n'
self._header += common
self._header += '#pragma once\n\n'
self._header += '#include <cstdint>\n\n'
self._header += '#include <cstddef>\n\n'
def output_includes(self):
self.add_include('cstdint', True)
self.add_include('cassert', True)
self.add_include('map', True)
self._source += '{{{__WRAPPER_INCLUDES__}}}\n'
def start(self, name):
self._name = name
self._header, self._source = "", ""
self.__system_includes, self.__user_includes = [], []
self.__type_convs = {}
self.__function_declarations = {}
self._bound_types = [] # list of bound types
self._bound_functions = [] # list of bound functions
self._bound_variables = [] # list of bound variables
self._enums = {} # list of bound enumerations
self._extern_types = [] # list of extern types
self._custom_init_code = ""
self._custom_free_code = ""
self.output_header()
self.output_includes()
self._source += 'static bool _type_tag_can_cast(uint32_t in_type_tag, uint32_t out_type_tag);\n'
self._source += 'static void *_type_tag_cast(void *in_T0, uint32_t in_type_tag, uint32_t out_type_tag);\n\n'
def add_include(self, path, is_system=False):
if is_system:
if path not in self.__system_includes:
self.__system_includes.append(path)
else:
if path not in self.__user_includes:
self.__user_includes.append(path)
def insert_code(self, code, in_source=True, in_header=True):
if in_header:
self._header += code
if in_source:
self._source += code
def insert_binding_code(self, code, comment=None):
parts = []
if comment is not None:
parts.append('// %s\n' % comment)
parts.append(code)
parts.append('\n')
self._source += ''.join(parts)
def add_custom_init_code(self, code):
self._custom_init_code += code
def add_custom_free_code(self, code):
self._custom_free_code += code
#
def defined(self, symbol):
return symbol in self.defines
#
def begin_type(self, conv, features, nobind=False):
"""Declare a new type converter."""
if self.verbose:
print('Binding type %s (%s)' % (conv.bound_name, conv.ctype))
self._header += conv.get_type_api(self._name)
self._source += '// %s type tag\n' % conv.ctype
self._source += 'static uint32_t %s = %s;\n\n' % (conv.type_tag, hex(zlib.crc32(conv.bound_name.encode()) & 0xffffffff))
self._source += conv.get_type_api(self._name)
conv.nobind = nobind
conv._features = copy.deepcopy(features)
self._bound_types.append(conv)
self.__type_convs[repr(conv.ctype)] = conv
feats = list(conv._features.values())
for feat in feats:
if hasattr(feat, 'init_type_converter'):
feat.init_type_converter(self, conv) # init converter feature
return conv
def end_type(self, conv):
type_glue = conv.get_type_glue(self, self._name)
self._source += type_glue + '\n'
def bind_type(self, conv, features={}):
self.begin_type(conv, features)
self.end_type(conv)
return conv
#
def typedef(self, type, alias_of, to_c_storage_type=None, bound_name=None):
conv = copy.deepcopy(self.__type_convs[alias_of])
default_arg_storage_type = type if to_c_storage_type is None else to_c_storage_type
if bound_name is not None:
conv.bound_name=bound_name
conv.ctype = parse(type, _CType)
conv.to_c_storage_ctype = parse(default_arg_storage_type, _CType)
self.__type_convs[type] = conv
#
def bind_named_enum(self, name, symbols, storage_type='int', bound_name=None, prefix='', namespace=None):
if bound_name is None:
bound_name = get_symbol_default_bound_name(name)
self.typedef(name, storage_type, bound_name=bound_name)
if namespace is None:
namespace = name
enum = {}
for symbol in symbols:
enum[prefix + symbol] = '%s::%s' % (namespace, symbol)
self._enums[bound_name] = enum
#
def begin_class(self, type, converter_class=None, noncopyable=False, moveable=False, bound_name=None, features={}, nobind=False):
"""Begin a class declaration."""
if type in self.__type_convs:
return self.__type_convs[type] # type already declared
default_storage_type = type + '*'
conv = self.default_class_converter(type, default_storage_type, bound_name) if converter_class is None else converter_class(type, default_storage_type, bound_name)
conv = self.begin_type(conv, features, nobind)
conv._non_copyable = noncopyable
conv._moveable = moveable
return conv
def end_class(self, conv):
"""End a class declaration."""
self.end_type(conv)
#
def bind_extern_type(self, type, bound_name=None, module=None):
"""Bind an external type."""
if type in self.__type_convs:
return self.__type_convs[type] # type already declared
default_storage_type = type + '*'
conv = self.default_extern_converter(type, default_storage_type, bound_name, module)
if self.verbose:
print('Binding extern type %s (%s)' % (conv.bound_name, conv.ctype))
self._header += conv.get_type_api(self._name)
self._source += conv.get_type_api(self._name)
self._extern_types.append(conv)
self.__type_convs[repr(conv.ctype)] = conv
self._source += conv.get_type_glue(self, self._name) + '\n'
return conv
#
def bind_ptr(self, type, converter_class=None, bound_name=None, features={}):
if type in self.__type_convs:
return self.__type_convs[type] # type already declared
conv = self.default_ptr_converter(type, None, bound_name) if converter_class is None else converter_class(type, None, bound_name)
self.bind_type(conv, features)
return conv
#
def add_cast(self, src_conv, tgt_conv, cast_delegate):
"""Declare a cast delegate from one type to another."""
src_conv._casts.append((tgt_conv, cast_delegate))
#
def __add_upcast(self, conv, base):
self.add_cast(conv, base, lambda in_var, out_var: '%s = (%s *)((%s *)%s);\n' % (out_var, base.ctype, conv.ctype, in_var))
for base_of_base in base._bases:
self.__add_upcast(conv, base_of_base)
def add_base(self, conv, base):
self.__add_upcast(conv, base)
conv._bases.append(base)
def add_bases(self, conv, bases):
for base in bases:
self.add_base(conv, base)
#
def select_ctype_conv(self, ctype):
"""Select a type converter."""
if repr(ctype) == 'void':
return None
while True:
type = repr(ctype)
if type in self.__type_convs:
return self.__type_convs[type]
type = repr(ctype.non_const())
if type in self.__type_convs:
return self.__type_convs[type]
if ctype.get_ref() == '':
break
ctype = ctype.dereference_once()
raise Exception("Unknown type %s (no converter available)" % ctype)
def get_conv(self, type):
return self.__type_convs[type]
#
def decl_var(self, ctype, name, eol=';\n'):
return '%s %s%s' % (get_fully_qualified_ctype_name(ctype), name, eol)
#
def select_args_convs(self, args):
return [{'conv': self.select_ctype_conv(arg.ctype), 'ctype': arg.ctype} for i, arg in enumerate(args)]
#
def commit_from_c_vars(self, rval, ctx):
assert 'not implemented in this generator' # pragma: no cover
def rval_assign_arg_in_out(self, out_var, arg_in_out):
assert 'not implemented in this generator' # pragma: no cover
#
def proxy_call_error(self, msg, ctx):
assert 'not implemented in this generator' # pragma: no cover
#
def __ctype_to_ownership_policy(self, ctype):
return 'Copy' if ctype.get_ref() == '' else 'NonOwning'
# --
def __expand_protos(self, protos):
_protos = []
for proto in protos:
_proto = (proto[0], [], proto[2])
for arg in proto[1]:
if arg.startswith('?'):
_protos.append(_proto)
_proto = copy.deepcopy(_proto)
arg = arg[1:]
_proto[1].append(arg)
_protos.append(_proto)
return _protos
def __prepare_protos(self, protos):
"""Prepare a list of prototypes, select converter objects"""
_protos = []
for proto in protos:
assert len(proto) == 3, "prototype incomplete. Expected 3 entries (type, [arguments], [features]), found %d" % len(proto)
rval_type, args, features = proto
rval_ctype = parse(rval_type, _CType)
rval_conv = self.select_ctype_conv(rval_ctype)
if rval_conv is not None and rval_conv.from_c_storage_ctype is not None:
from_c_storage_ctype = rval_conv.from_c_storage_ctype
else:
from_c_storage_ctype = rval_ctype # prepare the return value variable CType
if from_c_storage_ctype.get_ref() == '':
from_c_storage_ctype = from_c_storage_ctype.non_const()
_proto = {'rval': {'storage_ctype': from_c_storage_ctype, 'conv': rval_conv}, 'args': [], 'argsin': [], 'features': features}
if not type(args) is type([]):
args = [args]
for arg in args:
carg = self.parse_named_ctype(arg)
conv = self.select_ctype_conv(carg.ctype)
_proto['args'].append({'carg': carg, 'conv': conv, 'check_var': None})
# prepare argsin, a list of arguments that should be provided by the caller
_proto['argsin'] = _proto['args'] # default to the full arg list
if 'arg_out' in features: # exclude output arguments from the argsin list
_proto['argsin'] = [arg for arg in _proto['args'] if arg['carg'].name.naked_name() not in _proto['features']['arg_out']]
_protos.append(_proto)
# compute suggested_suffix if language doesn't support overload
if len(_protos) > 1:
# get the base one, usually the first one with the less args
id_base = 0
proto_base = _protos[id_base]
for id, proto in enumerate(_protos[1:]):
if len(proto["args"]) < len(proto_base["args"]):
proto_base = proto
id_base = id + 1
suggested_suffixes = []
for id, proto in enumerate(_protos):
if id == id_base:
continue
# check members difference
def get_suggested_suffix(with_type = False):
suggested_suffix = ""
for i, arg in enumerate(proto["args"]):
if i >= len(proto_base["args"]) or proto_base["args"][i]["carg"].name != arg["carg"].name or str(proto_base["args"][i]["carg"].ctype) != str(arg["carg"].ctype):
if suggested_suffix == "":
suggested_suffix = "With"
if with_type:
if arg["conv"].bound_name is not None:
suggested_suffix += clean_name_with_title(str(arg["conv"].bound_name))
else:
suggested_suffix += clean_name_with_title(str(arg['carg'].ctype))
if suggested_suffix.endswith("_nobind") and arg["conv"].nobind:
suggested_suffix = suggested_suffix[:-len("_nobind")]
suggested_suffix += clean_name_with_title(str(arg["carg"].name))
return suggested_suffix
suggested_suffix = get_suggested_suffix()
# check if this suffix already exists
if suggested_suffix in suggested_suffixes:
# recheck the suggested suffix, but with the type
suggested_suffix = get_suggested_suffix(True)
suggested_suffixes.append(suggested_suffix)
proto["suggested_suffix"] = suggested_suffix
return _protos
def __assert_conv_feature(self, conv, feature):
assert feature in conv._features, "Type converter for %s does not support the %s feature" % (conv.ctype, feature)
#
def _prepare_to_c_self(self, conv, out_var, ctx='none', features=[]):
out = ''
if 'proxy' in features:
proxy = conv._features['proxy']
out += ' ' + self.decl_var(conv.to_c_storage_ctype, '%s_wrapped' % out_var)
out += ' ' + conv.to_c_call(self.get_self(ctx), '&%s_wrapped' % out_var)
out += ' ' + self.decl_var(proxy.wrapped_conv.to_c_storage_ctype, out_var)
out += proxy.unwrap('%s_wrapped' % out_var, out_var)
else:
out += ' ' + self.decl_var(conv.to_c_storage_ctype, out_var)
out += ' ' + conv.to_c_call(self.get_self(ctx), '&%s' % out_var)
return out
def _declare_to_c_var(self, ctype, var):
return self.decl_var(ctype, var)
def _convert_to_c_var(self, idx, conv, var, ctx='default', features=[]):
out = conv.to_c_call(self.get_var(idx, ctx), '&%s' % var)
if 'validate_arg_in' in features:
validator = features['validate_arg_in'][idx]
if validator is not None:
out += validator(self, var, ctx)
return out
def prepare_to_c_var(self, idx, conv, var, ctx='default', features=[]):
return self._declare_to_c_var(conv.to_c_storage_ctype, var) + self._convert_to_c_var(idx, conv, var, ctx, features)
#
def declare_from_c_var(self, out_var):
return ''
def prepare_from_c_var(self, rval):
if rval['ownership'] is None:
rval['ownership'] = self.__ctype_to_ownership_policy(rval['ctype'])
# transform from {T&, T*, T**, ...} to T* where T is conv.ctype
expr = transform_var_ref_to(rval['var'], rval['ctype'].get_ref(), rval['conv'].ctype.add_ref('*').get_ref())
out_var = (rval['var'] if isinstance(rval['var'], str) else rval['var'].naked_name()) + '_out'
src = self.declare_from_c_var(out_var)
if 'rval_transform' in rval['conv']._features:
src += rval['conv']._features['rval_transform'](self, rval['conv'], expr, out_var, rval['ownership'])
else:
check_is_valid_pointer = rval['ctype'].is_pointer() or rval['conv']._is_pointer
if check_is_valid_pointer:
src += 'if (!%s) {\n' % rval['var']
src += self.rval_from_nullptr(out_var)
src += '} else {\n'
if rval['conv'].is_type_class() and rval['is_arg_in_out']: # if an object is used as arg_out then reuse the input argument directly
src += self.rval_assign_arg_in_out(out_var, self.get_var(rval['arg_idx'], rval['ctx']))
else:
src += self.rval_from_c_ptr(rval['conv'], out_var, expr, rval['ownership'])
if check_is_valid_pointer:
src += '}\n'
return src
#
def _proto_call(self, self_conv, proto, expr_eval, ctx, fixed_arg_count=None):
parts = []
features = proto['features']
enable_proxy = 'proxy' in features
if enable_proxy:
assert ctx != 'function', "Proxy feature cannot be used for a function call"
if self_conv is not None:
self.__assert_conv_feature(self_conv, 'proxy')
# prepare C call self argument
if self_conv:
if ctx in ['getter', 'setter', 'method', 'arithmetic_op', 'inplace_arithmetic_op', 'comparison_op']:
parts.append(self._prepare_to_c_self(self_conv, '_self', ctx, features))
# prepare C call arguments
args = proto['args']
arg_out = features['arg_out'] if 'arg_out' in features else None
c_call_args = []
argin_idx = 0
for idx, arg in enumerate(args):
conv = arg['conv']
var = 'arg%d' % idx
if arg_out is not None and arg['carg'].name.naked_name() in arg_out:
arg_ctype = conv.ctype
parts.append(self._declare_to_c_var(arg_ctype, var))
else:
arg_ctype = conv.to_c_storage_ctype
parts.append(self._declare_to_c_var(conv.to_c_storage_ctype, var))
parts.append(self._convert_to_c_var(argin_idx, conv, var, ctx, features))
argin_idx += 1
c_call_args.append(transform_var_ref_to(var, arg_ctype.get_ref(), arg['carg'].ctype.get_ref()))
if 'arg_in_out' in features: # add in_out vars to the arg_out list
if arg_out is None:
arg_out = []
arg_out = arg_out + features['arg_in_out']
# c++ exception support
if 'exception' in features:
parts.append('try {\n')
# declare return value
rvals = []
rvals_prepare_args = []
if ctx == 'constructor':
rval_conv = proto['rval']['conv']
from_c_storage_ctype = proto['rval']['storage_ctype'].add_ref('*') # constructor returns a pointer
ownership = 'Owning' # constructor output is always owned by the VM
if enable_proxy:
proxy = rval_conv._features['proxy']
parts.append(self.decl_var(proxy.wrapped_conv.ctype.add_ref('*'), 'rval_raw', ' = '))
parts.append('new %s(%s);\n' % (proxy.wrapped_conv.ctype, ', '.join(c_call_args)))
parts.append(self.decl_var(from_c_storage_ctype, 'rval'))
parts.append(proxy.wrap('rval_raw', 'rval'))
else:
if 'route' in features:
parts.append(self.decl_var(from_c_storage_ctype, 'rval', ' = '))