-
Notifications
You must be signed in to change notification settings - Fork 55
/
ccode.py
2516 lines (2112 loc) · 96.1 KB
/
ccode.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
# 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. #
#------------------------------------------------------------------------------------------#
import functools
from itertools import chain
import re
from pyccel.ast.basic import ScopedAstNode
from pyccel.ast.builtins import PythonRange, PythonComplex
from pyccel.ast.builtins import PythonPrint, PythonType
from pyccel.ast.builtins import PythonList, PythonTuple
from pyccel.ast.core import Declare, For, CodeBlock
from pyccel.ast.core import FuncAddressDeclare, FunctionCall, FunctionCallArgument
from pyccel.ast.core import Allocate, Deallocate
from pyccel.ast.core import FunctionAddress
from pyccel.ast.core import Assign, Import, AugAssign, AliasAssign
from pyccel.ast.core import SeparatorComment
from pyccel.ast.core import Module, AsName
from pyccel.ast.operators import PyccelAdd, PyccelMul, PyccelMinus, PyccelLt, PyccelGt
from pyccel.ast.operators import PyccelAssociativeParenthesis, PyccelMod
from pyccel.ast.operators import PyccelUnarySub, IfTernaryOperator
from pyccel.ast.datatypes import PythonNativeInt, PythonNativeBool, VoidType
from pyccel.ast.datatypes import TupleType, FixedSizeNumericType
from pyccel.ast.datatypes import CustomDataType, StringType, HomogeneousTupleType
from pyccel.ast.datatypes import PrimitiveBooleanType, PrimitiveIntegerType, PrimitiveFloatingPointType, PrimitiveComplexType
from pyccel.ast.datatypes import HomogeneousContainerType
from pyccel.ast.internals import Slice, PrecomputedCode, PyccelArrayShapeElement
from pyccel.ast.literals import LiteralTrue, LiteralFalse, LiteralImaginaryUnit, LiteralFloat
from pyccel.ast.literals import LiteralString, LiteralInteger, Literal
from pyccel.ast.literals import Nil
from pyccel.ast.mathext import math_constants
from pyccel.ast.numpyext import NumpyFull, NumpyArray
from pyccel.ast.numpyext import NumpyReal, NumpyImag, NumpyFloat, NumpySize
from pyccel.ast.numpytypes import NumpyInt8Type, NumpyInt16Type, NumpyInt32Type, NumpyInt64Type
from pyccel.ast.numpytypes import NumpyFloat32Type, NumpyFloat64Type, NumpyComplex64Type, NumpyComplex128Type
from pyccel.ast.numpytypes import NumpyNDArrayType, numpy_precision_map
from pyccel.ast.utilities import expand_to_loops
from pyccel.ast.variable import IndexedElement
from pyccel.ast.variable import Variable
from pyccel.ast.variable import DottedName
from pyccel.ast.variable import DottedVariable
from pyccel.ast.variable import InhomogeneousTupleVariable
from pyccel.ast.c_concepts import ObjectAddress, CMacro, CStringExpression, PointerCast, CNativeInt
from pyccel.codegen.printing.codeprinter import CodePrinter
from pyccel.errors.errors import Errors
from pyccel.errors.messages import (PYCCEL_RESTRICTION_TODO, INCOMPATIBLE_TYPEVAR_TO_FUNC,
PYCCEL_RESTRICTION_IS_ISNOT, UNSUPPORTED_ARRAY_RANK)
errors = Errors()
# TODO: add examples
__all__ = ["CCodePrinter", "ccode"]
# dictionary mapping numpy function to (argument_conditions, C_function).
# Used in CCodePrinter._print_NumpyUfuncBase(self, expr)
numpy_ufunc_to_c_float = {
'NumpyAbs' : 'fabs',
'NumpyFabs' : 'fabs',
'NumpyFloor': 'floor', # TODO: might require special treatment with casting
# ---
'NumpyExp' : 'exp',
'NumpyLog' : 'log',
'NumpySqrt': 'sqrt',
# ---
'NumpySin' : 'sin',
'NumpyCos' : 'cos',
'NumpyTan' : 'tan',
'NumpyArcsin' : 'asin',
'NumpyArccos' : 'acos',
'NumpyArctan' : 'atan',
'NumpyArctan2': 'atan2',
'NumpySinh' : 'sinh',
'NumpyCosh' : 'cosh',
'NumpyTanh' : 'tanh',
'NumpyArcsinh': 'asinh',
'NumpyArccosh': 'acosh',
'NumpyArctanh': 'atanh',
'NumpyIsInf':'isinf',
'NumpyIsFinite':'isfinite',
'NumpyIsNan':'isnan',
}
numpy_ufunc_to_c_complex = {
'NumpyAbs' : 'cabs',
# ---
'NumpyExp' : 'cexp',
'NumpyLog' : 'clog',
'NumpySqrt': 'csqrt',
# ---
'NumpySin' : 'csin',
'NumpyCos' : 'ccos',
'NumpyTan' : 'ctan',
'NumpyArcsin' : 'casin',
'NumpyArccos' : 'cacos',
'NumpyArctan' : 'catan',
'NumpySinh' : 'csinh',
'NumpyCosh' : 'ccosh',
'NumpyTanh' : 'ctanh',
'NumpyArcsinh': 'casinh',
'NumpyArccosh': 'cacosh',
'NumpyArctanh': 'catanh',
}
# dictionary mapping Math function to (argument_conditions, C_function).
# Used in CCodePrinter._print_MathFunctionBase(self, expr)
# Math function ref https://docs.python.org/3/library/math.html
math_function_to_c = {
# ---------- Number-theoretic and representation functions ------------
'MathCeil' : 'ceil',
# 'MathComb' : 'com' # TODO
'MathCopysign': 'copysign',
'MathFabs' : 'fabs',
'MathFloor' : 'floor',
# 'MathFmod' : '???', # TODO
# 'MathRexp' : '???' TODO requires two output
# 'MathFsum' : '???', # TODO
# 'MathIsclose' : '???', # TODO
'MathIsfinite': 'isfinite', # int isfinite(real-floating x);
'MathIsinf' : 'isinf', # int isinf(real-floating x);
'MathIsnan' : 'isnan', # int isnan(real-floating x);
# 'MathIsqrt' : '???' TODO
'MathLdexp' : 'ldexp',
# 'MathModf' : '???' TODO return two value
# 'MathPerm' : '???' TODO
# 'MathProd' : '???' TODO
'MathRemainder' : 'remainder',
'MathTrunc' : 'trunc',
# ----------------- Power and logarithmic functions -----------------------
'MathExp' : 'exp',
'MathExpm1' : 'expm1',
'MathLog' : 'log', # take also an option arg [base]
'MathLog1p' : 'log1p',
'MathLog2' : 'log2',
'MathLog10' : 'log10',
'MathPow' : 'pow',
'MathSqrt' : 'sqrt',
# --------------------- Trigonometric functions ---------------------------
'MathAcos' : 'acos',
'MathAsin' : 'asin',
'MathAtan' : 'atan',
'MathAtan2' : 'atan2',
'MathCos' : 'cos',
# 'MathDist' : '???', TODO
'MathHypot' : 'hypot',
'MathSin' : 'sin',
'MathTan' : 'tan',
# -------------------------- Hyperbolic functions -------------------------
'MathAcosh' : 'acosh',
'MathAsinh' : 'asinh',
'MathAtanh' : 'atanh',
'MathCosh' : 'cosh',
'MathSinh' : 'sinh',
'MathTanh' : 'tanh',
# --------------------------- Special functions ---------------------------
'MathErf' : 'erf',
'MathErfc' : 'erfc',
'MathGamma' : 'tgamma',
'MathLgamma' : 'lgamma',
# --------------------------- internal functions --------------------------
'MathFactorial' : 'pyc_factorial',
'MathGcd' : 'pyc_gcd',
'MathDegrees' : 'pyc_degrees',
'MathRadians' : 'pyc_radians',
'MathLcm' : 'pyc_lcm',
# --------------------------- cmath functions --------------------------
'CmathAcos' : 'cacos',
'CmathAcosh' : 'cacosh',
'CmathAsin' : 'casin',
'CmathAsinh' : 'casinh',
'CmathAtan' : 'catan',
'CmathAtanh' : 'catanh',
'CmathCos' : 'ccos',
'CmathCosh' : 'ccosh',
'CmathExp' : 'cexp',
'CmathSin' : 'csin',
'CmathSinh' : 'csinh',
'CmathSqrt' : 'csqrt',
'CmathTan' : 'ctan',
'CmathTanh' : 'ctanh',
}
c_library_headers = (
"complex",
"ctype",
"float",
"math",
"stdarg",
"stdbool",
"stddef",
"stdint",
"stdio",
"stdlib",
"string",
"tgmath",
"inttypes",
)
import_dict = {'omp_lib' : 'omp' }
c_imports = {n : Import(n, Module(n, (), ())) for n in
['stdlib',
'math',
'string',
'ndarrays',
'complex',
'stdint',
'pyc_math_c',
'stdio',
"inttypes",
'stdbool',
'assert',
'numpy_c']}
class CCodePrinter(CodePrinter):
"""
A printer for printing code in C.
A printer to convert Pyccel's AST to strings of c code.
As for all printers the navigation of this file is done via _print_X
functions.
Parameters
----------
filename : str
The name of the file being pyccelised.
prefix_module : str
A prefix to be added to the name of the module.
"""
printmethod = "_ccode"
language = "C"
_default_settings = {
'tabwidth': 4,
}
dtype_registry = {CNativeInt() : 'int',
VoidType() : 'void',
(PrimitiveComplexType(),8) : 'double complex',
(PrimitiveComplexType(),4) : 'float complex',
(PrimitiveFloatingPointType(),8) : 'double',
(PrimitiveFloatingPointType(),4) : 'float',
(PrimitiveIntegerType(),4) : 'int32_t',
(PrimitiveIntegerType(),8) : 'int64_t',
(PrimitiveIntegerType(),2) : 'int16_t',
(PrimitiveIntegerType(),1) : 'int8_t',
(PrimitiveBooleanType(),-1) : 'bool',
}
ndarray_type_registry = {
NumpyFloat64Type() : 'nd_double',
NumpyFloat32Type() : 'nd_float',
NumpyComplex128Type() : 'nd_cdouble',
NumpyComplex64Type() : 'nd_cfloat',
NumpyInt64Type() : 'nd_int64',
NumpyInt32Type() : 'nd_int32',
NumpyInt16Type() : 'nd_int16',
NumpyInt8Type() : 'nd_int8',
PythonNativeBool() : 'nd_bool'}
type_to_format = {(PrimitiveFloatingPointType(),8) : '%.15lf',
(PrimitiveFloatingPointType(),4) : '%.6f',
(PrimitiveIntegerType(),4) : '%d',
(PrimitiveIntegerType(),8) : LiteralString("%") + CMacro('PRId64'),
(PrimitiveIntegerType(),2) : LiteralString("%") + CMacro('PRId16'),
(PrimitiveIntegerType(),1) : LiteralString("%") + CMacro('PRId8'),
StringType() : '%s',
}
def __init__(self, filename, prefix_module = None):
errors.set_target(filename, 'file')
super().__init__()
self.prefix_module = prefix_module
self._additional_imports = {'stdlib':c_imports['stdlib']}
self._additional_code = ''
self._additional_args = []
self._temporary_args = []
self._current_module = None
self._in_header = False
def get_additional_imports(self):
"""return the additional imports collected in printing stage"""
return self._additional_imports.keys()
def add_import(self, import_obj):
if import_obj.source not in self._additional_imports:
self._additional_imports[import_obj.source] = import_obj
def _get_statement(self, codestring):
return "%s;\n" % codestring
def _get_comment(self, text):
return "// {0}\n".format(text)
def _format_code(self, lines):
return self.indent_code(lines)
def _flatten_list(self, irregular_list):
if isinstance(irregular_list, (PythonList, PythonTuple)):
f_list = [element for item in irregular_list for element in self._flatten_list(item)]
return f_list
else:
return [irregular_list]
def is_c_pointer(self, a):
"""
Indicate whether the object is a pointer in C code.
Some objects are accessed via a C pointer so that they can be modified in
their scope and that modification can be retrieved elsewhere. This
information cannot be found trivially so this function provides that
information while avoiding easily outdated code to be repeated.
The main reasons for this treatment are:
1. It is the actual memory address of an object
2. It is a reference to another object (e.g. an alias, an optional argument, or one of multiple return arguments)
See codegen_stage.md in the developer docs for more details.
Parameters
----------
a : TypedAstNode
The object whose storage we are enquiring about.
Returns
-------
bool
True if a C pointer, False otherwise.
"""
if isinstance(a, (Nil, ObjectAddress, PointerCast)):
return True
if isinstance(a, FunctionCall):
a = a.funcdef.results[0].var
if isinstance(getattr(a, 'dtype', None), CustomDataType) and a.is_argument:
return True
if not isinstance(a, Variable):
return False
return (a.is_alias and not isinstance(a.class_type, HomogeneousContainerType)) \
or a.is_optional or \
any(a is bi for b in self._additional_args for bi in b)
#========================== Numpy Elements ===============================#
def copy_NumpyArray_Data(self, expr):
"""
Get code which copies data from a Ndarray or a homogeneous tuple into a Ndarray.
When data is copied from a homogeneous tuple, the code declares and fills
a dummy data_buffer and copies the data from it to a NdArray struct.
When data is copied from a Ndarray this is done directly without an intermediate
structure.
Parameters
----------
expr : TypedAstNode
The Assign Node used to get the lhs and rhs.
Returns
-------
str
A string containing the code which allocates and copies the data.
"""
rhs = expr.rhs
lhs = expr.lhs
if rhs.rank == 0:
raise NotImplementedError(str(expr))
arg = rhs.arg if isinstance(rhs, NumpyArray) else rhs
lhs_address = self._print(ObjectAddress(lhs))
# If the data is copied from a Variable rather than a list or tuple
# use the function array_copy_data directly
if isinstance(arg, Variable):
return f"array_copy_data({lhs_address}, {self._print(arg)}, 0);\n"
order = lhs.order
lhs_dtype = lhs.dtype
declare_dtype = self.find_in_dtype_registry(lhs_dtype)
if isinstance(lhs.class_type, NumpyNDArrayType):
#set dtype to the C struct types
dtype = self.find_in_ndarray_type_registry(lhs_dtype)
elif isinstance(lhs.class_type, HomogeneousTupleType):
dtype = self.find_in_ndarray_type_registry(numpy_precision_map[
(lhs_dtype.primitive_type, lhs_dtype.precision)])
else:
raise NotImplementedError(f"Don't know how to index {lhs.class_type} type")
flattened_list = self._flatten_list(arg)
operations = ""
# Get the variable where the data will be copied
if order == "F":
# If the order is F then the data should be copied non-contiguously so a temporary
# variable is required to pass to array_copy_data
temp_var = self.scope.get_temporary_variable(lhs, order='C')
operations += self._print(Allocate(temp_var, shape=lhs.shape, order="C", status="unallocated"))
copy_to = temp_var
else:
copy_to = lhs
copy_to_data_var = DottedVariable(lhs.dtype, dtype, lhs=copy_to)
num_elements = len(flattened_list)
# Get the offset variable if it is needed
if num_elements != 1 and not all(v.rank == 0 for v in flattened_list):
offset_var = self.scope.get_temporary_variable(PythonNativeInt(), 'offset')
operations += self._print(Assign(offset_var, LiteralInteger(0)))
else:
offset_var = LiteralInteger(0)
offset_str = self._print(offset_var)
# Copy each of the elements
i = 0
while i < num_elements:
current_element = flattened_list[i]
# Copy an array element
if isinstance(current_element, (Variable, IndexedElement)) and current_element.rank >= 1:
elem_name = self._print(current_element)
target = self._print(ObjectAddress(copy_to))
operations += f"array_copy_data({target}, {elem_name}, {offset_str});\n"
i += 1
if i < num_elements:
operations += self._print(AugAssign(offset_var, '+', NumpySize(current_element)))
# Copy multiple scalar elements
else:
self.add_import(c_imports['string'])
remaining_elements = flattened_list[i:]
lenSubset = next((i for i,v in enumerate(remaining_elements) if v.rank != 0), len(remaining_elements))
if lenSubset == 0:
errors.report(f"Can't copy {rhs} into {lhs}", symbol=expr,
severity='fatal')
subset = remaining_elements[:lenSubset]
# Declare list of consecutive elements
subset_str = "{" + ', '.join(self._print(elem) for elem in subset) + "}"
dummy_array_name = self.scope.get_new_name()
operations += f"{declare_dtype} {dummy_array_name}[] = {subset_str};\n"
copy_to_data = self._print(copy_to_data_var)
type_size = self._print(DottedVariable(VoidType(), 'type_size', lhs=copy_to))
operations += f"memcpy(&{copy_to_data}[{offset_str}], {dummy_array_name}, {lenSubset} * {type_size});\n"
i += lenSubset
if i < num_elements:
operations += self._print(AugAssign(offset_var, '+', LiteralInteger(lenSubset)))
if order == "F":
operations += f"array_copy_data({lhs_address}, {self._print(copy_to)}, 0);\n" + self._print(Deallocate(copy_to))
return operations
def arrayFill(self, expr):
"""
Print the assignment of a NdArray.
Print the code necessary to create and fill an ndarray.
Parameters
----------
expr : TypedAstNode
The Assign Node used to get the lhs and rhs.
Returns
-------
str
Return a str that contains a call to the C function array_fill.
"""
rhs = expr.rhs
lhs = expr.lhs
code_init = ''
declare_dtype = self.find_in_dtype_registry(rhs.dtype)
if rhs.fill_value is not None:
if isinstance(rhs.fill_value, Literal):
code_init += 'array_fill(({0}){1}, {2});\n'.format(declare_dtype, self._print(rhs.fill_value), self._print(lhs))
else:
code_init += 'array_fill({0}, {1});\n'.format(self._print(rhs.fill_value), self._print(lhs))
return code_init
def _init_stack_array(self, expr):
"""
Return a string which handles the assignment of a stack ndarray.
Print the code necessary to initialise a ndarray on the stack.
Parameters
----------
expr : TypedAstNode
The Assign Node used to get the lhs and rhs.
Returns
-------
buffer_array : str
String initialising the stack (C) array which stores the data.
array_init : str
String containing the rhs of the initialization of a stack array.
"""
var = expr
dtype = self.find_in_dtype_registry(var.dtype)
if isinstance(var.class_type, NumpyNDArrayType):
np_dtype = self.find_in_ndarray_type_registry(var.dtype)
elif isinstance(var.class_type, HomogeneousContainerType):
np_dtype = self.find_in_ndarray_type_registry(numpy_precision_map[(var.dtype.primitive_type, var.dtype.precision)])
else:
raise NotImplementedError(f"Don't know how to index {expr.class_type} type")
shape = ", ".join(self._print(i) for i in var.alloc_shape)
tot_shape = self._print(functools.reduce(
lambda x,y: PyccelMul(x,y,simplify=True), var.alloc_shape))
declare_dtype = self.find_in_dtype_registry(NumpyInt64Type())
dummy_array_name = self.scope.get_new_name('array_dummy')
buffer_array = "{dtype} {name}[{size}];\n".format(
dtype = dtype,
name = dummy_array_name,
size = tot_shape)
shape_init = "({declare_dtype}[]){{{shape}}}".format(declare_dtype=declare_dtype, shape=shape)
strides_init = "({declare_dtype}[{length}]){{0}}".format(declare_dtype=declare_dtype, length=len(var.shape))
array_init = ' = (t_ndarray){{\n.{0}={1},\n .shape={2},\n .strides={3},\n '
array_init += '.nd={4},\n .type={0},\n .is_view={5}\n}};\n'
array_init = array_init.format(np_dtype, dummy_array_name,
shape_init, strides_init, len(var.shape), 'false')
array_init += 'stack_array_init(&{})'.format(self._print(var))
self.add_import(c_imports['ndarrays'])
return buffer_array, array_init
def _handle_inline_func_call(self, expr):
"""
Print a function call to an inline function.
Use the arguments passed to an inline function to print
its body with the passed arguments in place of the function
arguments.
Parameters
----------
expr : FunctionCall
The function call which should be printed inline.
Returns
-------
str
The code for the inline function.
"""
func = expr.funcdef
body = func.body
for b in body.body:
if isinstance(b, ScopedAstNode):
b.scope.update_parent_scope(self.scope, is_loop=True)
# Print any arguments using the same inline function
# As the function definition is modified directly this function
# cannot be called recursively with the same FunctionDef
args = []
for a in expr.args:
if a.is_user_of(func):
code = PrecomputedCode(self._print(a))
args.append(code)
else:
args.append(a.value)
# Create new local variables to ensure there are no name collisions
new_local_vars = [self.scope.get_temporary_variable(v) \
for v in func.local_vars]
parent_assign = expr.get_direct_user_nodes(lambda x: isinstance(x, Assign))
if parent_assign:
results = {r.var : l for r,l in zip(func.results, parent_assign[0].lhs)}
orig_res_vars = list(results.keys())
new_res_vars = self._temporary_args
new_res_vars = [a.obj if isinstance(a, ObjectAddress) else a for a in new_res_vars]
self._temporary_args = []
body.substitute(orig_res_vars, new_res_vars)
# Replace the arguments in the code
func.swap_in_args(args, new_local_vars)
func.remove_presence_checks()
# Collect code but strip empty end
body_code = self._print(body)
code_lines = body_code.split('\n')[:-1]
return_regex = re.compile(r'\breturn\b')
has_results = [return_regex.search(l) is not None for l in code_lines]
if len(func.results) == 0 and not any(has_results):
code = body_code
else:
result_idx = has_results.index(True)
result_line = code_lines[result_idx]
body_code = '\n'.join(code_lines[:result_idx])+'\n'
if len(func.results) != 1:
code = body_code
else:
self._additional_code += body_code
# Strip return and ; from return statement
code = result_line[7:-1]
# Put back original arguments
func.reinstate_presence_checks()
func.swap_out_args()
if parent_assign:
body.substitute(new_res_vars, orig_res_vars)
if func.global_vars or func.global_funcs:
mod = func.get_direct_user_nodes(lambda x: isinstance(x, Module))[0]
self.add_import(Import(mod.name, [AsName(v, v.name) \
for v in (*func.global_vars, *func.global_funcs)]))
for v in (*func.global_vars, *func.global_funcs):
self.scope.insert_symbol(v.name)
for b in body.body:
if isinstance(b, ScopedAstNode):
b.scope.update_parent_scope(func.scope, is_loop=True)
return code
# ============ Elements ============ #
def _print_PythonAbs(self, expr):
if expr.arg.dtype.primitive_type is PrimitiveFloatingPointType():
self.add_import(c_imports['math'])
func = "fabs"
elif expr.arg.dtype.primitive_type is PrimitiveComplexType():
self.add_import(c_imports['complex'])
func = "cabs"
else:
func = "labs"
return "{}({})".format(func, self._print(expr.arg))
def _print_PythonMin(self, expr):
arg = expr.args[0]
if arg.dtype.primitive_type is PrimitiveFloatingPointType() and len(arg) == 2:
self.add_import(c_imports['math'])
return "fmin({}, {})".format(self._print(arg[0]),
self._print(arg[1]))
elif arg.dtype.primitive_type is PrimitiveIntegerType() and len(arg) == 2:
arg1 = self.scope.get_temporary_variable(PythonNativeInt())
arg2 = self.scope.get_temporary_variable(PythonNativeInt())
assign1 = Assign(arg1, arg[0])
assign2 = Assign(arg2, arg[1])
self._additional_code += self._print(assign1)
self._additional_code += self._print(assign2)
return f"({arg1} < {arg2} ? {arg1} : {arg2})"
else:
return errors.report("min in C is only supported for 2 scalar arguments", symbol=expr,
severity='fatal')
def _print_PythonMax(self, expr):
arg = expr.args[0]
if arg.dtype.primitive_type is PrimitiveFloatingPointType() and len(arg) == 2:
self.add_import(c_imports['math'])
return "fmax({}, {})".format(self._print(arg[0]),
self._print(arg[1]))
elif arg.dtype.primitive_type is PrimitiveIntegerType() and len(arg) == 2:
arg1 = self.scope.get_temporary_variable(PythonNativeInt())
arg2 = self.scope.get_temporary_variable(PythonNativeInt())
assign1 = Assign(arg1, arg[0])
assign2 = Assign(arg2, arg[1])
self._additional_code += self._print(assign1)
self._additional_code += self._print(assign2)
return f"({arg1} > {arg2} ? {arg1} : {arg2})"
else:
return errors.report("max in C is only supported for 2 scalar arguments", symbol=expr,
severity='fatal')
def _print_SysExit(self, expr):
code = ""
if not isinstance(getattr(expr.status.dtype, 'primitive_type', None), PrimitiveIntegerType) \
or expr.status.rank > 0:
print_arg = FunctionCallArgument(expr.status)
code = self._print(PythonPrint((print_arg, ), file="stderr"))
arg = "1"
else:
arg = self._print(expr.status)
return f"{code}exit({arg});\n"
def _print_PythonFloat(self, expr):
value = self._print(expr.arg)
type_name = self.find_in_dtype_registry(expr.dtype)
return '({0})({1})'.format(type_name, value)
def _print_PythonInt(self, expr):
self.add_import(c_imports['stdint'])
value = self._print(expr.arg)
type_name = self.find_in_dtype_registry(expr.dtype)
return '({0})({1})'.format(type_name, value)
def _print_PythonBool(self, expr):
value = self._print(expr.arg)
return '({} != 0)'.format(value)
def _print_Literal(self, expr):
return repr(expr.python_value)
def _print_LiteralInteger(self, expr):
if isinstance(expr, LiteralInteger) and getattr(expr.dtype, 'precision', -1) == 8:
self.add_import(c_imports['stdint'])
return f"INT64_C({repr(expr.python_value)})"
return repr(expr.python_value)
def _print_LiteralFloat(self, expr):
if isinstance(expr, LiteralFloat) and expr.dtype.precision == 4:
return f"{repr(expr.python_value)}f"
return repr(expr.python_value)
def _print_LiteralComplex(self, expr):
if expr.real == LiteralFloat(0):
return self._print(PyccelAssociativeParenthesis(PyccelMul(expr.imag, LiteralImaginaryUnit())))
else:
return self._print(PyccelAssociativeParenthesis(PyccelAdd(expr.real,
PyccelMul(expr.imag, LiteralImaginaryUnit()))))
def _print_PythonComplex(self, expr):
if expr.is_cast:
value = self._print(expr.internal_var)
else:
value = self._print(PyccelAssociativeParenthesis(PyccelAdd(expr.real,
PyccelMul(expr.imag, LiteralImaginaryUnit()))))
type_name = self.find_in_dtype_registry(expr.dtype)
return '({0})({1})'.format(type_name, value)
def _print_LiteralImaginaryUnit(self, expr):
self.add_import(c_imports['complex'])
return '_Complex_I'
def _print_Header(self, expr):
return ''
def _print_ModuleHeader(self, expr):
self.set_scope(expr.module.scope)
self._in_header = True
name = expr.module.name
if isinstance(name, AsName):
name = name.name
# TODO: Add interfaces
classes = ""
funcs = ""
for classDef in expr.module.classes:
if classDef.docstring is not None:
classes += self._print(classDef.docstring)
classes += f"struct {classDef.name} {{\n"
classes += ''.join(self._print(Declare(var)) for var in classDef.attributes)
class_scope = classDef.scope
for method in classDef.methods:
if not method.is_inline:
class_scope.rename_function(method, f"{classDef.name}__{method.name.lstrip('__')}")
funcs += f"{self.function_signature(method)};\n"
for interface in classDef.interfaces:
for func in interface.functions:
if not func.is_inline:
class_scope.rename_function(func, f"{classDef.name}__{func.name.lstrip('__')}")
funcs += f"{self.function_signature(func)};\n"
classes += "};\n"
funcs += '\n'.join(f"{self.function_signature(f)};" for f in expr.module.funcs if not f.is_inline)
global_variables = ''.join(['extern '+self._print(d) for d in expr.module.declarations if not d.variable.is_private])
# Print imports last to be sure that all additional_imports have been collected
imports = [*expr.module.imports, *self._additional_imports.values()]
imports = ''.join(self._print(i) for i in imports)
self._in_header = False
self.exit_scope()
return (f"#ifndef {name.upper()}_H\n \
#define {name.upper()}_H\n\n \
{imports}\n \
{global_variables}\n \
{classes}\n \
{funcs}\n \
#endif // {name}_H\n")
def _print_Module(self, expr):
self.set_scope(expr.scope)
self._current_module = expr.name
body = ''.join(self._print(i) for i in expr.body)
global_variables = ''.join([self._print(d) for d in expr.declarations])
# Print imports last to be sure that all additional_imports have been collected
imports = [Import(expr.name, Module(expr.name,(),())), *self._additional_imports.values()]
imports = ''.join(self._print(i) for i in imports)
code = ('{imports}\n'
'{variables}\n'
'{body}\n').format(
imports = imports,
variables = global_variables,
body = body)
self.exit_scope()
return code
def _print_Break(self, expr):
return 'break;\n'
def _print_Continue(self, expr):
return 'continue;\n'
def _print_While(self, expr):
self.set_scope(expr.scope)
body = self._print(expr.body)
self.exit_scope()
cond = self._print(expr.test)
return 'while({condi})\n{{\n{body}}}\n'.format(condi = cond, body = body)
def _print_If(self, expr):
lines = []
for i, (c, e) in enumerate(expr.blocks):
var = self._print(e)
if i == 0:
lines.append("if (%s)\n{\n" % self._print(c))
elif i == len(expr.blocks) - 1 and isinstance(c, LiteralTrue):
lines.append("else\n{\n")
else:
lines.append("else if (%s)\n{\n" % self._print(c))
lines.append("%s}\n" % var)
return "".join(lines)
def _print_IfTernaryOperator(self, expr):
cond = self._print(expr.cond)
value_true = self._print(expr.value_true)
value_false = self._print(expr.value_false)
return '{cond} ? {true} : {false}'.format(cond = cond, true =value_true, false = value_false)
def _print_LiteralTrue(self, expr):
return '1'
def _print_LiteralFalse(self, expr):
return '0'
def _print_PyccelAnd(self, expr):
args = [self._print(a) for a in expr.args]
return ' && '.join(a for a in args)
def _print_PyccelOr(self, expr):
args = [self._print(a) for a in expr.args]
return ' || '.join(a for a in args)
def _print_PyccelEq(self, expr):
lhs = self._print(expr.args[0])
rhs = self._print(expr.args[1])
return '{0} == {1}'.format(lhs, rhs)
def _print_PyccelNe(self, expr):
lhs = self._print(expr.args[0])
rhs = self._print(expr.args[1])
return '{0} != {1}'.format(lhs, rhs)
def _print_PyccelLt(self, expr):
lhs = self._print(expr.args[0])
rhs = self._print(expr.args[1])
return '{0} < {1}'.format(lhs, rhs)
def _print_PyccelLe(self, expr):
lhs = self._print(expr.args[0])
rhs = self._print(expr.args[1])
return '{0} <= {1}'.format(lhs, rhs)
def _print_PyccelGt(self, expr):
lhs = self._print(expr.args[0])
rhs = self._print(expr.args[1])
return '{0} > {1}'.format(lhs, rhs)
def _print_PyccelGe(self, expr):
lhs = self._print(expr.args[0])
rhs = self._print(expr.args[1])
return '{0} >= {1}'.format(lhs, rhs)
def _print_PyccelNot(self, expr):
a = self._print(expr.args[0])
return '!{}'.format(a)
def _print_PyccelMod(self, expr):
self.add_import(c_imports['math'])
self.add_import(c_imports['pyc_math_c'])
first = self._print(expr.args[0])
second = self._print(expr.args[1])
if expr.dtype.primitive_type is PrimitiveIntegerType():
return "pyc_modulo({n}, {base})".format(n=first, base=second)
if expr.args[0].dtype.primitive_type is PrimitiveIntegerType():
first = self._print(NumpyFloat(expr.args[0]))
if expr.args[1].dtype.primitive_type is PrimitiveIntegerType():
second = self._print(NumpyFloat(expr.args[1]))
return "pyc_fmodulo({n}, {base})".format(n=first, base=second)
def _print_PyccelPow(self, expr):
b = expr.args[0]
e = expr.args[1]
if expr.dtype.primitive_type is PrimitiveComplexType():
b = self._print(b if b.dtype.primitive_type is PrimitiveComplexType() else PythonComplex(b))
e = self._print(e if e.dtype.primitive_type is PrimitiveComplexType() else PythonComplex(e))
self.add_import(c_imports['complex'])
return 'cpow({}, {})'.format(b, e)
self.add_import(c_imports['math'])
b = self._print(b if b.dtype.primitive_type is PrimitiveFloatingPointType() else NumpyFloat(b))
e = self._print(e if e.dtype.primitive_type is PrimitiveFloatingPointType() else NumpyFloat(e))
code = 'pow({}, {})'.format(b, e)
return self._cast_to(expr, expr.dtype).format(code)
def _print_Import(self, expr):
if expr.ignore:
return ''
if isinstance(expr.source, AsName):
source = expr.source.name
else:
source = expr.source
if isinstance(source, DottedName):
source = source.name[-1]
else:
source = self._print(source)
# Get with a default value is not used here as it is
# slower and on most occasions the import will not be in the
# dictionary
if source in import_dict: # pylint: disable=consider-using-get
source = import_dict[source]
if expr.source_module:
for classDef in expr.source_module.classes:
class_scope = classDef.scope
for method in classDef.methods:
if not method.is_inline:
class_scope.rename_function(method, f"{classDef.name}__{method.name.lstrip('__')}")
for interface in classDef.interfaces:
for func in interface.functions:
if not func.is_inline:
class_scope.rename_function(func, f"{classDef.name}__{func.name.lstrip('__')}")
if source is None:
return ''
if expr.source in c_library_headers:
return '#include <{0}.h>\n'.format(source)
else:
return '#include "{0}.h"\n'.format(source)
def _print_LiteralString(self, expr):
format_str = format(expr.python_value)
format_str = format_str.replace("\\", "\\\\")\
.replace('\a', '\\a')\
.replace('\b', '\\b')\
.replace('\f', '\\f')\
.replace("\n", "\\n")\
.replace('\r', '\\r')\
.replace('\t', '\\t')\
.replace('\v', '\\v')\
.replace('"', '\\"')\
.replace("'", "\\'")
return '"{}"'.format(format_str)
def get_print_format_and_arg(self, var):
"""
Get the C print format string for the object var.
Get the C print format string which will allow the generated code
to print the variable passed as argument.
Parameters
----------
var : TypedAstNode
The object which will be printed.
Returns
-------
arg_format : str
The format which should be printed in the format string of the