-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathwrapper.py
More file actions
executable file
·1938 lines (1592 loc) · 75.9 KB
/
wrapper.py
File metadata and controls
executable file
·1938 lines (1592 loc) · 75.9 KB
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
"""
Code to use the parsed results and convert it to a format
that Matlab's MEX compiler can use.
"""
# pylint: disable=too-many-lines, no-self-use, too-many-arguments, too-many-branches, too-many-statements, consider-using-f-string, unspecified-encoding
import copy
import os
import os.path as osp
import textwrap
from functools import partial, reduce
from typing import Dict, Iterable, List, Union
import gtwrap.interface_parser as parser
import gtwrap.template_instantiator as instantiator
from gtwrap.interface_parser.function import ArgumentList
from gtwrap.matlab_wrapper.mixins import CheckMixin, FormatMixin
from gtwrap.matlab_wrapper.templates import WrapperTemplate
from gtwrap.template_instantiator.classes import InstantiatedClass
class MatlabWrapper(CheckMixin, FormatMixin):
""" Wrap the given C++ code into Matlab.
Attributes
module: the C++ module being wrapped
module_name: name of the C++ module being wrapped
top_module_namespace: C++ namespace for the top module (default '')
ignore_classes: A list of classes to ignore (default [])
"""
def __init__(self,
module_name,
top_module_namespace='',
ignore_classes=(),
use_boost_serialization=False):
super().__init__()
self.module_name = module_name
self.top_module_namespace = top_module_namespace
self.ignore_classes = ignore_classes
self.verbose = False
self.use_boost_serialization = use_boost_serialization
# Map the data type to its Matlab class.
# Found in Argument.cpp in old wrapper
self.data_type = {
'string': 'char',
'char': 'char',
'unsigned char': 'unsigned char',
'Vector': 'double',
'Matrix': 'double',
'int': 'numeric',
'size_t': 'numeric',
'bool': 'logical'
}
# Map the data type into the type used in Matlab methods.
# Found in matlab.h in old wrapper
self.data_type_param = {
'string': 'char',
'char': 'char',
'unsigned char': 'unsigned char',
'size_t': 'int',
'int': 'int',
'double': 'double',
'Point2': 'double',
'Point3': 'double',
'Vector': 'double',
'Matrix': 'double',
'bool': 'bool'
}
# The amount of times the wrapper has created a call to geometry_wrapper
self.wrapper_id = 0
# Map each wrapper id to its collector function namespace, class, type, and string format
self.wrapper_map: Dict = {}
# Set of all the includes in the namespace
self.includes: List[parser.Include] = []
# Set of all classes in the namespace
self.classes: List[Union[parser.Class,
instantiator.InstantiatedClass]] = []
self.classes_elems: Dict[Union[parser.Class,
instantiator.InstantiatedClass],
int] = {}
# Id for ordering global functions in the wrapper
self.global_function_id = 0
# Files and their content
self.content: List[str] = []
# Ensure the template file is always picked up from the correct directory.
dir_path = osp.dirname(osp.realpath(__file__))
with open(osp.join(dir_path, "matlab_wrapper.tpl")) as f:
self.wrapper_file_headers = f.read()
def add_class(self, instantiated_class):
"""Add `instantiated_class` to the list of classes."""
if self.classes_elems.get(instantiated_class) is None:
self.classes_elems[instantiated_class] = 0
self.classes.append(instantiated_class)
def _update_wrapper_id(self,
collector_function=None,
id_diff=0,
function_name: str = None):
"""
Get and define wrapper ids.
Generates the map of id -> collector function.
Args:
collector_function: tuple storing info about the wrapper function
(namespace, class/function instance,
type of collector function, method object if class instance)
id_diff: constant to add to the id in the map
function_name: Optional custom function_name.
Returns:
the current wrapper id
"""
if collector_function is not None:
is_instantiated_class = isinstance(collector_function[1],
instantiator.InstantiatedClass)
if function_name is None:
if is_instantiated_class:
function_name = collector_function[0] + \
collector_function[1].name + '_' + collector_function[2]
else:
function_name = collector_function[1].name
self.wrapper_map[self.wrapper_id] = (
collector_function[0], collector_function[1],
collector_function[2], function_name + '_' +
str(self.wrapper_id + id_diff), collector_function[3])
self.wrapper_id += 1
return self.wrapper_id - 1
def _qualified_name(self, names):
return 'handle' if names == '' else names
def _insert_spaces(self, x, y):
"""Insert spaces at the beginning of each line
Args:
x: the statement currently generated
y: the addition to add to the statement
"""
return x + '\n' + ('' if y == '' else ' ') + y
@staticmethod
def _expand_default_arguments(method, save_backup=True):
"""Recursively expand all possibilities for optional default arguments.
We create "overload" functions with fewer arguments, but since we have to "remember" what
the default arguments are for later, we make a backup.
"""
def args_copy(args):
return ArgumentList([copy.copy(arg) for arg in args.list()])
def method_copy(method):
method2 = copy.copy(method)
method2.args = args_copy(method.args)
method2.args.backup = method.args.backup
return method2
if save_backup:
method.args.backup = args_copy(method.args)
method = method_copy(method)
for arg in reversed(method.args.list()):
if arg.default is not None:
arg.default = None
methodWithArg = method_copy(method)
method.args.list().remove(arg)
return [
methodWithArg,
*MatlabWrapper._expand_default_arguments(method,
save_backup=False)
]
break
assert all(arg.default is None for arg in method.args.list()), \
'In parsing method {:}: Arguments with default values cannot appear before ones ' \
'without default values.'.format(method.name)
return [method]
def _group_methods(self, methods):
"""Group overloaded methods together"""
method_map = {}
method_out = []
for method in methods:
method_index = method_map.get(method.name)
if method_index is None:
method_map[method.name] = len(method_out)
method_out.append(
MatlabWrapper._expand_default_arguments(method))
else:
method_out[
method_index] += MatlabWrapper._expand_default_arguments(
method)
return method_out
def _wrap_args(self, args):
"""Wrap an interface_parser.ArgumentList into a list of arguments.
Returns:
A string representation of the arguments. For example:
'int x, double y'
"""
arg_wrap = ''
for i, arg in enumerate(args.list(), 1):
c_type = self._format_type_name(arg.ctype.typename,
include_namespace=False)
arg_wrap += '{c_type} {arg_name}{comma}'.format(
c_type=c_type,
arg_name=arg.name,
comma='' if i == len(args.list()) else ', ')
return arg_wrap
def _wrap_variable_arguments(self, args, wrap_datatypes=True):
""" Wrap an interface_parser.ArgumentList into a statement of argument
checks.
Returns:
A string representation of a variable arguments for an if
statement. For example:
' && isa(varargin{1},'double') && isa(varargin{2},'numeric')'
"""
var_arg_wrap = ''
for i, arg in enumerate(args.list(), 1):
name = arg.ctype.typename.name
if name in self.not_check_type:
continue
check_type = self.data_type_param.get(name)
if self.data_type.get(check_type):
check_type = self.data_type[check_type]
if check_type is None:
check_type = self._format_type_name(
arg.ctype.typename,
separator='.',
is_constructor=not wrap_datatypes)
var_arg_wrap += " && isa(varargin{{{num}}},'{data_type}')".format(
num=i, data_type=check_type)
if name == 'Vector':
var_arg_wrap += ' && size(varargin{{{num}}},2)==1'.format(
num=i)
if name == 'Point2':
var_arg_wrap += ' && size(varargin{{{num}}},1)==2'.format(
num=i)
var_arg_wrap += ' && size(varargin{{{num}}},2)==1'.format(
num=i)
if name == 'Point3':
var_arg_wrap += ' && size(varargin{{{num}}},1)==3'.format(
num=i)
var_arg_wrap += ' && size(varargin{{{num}}},2)==1'.format(
num=i)
return var_arg_wrap
def _wrap_list_variable_arguments(self, args):
""" Wrap an interface_parser.ArgumentList into a list of argument
variables.
Returns:
A string representation of a list of variable arguments.
For example:
'varargin{1}, varargin{2}, varargin{3}'
"""
var_list_wrap = ''
first = True
for i in range(1, len(args.list()) + 1):
if first:
var_list_wrap += 'varargin{{{}}}'.format(i)
first = False
else:
var_list_wrap += ', varargin{{{}}}'.format(i)
return var_list_wrap
def _wrap_method_check_statement(self, args: parser.ArgumentList):
"""
Wrap the given arguments into either just a varargout call or a
call in an if statement that checks if the parameters are accurate.
TODO Update this method so that default arguments are supported.
"""
arg_id = 1
param_count = len(args)
check_statement = 'if length(varargin) == {param_count}'.format(
param_count=param_count)
for _, arg in enumerate(args.list()):
name = arg.ctype.typename.name
if name in self.not_check_type:
arg_id += 1
continue
check_type = self.data_type_param.get(name)
if self.data_type.get(check_type):
check_type = self.data_type[check_type]
if check_type is None:
check_type = self._format_type_name(arg.ctype.typename,
separator='.')
check_statement += " && isa(varargin{{{id}}},'{ctype}')".format(
id=arg_id, ctype=check_type)
if name == 'Vector':
check_statement += ' && size(varargin{{{num}}},2)==1'.format(
num=arg_id)
if name == 'Point2':
check_statement += ' && size(varargin{{{num}}},1)==2'.format(
num=arg_id)
check_statement += ' && size(varargin{{{num}}},2)==1'.format(
num=arg_id)
if name == 'Point3':
check_statement += ' && size(varargin{{{num}}},1)==3'.format(
num=arg_id)
check_statement += ' && size(varargin{{{num}}},2)==1'.format(
num=arg_id)
arg_id += 1
check_statement = check_statement \
if check_statement == '' \
else check_statement + '\n'
return check_statement
def _unwrap_argument(self, arg, arg_id=0, instantiated_class=None):
ctype_camel = self._format_type_name(arg.ctype.typename, separator='')
ctype_sep = self._format_type_name(arg.ctype.typename)
if instantiated_class and \
self.is_enum(arg.ctype, instantiated_class):
enum_type = f"{arg.ctype.typename}"
arg_type = f"{enum_type}"
unwrap = f'unwrap_enum<{enum_type}>(in[{arg_id}]);'
elif self.is_ref(arg.ctype): # and not constructor:
arg_type = "{ctype}&".format(ctype=ctype_sep)
unwrap = '*unwrap_shared_ptr< {ctype} >(in[{id}], "ptr_{ctype_camel}");'.format(
ctype=ctype_sep, ctype_camel=ctype_camel, id=arg_id)
elif self.is_ptr(arg.ctype) and \
arg.ctype.typename.name not in self.ignore_namespace:
arg_type = "{ctype_sep}*".format(ctype_sep=ctype_sep)
unwrap = 'unwrap_ptr< {ctype_sep} >(in[{id}], "ptr_{ctype}");'.format(
ctype_sep=ctype_sep, ctype=ctype_camel, id=arg_id)
elif (self.is_shared_ptr(arg.ctype) or self.can_be_pointer(arg.ctype)) and \
arg.ctype.typename.name not in self.ignore_namespace:
arg_type = "std::shared_ptr<{ctype_sep}>".format(
ctype_sep=ctype_sep)
unwrap = 'unwrap_shared_ptr< {ctype_sep} >(in[{id}], "ptr_{ctype}");'.format(
ctype_sep=ctype_sep, ctype=ctype_camel, id=arg_id)
else:
arg_type = "{ctype}".format(ctype=arg.ctype.typename.name)
unwrap = 'unwrap< {ctype} >(in[{id}]);'.format(
ctype=arg.ctype.typename.name, id=arg_id)
return arg_type, unwrap
def _wrapper_unwrap_arguments(self,
args,
arg_id=0,
instantiated_class=None):
"""Format the interface_parser.Arguments.
Examples:
((a), unsigned char a = unwrap< unsigned char >(in[1]);),
((a), Test& t = *unwrap_shared_ptr< Test >(in[1], "ptr_Test");),
((a), std::shared_ptr<Test> p1 = unwrap_shared_ptr< Test >(in[1], "ptr_Test");)
"""
body_args = ''
for arg in args.list():
arg_type, unwrap = self._unwrap_argument(
arg, arg_id, instantiated_class=instantiated_class)
body_args += textwrap.indent(textwrap.dedent('''\
{arg_type} {name} = {unwrap}
'''.format(arg_type=arg_type, name=arg.name,
unwrap=unwrap)),
prefix=' ')
arg_id += 1
params = ''
explicit_arg_names = [arg.name for arg in args.list()]
# when returning the params list, we need to re-include the default args.
for arg in args.backup.list():
if params != '':
params += ','
if (arg.default is not None) and (arg.name
not in explicit_arg_names):
params += arg.default
continue
if not self.is_ref(arg.ctype) and (self.is_shared_ptr(arg.ctype) or \
self.is_ptr(arg.ctype) or self.can_be_pointer(arg.ctype)) and \
not self.is_enum(arg.ctype, instantiated_class) and \
arg.ctype.typename.name not in self.ignore_namespace:
if arg.ctype.is_shared_ptr:
call_type = arg.ctype.is_shared_ptr
else:
call_type = arg.ctype.is_ptr
if call_type == "":
params += "*"
params += arg.name
return params, body_args
@staticmethod
def _return_count(return_type):
"""The amount of objects returned by the given
interface_parser.ReturnType.
"""
return 1 if return_type.type2 == '' else 2
def _wrapper_name(self):
"""Determine the name of wrapper function."""
return self.module_name + '_wrapper'
def class_serialize_comment(self, class_name, static_methods):
"""Generate comments for serialize methods."""
comment_wrap = ''
static_methods = sorted(static_methods, key=lambda name: name.name)
for static_method in static_methods:
if comment_wrap == '':
comment_wrap = '%-------Static Methods-------\n'
comment_wrap += '%{name}({args}) : returns {return_type}\n'.format(
name=static_method.name,
args=self._wrap_args(static_method.args),
return_type=self._format_return_type(static_method.return_type,
include_namespace=True))
comment_wrap += textwrap.dedent('''\
%
%-------Serialization Interface-------
%string_serialize() : returns string
%string_deserialize(string serialized) : returns {class_name}
%
''').format(class_name=class_name)
return comment_wrap
def class_comment(self, instantiated_class):
"""Generate comments for the given class in Matlab.
Args
instantiated_class: the class being wrapped
ctors: a list of the constructors in the class
methods: a list of the methods in the class
"""
class_name = instantiated_class.name
ctors = instantiated_class.ctors
properties = instantiated_class.properties
methods = instantiated_class.methods
static_methods = instantiated_class.static_methods
comment = textwrap.dedent('''\
%class {class_name}, see Doxygen page for details
%at https://gtsam.org/doxygen/
''').format(class_name=class_name)
if len(ctors) != 0:
comment += '%\n%-------Constructors-------\n'
# Write constructors
for ctor in ctors:
comment += '%{ctor_name}({args})\n'.format(ctor_name=ctor.name,
args=self._wrap_args(
ctor.args))
if len(properties) != 0:
comment += '%\n' \
'%-------Properties-------\n'
for propty in properties:
comment += '%{}\n'.format(propty.name)
if len(methods) != 0:
comment += '%\n' \
'%-------Methods-------\n'
methods = sorted(methods, key=lambda name: name.name)
# Write methods
for method in methods:
if method.name in self.whitelist:
continue
if method.name in self.ignore_methods:
continue
comment += '%{name}({args})'.format(name=method.name,
args=self._wrap_args(
method.args))
if method.return_type.type2 == '':
return_type = self._format_type_name(
method.return_type.type1.typename)
else:
return_type = 'pair< {type1}, {type2} >'.format(
type1=self._format_type_name(
method.return_type.type1.typename),
type2=self._format_type_name(
method.return_type.type2.typename))
comment += ' : returns {return_type}\n'.format(
return_type=return_type)
comment += '%\n'
if len(static_methods) != 0:
comment += self.class_serialize_comment(class_name, static_methods)
return comment
def wrap_method(self, methods):
"""
Wrap methods in the body of a class.
"""
if not isinstance(methods, list):
methods = [methods]
return ''
def wrap_methods(self, methods, global_funcs=False, global_ns=None):
"""
Wrap a sequence of methods/functions. Groups methods with the same names
together.
If global_funcs is True then output every method into its own file.
"""
output = ''
methods = self._group_methods(methods)
for method in methods:
if method in self.ignore_methods:
continue
if global_funcs:
method_text = self.wrap_global_function(method)
self.content.append(("".join([
'+' + x + '/' for x in global_ns.full_namespaces()[1:]
])[:-1], [(method[0].name + '.m', method_text)]))
else:
method_text = self.wrap_method(method)
output += ''
return output
def wrap_global_function(self, function):
"""Wrap the given global function."""
if not isinstance(function, list):
function = [function]
function_name = function[0].name
# Get all combinations of parameters
param_wrap = ''
# Iterate through possible overloads of the function
for i, overload in enumerate(function):
param_wrap += ' if' if i == 0 else ' elseif'
param_wrap += ' length(varargin) == '
if len(overload.args.list()) == 0:
param_wrap += '0\n'
else:
param_wrap += str(len(overload.args.list())) \
+ self._wrap_variable_arguments(overload.args, False) + '\n'
# Determine format of return and varargout statements
return_type_formatted = self._format_return_type(
overload.return_type, include_namespace=True, separator=".")
varargout = self._format_varargout(overload.return_type,
return_type_formatted)
param_wrap += textwrap.indent(textwrap.dedent('''\
{varargout}{module_name}_wrapper({num}, varargin{{:}});
''').format(varargout=varargout,
module_name=self.module_name,
num=self._update_wrapper_id(
collector_function=(function[0].parent.name,
function[i], 'global_function',
None))),
prefix=' ')
param_wrap += textwrap.indent(textwrap.dedent('''\
else
error('Arguments do not match any overload of function {func_name}');
end''').format(func_name=function_name),
prefix=' ')
global_function = textwrap.indent(textwrap.dedent('''\
function varargout = {m_method}(varargin)
{statements}
end
''').format(m_method=function_name, statements=param_wrap),
prefix='')
return global_function
def wrap_class_constructors(self, namespace_name, inst_class, parent_name,
ctors, is_virtual):
"""Wrap class constructor.
Args:
namespace_name: the name of the namespace ('' if it does not exist)
inst_class: instance of the class
parent_name: the name of the parent class if it exists
ctors: the interface_parser.Constructor in the class
is_virtual: whether the class is part of a virtual inheritance
chain
"""
has_parent = parent_name != ''
class_name = inst_class.name
if has_parent:
parent_name = self._format_type_name(parent_name, separator=".")
if not isinstance(ctors, Iterable):
ctors = [ctors]
ctors = sum((MatlabWrapper._expand_default_arguments(ctor)
for ctor in ctors), [])
methods_wrap = textwrap.indent(textwrap.dedent("""\
methods
function obj = {class_name}(varargin)
""").format(class_name=class_name),
prefix='')
if is_virtual:
methods_wrap += " if (nargin == 2 || (nargin == 3 && strcmp(varargin{3}, 'void')))"
else:
methods_wrap += ' if nargin == 2'
methods_wrap += " && isa(varargin{1}, 'uint64')"
methods_wrap += " && varargin{1} == uint64(5139824614673773682)\n"
if is_virtual:
methods_wrap += textwrap.indent(textwrap.dedent('''\
if nargin == 2
my_ptr = varargin{{2}};
else
my_ptr = {wrapper_name}({id}, varargin{{2}});
end
''').format(wrapper_name=self._wrapper_name(),
id=self._update_wrapper_id() + 1),
prefix=' ')
else:
methods_wrap += ' my_ptr = varargin{2};\n'
collector_base_id = self._update_wrapper_id(
(namespace_name, inst_class, 'collectorInsertAndMakeBase', None),
id_diff=-1 if is_virtual else 0)
methods_wrap += ' {ptr}{wrapper_name}({id}, my_ptr);\n' \
.format(
ptr='base_ptr = ' if has_parent else '',
wrapper_name=self._wrapper_name(),
id=collector_base_id - (1 if is_virtual else 0))
for ctor in ctors:
wrapper_return = '[ my_ptr, base_ptr ] = ' \
if has_parent \
else 'my_ptr = '
methods_wrap += textwrap.indent(textwrap.dedent('''\
elseif nargin == {len}{varargin}
{ptr}{wrapper}({num}{comma}{var_arg});
''').format(len=len(ctor.args.list()),
varargin=self._wrap_variable_arguments(
ctor.args, False),
ptr=wrapper_return,
wrapper=self._wrapper_name(),
num=self._update_wrapper_id(
(namespace_name, inst_class, 'constructor', ctor)),
comma='' if len(ctor.args.list()) == 0 else ', ',
var_arg=self._wrap_list_variable_arguments(ctor.args)),
prefix=' ')
base_obj = ''
if has_parent:
base_obj = ' obj = obj@{parent_name}(uint64(5139824614673773682), base_ptr);'.format(
parent_name=parent_name)
if base_obj:
base_obj = '\n' + base_obj
methods_wrap += textwrap.indent(textwrap.dedent('''\
else
error('Arguments do not match any overload of {class_name_doc} constructor');
end{base_obj}
obj.ptr_{class_name} = my_ptr;
end\n
''').format(namespace=namespace_name,
d='' if namespace_name == '' else '.',
class_name_doc=self._format_class_name(inst_class,
separator="."),
class_name=self._format_class_name(inst_class,
separator=""),
base_obj=base_obj),
prefix=' ')
return methods_wrap
def wrap_properties_block(self, class_name, inst_class):
"""Generate Matlab properties block of the class.
E.g.
```
properties
ptr_gtsamISAM2Params = 0
relinearizeSkip
end
```
Args:
class_name: Class name with namespace to assign unique pointer.
inst_class: The instantiated class whose properties we want to wrap.
Returns:
str: The `properties` block in a Matlab `classdef`.
"""
# Get the property names and make into newline separated block
class_pointer = " ptr_{class_name} = 0".format(class_name=class_name)
if len(inst_class.properties) > 0:
properties = '\n' + "\n".join(
[" {}".format(p.name) for p in inst_class.properties])
else:
properties = ''
properties = class_pointer + properties
properties_block = textwrap.dedent('''\
properties
{properties}
end
''').format(properties=properties)
return properties_block
def wrap_class_properties(self, namespace_name: str,
inst_class: InstantiatedClass):
"""Generate wrappers for the setters & getters of class properties.
Args:
inst_class: The instantiated class whose properties we wish to wrap.
"""
properties = []
for propty in inst_class.properties:
# These are the setters and getters in the .m file
function_name = namespace_name + inst_class.name + '_get_' + propty.name
getter = """
function varargout = get.{name}(this)
{varargout} = {wrapper}({num}, this);
this.{name} = {varargout};
end
""".format(name=propty.name,
varargout='varargout{1}',
wrapper=self._wrapper_name(),
num=self._update_wrapper_id(
(namespace_name, inst_class, propty.name, propty),
function_name=function_name))
properties.append(getter)
# Setter doesn't need varargin since it needs just one input.
function_name = namespace_name + inst_class.name + '_set_' + propty.name
setter = """
function set.{name}(this, value)
obj.{name} = value;
{wrapper}({num}, this, value);
end
""".format(name=propty.name,
wrapper=self._wrapper_name(),
num=self._update_wrapper_id(
(namespace_name, inst_class, propty.name, propty),
function_name=function_name))
properties.append(setter)
return properties
def wrap_class_deconstructor(self, namespace_name, inst_class):
"""Generate the delete function for the Matlab class."""
class_name = inst_class.name
methods_text = textwrap.indent(textwrap.dedent("""\
function delete(obj)
{wrapper}({num}, obj.ptr_{class_name});
end\n
""").format(num=self._update_wrapper_id(
(namespace_name, inst_class, 'deconstructor', None)),
wrapper=self._wrapper_name(),
class_name="".join(inst_class.parent.full_namespaces()) +
class_name),
prefix=' ')
return methods_text
def wrap_class_display(self):
"""Generate the display function for the Matlab class."""
return textwrap.indent(textwrap.dedent("""\
function display(obj), obj.print(''); end
%DISPLAY Calls print on the object
function disp(obj), obj.display; end
%DISP Calls print on the object
"""),
prefix=' ')
def _group_class_methods(self, methods):
"""Group overloaded methods together"""
return self._group_methods(methods)
@classmethod
def _format_varargout(cls, return_type, return_type_formatted):
"""Determine format of return and varargout statements"""
if cls._return_count(return_type) == 1:
varargout = '' \
if return_type_formatted == 'void' \
else 'varargout{1} = '
else:
varargout = '[ varargout{1} varargout{2} ] = '
return varargout
def wrap_class_methods(self,
namespace_name,
inst_class,
methods,
serialize=(False, )):
"""Wrap the methods in the class.
Args:
namespace_name: the name of the class's namespace
inst_class: the instantiated class whose methods to wrap
methods: the methods to wrap in the order to wrap them
serialize: mutable param storing if one of the methods is serialize
"""
method_text = ''
methods = self._group_class_methods(methods)
# Convert to list so that it is mutable
if isinstance(serialize, tuple):
serialize = list(serialize)
for method in methods:
method_name = method[0].name
if method_name in self.whitelist and method_name != 'serialize':
continue
if method_name in self.ignore_methods:
continue
if method_name == 'serialize':
if self.use_boost_serialization:
serialize[0] = True
method_text += self.wrap_class_serialize_method(
namespace_name, inst_class)
else:
# Generate method code
method_text += textwrap.indent(textwrap.dedent("""\
function varargout = {method_name}(this, varargin)
""").format(caps_name=method_name.upper(),
method_name=method_name),
prefix='')
for overload in method:
method_text += textwrap.indent(textwrap.dedent("""\
% {caps_name} usage: {method_name}(""").format(
caps_name=method_name.upper(),
method_name=method_name),
prefix=' ')
# Determine format of return and varargout statements
return_type_formatted = self._format_return_type(
overload.return_type,
include_namespace=True,
separator=".")
varargout = self._format_varargout(overload.return_type,
return_type_formatted)
check_statement = self._wrap_method_check_statement(
overload.args)
class_name = namespace_name + ('' if namespace_name == ''
else '.') + inst_class.name
end_statement = '' \
if check_statement == '' \
else textwrap.indent(textwrap.dedent("""\
return
end
""").format(
class_name=class_name,
method_name=overload.original.name), prefix=' ')
method_text += textwrap.dedent("""\
{method_args}) : returns {return_type}
% Doxygen can be found at https://gtsam.org/doxygen/
{check_statement}{spacing}{varargout}{wrapper}({num}, this, varargin{{:}});
{end_statement}""").format(
method_args=self._wrap_args(overload.args),
return_type=return_type_formatted,
num=self._update_wrapper_id(
(namespace_name, inst_class,
overload.original.name, overload)),
check_statement=check_statement,
spacing='' if check_statement == '' else ' ',
varargout=varargout,
wrapper=self._wrapper_name(),
end_statement=end_statement)
final_statement = textwrap.indent(textwrap.dedent("""\
error('Arguments do not match any overload of function {class_name}.{method_name}');
""".format(class_name=class_name, method_name=method_name)),
prefix=' ')
method_text += final_statement + 'end\n\n'
return method_text
def wrap_static_methods(self, namespace_name, instantiated_class,
serialize):
"""
Wrap the static methods in the class.
"""
class_name = instantiated_class.name
method_text = 'methods(Static = true)\n'
static_methods = sorted(instantiated_class.static_methods,
key=lambda name: name.name)
static_methods = self._group_class_methods(static_methods)
for static_method in static_methods:
format_name = list(static_method[0].name)
format_name[0] = format_name[0]
if static_method[0].name in self.ignore_methods:
continue
method_text += textwrap.indent(textwrap.dedent('''\
function varargout = {name}(varargin)
'''.format(name=''.join(format_name))),
prefix=" ")
for static_overload in static_method:
check_statement = self._wrap_method_check_statement(
static_overload.args)
end_statement = '' \
if check_statement == '' \
else textwrap.indent(textwrap.dedent("""
return
end
"""), prefix='')
method_text += textwrap.indent(textwrap.dedent('''\
% {name_caps} usage: {name_upper_case}({args}) : returns {return_type}
% Doxygen can be found at https://gtsam.org/doxygen/
{check_statement}{spacing}varargout{{1}} = {wrapper}({id}, varargin{{:}});{end_statement}
''').format(
name=''.join(format_name),
name_caps=static_overload.name.upper(),
name_upper_case=static_overload.name,
args=self._wrap_args(static_overload.args),
return_type=self._format_return_type(
static_overload.return_type,
include_namespace=True,
separator="."),
length=len(static_overload.args.list()),
var_args_list=self._wrap_variable_arguments(
static_overload.args),
check_statement=check_statement,
spacing='' if check_statement == '' else ' ',
wrapper=self._wrapper_name(),
id=self._update_wrapper_id(
(namespace_name, instantiated_class,
static_overload.name, static_overload)),
class_name=instantiated_class.name,
end_statement=end_statement),
prefix=' ')