-
Notifications
You must be signed in to change notification settings - Fork 55
/
bind_c.py
814 lines (655 loc) · 26.4 KB
/
bind_c.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
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------------------#
# This file is part of Pyccel which is released under MIT License. See the LICENSE file or #
# go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. #
#------------------------------------------------------------------------------------------#
"""
Module describing all elements of the AST needed to represent elements which appear in a Fortran-C binding
file.
"""
from pyccel.ast.basic import PyccelAstNode
from pyccel.ast.core import Module, Deallocate
from pyccel.ast.core import FunctionDef, ClassDef
from pyccel.ast.core import FunctionDefArgument, FunctionDefResult
from pyccel.ast.datatypes import FixedSizeType, PythonNativeInt
from pyccel.ast.variable import Variable
from pyccel.utilities.metaclasses import Singleton
__all__ = (
'BindCArrayVariable',
'BindCClassDef',
'BindCClassProperty',
'BindCFunctionDef',
'BindCFunctionDefArgument',
'BindCFunctionDefResult',
'BindCModule',
'BindCPointer',
'BindCVariable',
'CLocFunc',
'C_F_Pointer',
'DeallocatePointer',
)
# =======================================================================================
# Datatypes
# =======================================================================================
class BindCPointer(FixedSizeType, metaclass = Singleton):
"""
Datatype representing a C pointer in Fortran.
Datatype representing a C pointer in Fortran. This data type is defined
in the iso_c_binding module.
"""
__slots__ = ()
_name = 'bindcpointer'
# =======================================================================================
# Wrapper classes
# =======================================================================================
class BindCFunctionDef(FunctionDef):
"""
Represents the definition of a C-compatible function.
Contains the C-compatible version of the function which is
used for the wrapper.
As compared to a normal FunctionDef, this version contains
arguments for the shape of arrays. It should be generated by
calling `codegen.wrapper.FortranToCWrapper.wrap`.
Parameters
----------
*args : list
See FunctionDef.
original_function : FunctionDef
The function from which the C-compatible version was created.
**kwargs : dict
See FunctionDef.
See Also
--------
pyccel.ast.core.FunctionDef
The class from which BindCFunctionDef inherits which contains all
details about the args and kwargs.
"""
__slots__ = ('_original_function',)
_attribute_nodes = (*FunctionDef._attribute_nodes, '_original_function')
def __init__(self, *args, original_function, **kwargs):
self._original_function = original_function
super().__init__(*args, **kwargs)
assert self.name == self.name.lower()
assert all(isinstance(a, BindCFunctionDefArgument) for a in self._arguments)
assert all(isinstance(a, BindCFunctionDefResult) for a in self._results)
@property
def original_function(self):
"""
The function which is wrapped by this BindCFunctionDef.
The original function which would be printed in pure Fortran which is not
compatible with C.
"""
return self._original_function
@property
def bind_c_arguments(self):
"""
Get the BindCFunctionDefArguments of the function.
Return a list of all the arguments passed to the function.
These objects all have the type BindCFunctionDefArgument so
shapes and strides are hidden.
"""
return self._arguments
@property
def bind_c_results(self):
"""
Get the BindCFunctionDefResults of the function.
Return a list of all the results returned by the function.
These objects all have the type BindCFunctionDefResult so
shapes and strides are hidden.
"""
return self._results
@property
def results(self):
"""
List of all objects returned by the function.
A list of all objects returned by the function including variables
which contain array metadata.
"""
return [ai for a in self._results for ai in a.get_all_function_def_results()]
@property
def arguments(self):
"""
List of all arguments passed to the function.
List of all arguments passed to the function including variables
which contain array metadata.
"""
return [ai for a in self._arguments for ai in a.get_all_function_def_arguments()]
def rename(self, newname):
"""
Rename the FunctionDef name->newname.
Rename the FunctionDef name->newname.
Parameters
----------
newname : str
New name for the FunctionDef.
"""
assert newname == newname.lower()
self._name = newname
# =======================================================================================
class BindCFunctionDefArgument(FunctionDefArgument):
"""
Stores all the information necessary to expose an argument to C code.
Arguments of a C-compatible function may need additional information
in order to fully construct the object. This class is mostly important
for array objects. These objects must pass not only the data, but also
meta-data. Namely the shape and strides for the array in each dimension.
This information is stored in this class.
Parameters
----------
var : Variable
The variable being passed as an argument (with a C-compatible type).
scope : pyccel.parser.scope.Scope
The scope in which any arguments to the function should be declared.
This is used to create the shape and stride variables.
original_arg_var : Variable
The variable which was passed to the function currently being wrapped
in a C-Fortran interface. This variable may have a type which is not
compatible with C.
wrapping_bound_argument : bool
Indicates if the argument being wrapped was a bound argument of a
class method.
**kwargs : dict
See FunctionDefArgument.
See Also
--------
pyccel.ast.core.FunctionDefArgument
The class from which BindCFunctionDefArgument inherits which
contains all details about the args and kwargs.
"""
__slots__ = ('_shape', '_strides', '_original_arg_var', '_rank', '_wrapping_bound_argument')
_attribute_nodes = FunctionDefArgument._attribute_nodes + \
('_shape', '_strides', '_original_arg_var')
def __init__(self, var, scope, original_arg_var, wrapping_bound_argument, **kwargs):
name = var.name
self._rank = original_arg_var.rank
shape = [scope.get_temporary_variable(PythonNativeInt(),
name=f'{name}_shape_{i+1}')
for i in range(self._rank)]
strides = [scope.get_temporary_variable(PythonNativeInt(),
name=f'{name}_stride_{i+1}')
for i in range(self._rank)]
self._shape = shape
self._strides = strides
self._original_arg_var = original_arg_var
self._wrapping_bound_argument = wrapping_bound_argument
super().__init__(var, **kwargs)
@property
def original_function_argument_variable(self):
"""
The argument which was passed to the function currently being wrapped.
The Variable which was passed to the function currently being wrapped
in a C-Fortran interface. This variable may have a type which is not
compatible with C.
"""
return self._original_arg_var
@property
def shape(self):
"""
The shape of the array argument in each dimension.
A tuple containing the variables which describe the number of
elements along each dimension of an array argument. These values
must be passed to any C-compatible function taking an array as an
argument.
"""
return self._shape
@property
def strides(self):
"""
The strides of the array argument in each dimension.
A tuple containing the variables which describe the strides of
an array argument in each dimension. These values must be passed to
any C-compatible function taking an array as an argument.
"""
return self._strides
def get_all_function_def_arguments(self):
"""
Get all argument variables which must be printed to fully describe this argument.
Get a list of all the arguments to the C-compatible function which are
required in order to fully describe this argument. This includes the data
for the object itself as well as any sizes or strides necessary to
define arrays.
Returns
-------
list
A list of FunctionDefArguments which will be arguments of a BindCFunctionDef.
"""
args = [self]
args += [FunctionDefArgument(size) for size in self.shape]
args += [FunctionDefArgument(stride) for stride in self.strides]
return args
def __repr__(self):
if self.has_default:
argument = str(self.name)
value = str(self.value)
return f'BindCFunctionDefArgument({argument}={value}, inout={self.inout})'
else:
return f'BindCFunctionDefArgument({repr(self.name)}, inout={self.inout})'
@property
def inout(self):
"""
Indicates whether the argument may be modified by the function.
True if the argument may be modified in the function. False if
the argument remains constant in the function. For array arguments
the inout status of the sizes and strides are also returned.
"""
if self._rank:
return [False] + [False, False]*self._rank
else:
return super().inout
@property
def wrapping_bound_argument(self):
"""
Indicates if the argument being wrapped was originally a bound argument.
Indicates if the argument being wrapped originally appeared in a class
method as a bound argument.
"""
return self._wrapping_bound_argument
# =======================================================================================
class BindCFunctionDefResult(FunctionDefResult):
"""
Stores all the information necessary to expose a result to C code.
Results of a C-compatible function may need additional information
in order to fully construct the object. This class is mostly important
for array objects. These objects must describe not only the data, but also
meta-data. Namely the shape for the array in each dimension.
This information is stored in this class.
Parameters
----------
var : Variable
The variable being returned (with a C-compatible type).
original_res_var : Variable
The variable which was returned by the function currently being wrapped
in a C-Fortran interface. This variable may have a type which is not
compatible with C.
scope : pyccel.parser.scope.Scope
The scope in which any arguments to the function should be declared.
This is used to create the shape and stride variables.
**kwargs : dict
See FunctionDefResult.
See Also
--------
pyccel.ast.core.FunctionDefResult
The class from which BindCFunctionDefResult inherits which
contains all details about the args and kwargs.
"""
__slots__ = ('_shape', '_original_res_var')
_attribute_nodes = FunctionDefResult._attribute_nodes + \
('_shape', '_original_res_var')
def __init__(self, var, original_res_var, scope, **kwargs):
name = original_res_var.name
self._shape = [scope.get_temporary_variable(PythonNativeInt(),
name=f'{name}_shape_{i+1}')
for i in range(original_res_var.rank)]
self._original_res_var = original_res_var
super().__init__(var, **kwargs)
@property
def original_function_result_variable(self):
"""
The result returned by the function currently being wrapped.
The variable which was returned by the function currently being wrapped
in a C-Fortran interface. This variable may have a type which is not
compatible with C.
"""
return self._original_res_var
@property
def shape(self):
"""
The shape of the array result in each dimension.
A tuple containing the variables which describe the number of
elements along each dimension of an array result. These values
must be returned by any C-compatible function returning an array.
"""
return self._shape
def get_all_function_def_results(self):
"""
Get all result variables which must be printed to fully describe this result.
Get a list of all the results of the C-compatible function which are
required in order to fully describe this result. This includes the data
for the object itself as well as any sizes necessary to
define arrays.
Returns
-------
list
A list of FunctionDefResults which will be results of a BindCFunctionDef.
"""
res = [self]
res += [FunctionDefResult(size) for size in self.shape]
return res
# =======================================================================================
class BindCModule(Module):
"""
Represents a Module which only contains functions compatible with C.
Represents a Module which provides the C-Fortran interface to another module.
Both functions and module variables are wrapped in order to be compatible with
C.
Parameters
----------
*args : tuple
See `pyccel.ast.core.Module`.
original_module : Module
The Module being wrapped.
variable_wrappers : list of BindCFunctionDef
A list containing all the functions which expose module variables to C.
removed_functions : list of FunctionDef
A list of any functions which weren't translated to BindCFunctionDef
objects (e.g. private functions).
**kwargs : dict
See `pyccel.ast.core.Module`.
See Also
--------
pyccel.ast.core.Module
The class from which BindCModule inherits which contains all details
about the args and kwargs.
"""
__slots__ = ('_orig_mod','_variable_wrappers', '_removed_functions')
_attribute_nodes = Module._attribute_nodes + ('_orig_mod','_variable_wrappers', '_removed_functions')
def __init__(self, *args, original_module, variable_wrappers = (), removed_functions = None, **kwargs):
self._orig_mod = original_module
self._variable_wrappers = variable_wrappers
self._removed_functions = removed_functions
super().__init__(*args, **kwargs)
@property
def original_module(self):
"""
The module which was wrapped.
The original module for which this object provides the C-Fortran interface.
"""
return self._orig_mod
@property
def variable_wrappers(self):
"""
Get the wrappers which expose module variables to C.
Get a list containing all the BindCFunctionDefs which expose module variables to C.
"""
return self._variable_wrappers
@property
def removed_functions(self):
"""
Get the functions which weren't translated to BindCFunctionDef objects.
Get a list of the functions which weren't translated to BindCFunctionDef objects.
This includes private functions and objects for which wrapper support is lacking.
"""
return self._removed_functions
@property
def declarations(self):
"""
Get the declarations of all module variables.
In the case of a BindCModule no variables should be declared. Basic variables
are used directly from the original module and more complex variables require
wrapper functions.
"""
return ()
# =======================================================================================
class BindCVariable(Variable):
"""
A class which wraps a compatible variable from Fortran to make it available in C.
A class which wraps a compatible variable from Fortran to make it available in C.
A compatible variable is a variable which can be exposed to C simply using
iso_c_binding (i.e. no wrapper function is required).
Parameters
----------
*args : tuple
See Variable.
**kwargs : dict
See Variable.
See Also
--------
Variable : The super class.
"""
__slots__ = ('_f_name',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._f_name = self._name.lower()
@property
def name(self):
"""
The name of the external variable that should be printed in C.
The name of the external variable that should be printed in C.
In order to be compatible with Fortran the name must be printed
in lower case letters.
"""
return self._f_name
@property
def indexed_name(self):
"""
The name under which the variable is indexed in the scope.
The name under which the variable is indexed in the scope. This is
important in order to be able to collect the original Python name
used by the user in case of collisions.
"""
return self._name
# =======================================================================================
class BindCArrayVariable(Variable):
"""
A class which wraps an array from Fortran to make it available in C.
A class which wraps an array from Fortran to make it available in C.
Parameters
----------
*args : tuple
See Variable.
wrapper_function : FunctionDef
The function which can be used to access the array.
original_variable : Variable
The original variable in the Fortran code.
**kwargs : dict
See Variable.
See Also
--------
Variable : The super class.
"""
__slots__ = ('_wrapper_function', '_original_variable')
_attribute_nodes = ('_wrapper_function', '_original_variable')
def __init__(self, *args, wrapper_function, original_variable, **kwargs):
self._original_variable = original_variable
self._wrapper_function = wrapper_function
super().__init__(*args, **kwargs)
@property
def original_variable(self):
"""
The original variable in the Fortran code.
The original variable in the Fortran code. This is important in
order to access the correct type and other details about the
Variable.
"""
return self._original_variable
@property
def wrapper_function(self):
"""
The function which can be used to access the array.
The function which can be used to access the array. The function
must return the pointer to the raw data and information about
the shape.
"""
return self._wrapper_function
# =======================================================================================
class BindCClassProperty(PyccelAstNode):
"""
A class which wraps a class attribute.
A class which wraps a class attribute to make it accessible
from C. In the future this class will also be used to handle properties of
classes (i.e. functions marked with the `@property` decorator).
Parameters
----------
python_name : str
The name of the attribute/property in the original Python code.
getter : FunctionDef
The function which collects the value of the class attribute.
setter : FunctionDef
The function which modifies the value of the class attribute.
class_type : Variable
The type of the class to which the attribute belongs.
docstring : LiteralString, optional
The docstring of the property.
"""
__slots__ = ('_getter', '_setter', '_python_name', '_docstring', '_class_type')
_attribute_nodes = ('_getter', '_setter')
def __init__(self, python_name, getter, setter, class_type, docstring = None):
if not isinstance(getter, BindCFunctionDef):
raise TypeError("Getter should be a BindCFunctionDef")
if not isinstance(setter, BindCFunctionDef):
raise TypeError("Setter should be a BindCFunctionDef")
self._python_name = python_name
self._getter = getter
self._setter = setter
self._class_type = class_type
self._docstring = docstring
super().__init__()
@property
def getter(self):
"""
The BindCFunctionDef describing the getter function.
The BindCFunctionDef describing the function which allows the user to collect
the value of the property.
"""
return self._getter
@property
def setter(self):
"""
The BindCFunctionDef describing the setter function.
The BindCFunctionDef describing the function which allows the user to modify
the value of the property.
"""
return self._setter
@property
def class_type(self):
"""
The type of the class to which the attribute belongs.
The type of the class to which the attribute belongs.
"""
return self._class_type
@property
def python_name(self):
"""
The name of the attribute/property in the original Python code.
The name of the attribute/property in the original Python code.
"""
return self._python_name
@property
def docstring(self):
"""
The docstring of the property being wrapped.
The docstring of the property being wrapped.
"""
return self._docstring
# =======================================================================================
class BindCClassDef(ClassDef):
"""
Represents a class which is compatible with C.
Represents a class which is compatible with C. This means that it stores
C-compatible versions of class methods and getters and setters for class
variables.
Parameters
----------
original_class : ClassDef
The class being wrapped.
new_func : BindCFunctionDef
The function which provides a new instance of the class.
**kwargs : dict
See ClassDef.
"""
__slots__ = ('_original_class', '_new_func')
def __init__(self, original_class, new_func, **kwargs):
self._original_class = original_class
self._new_func = new_func
super().__init__(original_class.name, scope = original_class.scope, **kwargs)
@property
def new_func(self):
"""
Get the wrapper for `__new__`.
Get the wrapper for `__new__` which allocates the memory for the class instance.
"""
return self._new_func
# =======================================================================================
# Utility functions
# =======================================================================================
class CLocFunc(PyccelAstNode):
"""
Creates a C-compatible pointer to the argument.
Class representing the iso_c_binding function cloc which returns a valid
C pointer to the location where an object can be found.
Parameters
----------
argument : Variable
The object which should be pointed to.
result : Variable of dtype BindCPointer
The variable where the C-compatible pointer should be stored.
"""
__slots__ = ('_arg', '_result')
_attribute_nodes = ()
def __init__(self, argument, result):
self._arg = argument
self._result = result
assert result.dtype is BindCPointer()
super().__init__()
@property
def arg(self):
"""
Pointer target.
Object which will be pointed at by the result pointer.
"""
return self._arg
@property
def result(self):
"""
The variable where the C-compatible pointer should be stored.
The variable where the C-compatible pointer of dtype BindCPointer
should be stored.
"""
return self._result
# =======================================================================================
class C_F_Pointer(PyccelAstNode):
"""
Creates a Fortran array pointer from a C pointer and size information.
Represents the iso_c_binding function C_F_Pointer which takes a pointer
to an object in C (with dtype BindCPointer) and a list of sizes and returns
a Fortran array pointer.
Parameters
----------
c_expr : Variable of dtype BindCPointer
The Variable containing the C pointer.
f_expr : Variable
The Variable containing the resulting array.
shape : list of Variables
A list describing the Variables which dictate the size of the array in each dimension.
"""
__slots__ = ('_c_expr', '_f_expr', '_shape')
_attribute_nodes = ('_c_expr', '_f_expr', '_shape')
def __init__(self, c_expr, f_expr, shape = ()):
self._c_expr = c_expr
self._f_expr = f_expr
self._shape = shape
super().__init__()
@property
def c_pointer(self):
"""
The Variable containing the C pointer.
The Variable of dtype BindCPointer which contains the C pointer.
"""
return self._c_expr
@property
def f_array(self):
"""
The Variable containing the resulting array.
The Variable where the array pointer will be stored.
"""
return self._f_expr
@property
def shape(self):
"""
A list of the sizes of the array in each dimension.
A list describing the Variables which are passed as arguments, in order to
determine the size of the array in each dimension.
"""
return self._shape
class DeallocatePointer(Deallocate):
"""
Represents memory deallocation for memory only stored in a pointer.
Represents memory deallocation for memory only stored in a pointer. Usually
`deallocate` is not called on pointers so as not to delete the target values
however this capability is necessary in the wrapper.
Parameters
----------
variable : pyccel.ast.core.Variable
The typed variable (usually an array) that needs memory deallocation.
"""
__slots__ = ()