-
Notifications
You must be signed in to change notification settings - Fork 55
/
fcode.py
3275 lines (2674 loc) · 122 KB
/
fcode.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. #
#------------------------------------------------------------------------------------------#
"""Print to F90 standard. Trying to follow the information provided at
www.fortran90.org as much as possible."""
import functools
import string
import re
from collections import OrderedDict
from itertools import chain
import numpy as np
from pyccel.ast.basic import TypedAstNode
from pyccel.ast.bind_c import BindCPointer, BindCFunctionDef, BindCFunctionDefArgument, BindCModule, BindCClassDef
from pyccel.ast.builtins import PythonInt, PythonType, PythonPrint, PythonRange
from pyccel.ast.builtins import PythonTuple, DtypePrecisionToCastFunction
from pyccel.ast.builtins import PythonBool, PythonAbs
from pyccel.ast.core import FunctionDef
from pyccel.ast.core import SeparatorComment, Comment
from pyccel.ast.core import ConstructorCall
from pyccel.ast.core import FunctionCallArgument
from pyccel.ast.core import FunctionAddress
from pyccel.ast.core import Return, Module, For
from pyccel.ast.core import Import, CodeBlock, AsName, EmptyNode
from pyccel.ast.core import Assign, AliasAssign, Declare, Deallocate
from pyccel.ast.core import FunctionCall, PyccelFunctionDef
from pyccel.ast.datatypes import PrimitiveBooleanType, PrimitiveIntegerType, PrimitiveFloatingPointType, PrimitiveComplexType
from pyccel.ast.datatypes import SymbolicType, StringType, FixedSizeNumericType
from pyccel.ast.datatypes import PythonNativeInt
from pyccel.ast.datatypes import CustomDataType, InhomogeneousTupleType
from pyccel.ast.datatypes import pyccel_type_to_original_type
from pyccel.ast.internals import Slice, PrecomputedCode, PyccelArrayShapeElement
from pyccel.ast.itertoolsext import Product
from pyccel.ast.literals import LiteralInteger, LiteralFloat, Literal, LiteralEllipsis
from pyccel.ast.literals import LiteralTrue, LiteralFalse, LiteralString
from pyccel.ast.literals import Nil
from pyccel.ast.mathext import math_constants
from pyccel.ast.numpyext import NumpyEmpty, NumpyInt32
from pyccel.ast.numpyext import NumpyFloat, NumpyBool
from pyccel.ast.numpyext import NumpyReal, NumpyImag
from pyccel.ast.numpyext import NumpyRand
from pyccel.ast.numpyext import NumpyNewArray
from pyccel.ast.numpyext import NumpyNonZero
from pyccel.ast.numpyext import NumpySign
from pyccel.ast.numpyext import NumpyIsFinite, NumpyIsNan
from pyccel.ast.operators import PyccelAdd, PyccelMul, PyccelMinus, PyccelAnd
from pyccel.ast.operators import PyccelMod, PyccelNot, PyccelAssociativeParenthesis
from pyccel.ast.operators import PyccelUnarySub, PyccelLt, PyccelGt, IfTernaryOperator
from pyccel.ast.utilities import builtin_import_registry as pyccel_builtin_import_registry
from pyccel.ast.utilities import expand_to_loops
from pyccel.ast.variable import Variable, IndexedElement, InhomogeneousTupleVariable, DottedName
from pyccel.errors.errors import Errors
from pyccel.errors.messages import *
from pyccel.codegen.printing.codeprinter import CodePrinter
# TODO: add examples
# TODO: use _get_statement when returning a string
__all__ = ["FCodePrinter", "fcode"]
numpy_ufunc_to_fortran = {
'NumpyAbs' : 'abs',
'NumpyFabs' : 'abs',
'NumpyFloor': 'floor', # TODO: might require special treatment with casting
# ---
'NumpyExp' : 'exp',
'NumpyLog' : 'Log',
# 'NumpySqrt': 'Sqrt', # sqrt is printed using _Print_NumpySqrt
# ---
'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',
'NumpyIsFinite':'ieee_is_finite',
'NumpyIsNan' :'ieee_is_nan',
}
math_function_to_fortran = {
'MathAcos' : 'acos',
'MathAcosh' : 'acosh',
'MathAsin' : 'asin',
'MathAsinh' : 'asinh',
'MathAtan' : 'atan',
'MathAtan2' : 'atan2',
'MathAtanh' : 'atanh',
'MathCopysign': 'sign',
'MathCos' : 'cos',
'MathCosh' : 'cosh',
'MathErf' : 'erf',
'MathErfc' : 'erfc',
'MathExp' : 'exp',
# 'MathExpm1' : '???', # TODO
'MathFabs' : 'abs',
# 'MathFmod' : '???', # TODO
# 'MathFsum' : '???', # TODO
'MathGamma' : 'gamma',
'MathHypot' : 'hypot',
# 'MathLdexp' : '???', # TODO
'MathLgamma' : 'log_gamma',
'MathLog' : 'log',
'MathLog10' : 'log10',
# 'MathLog1p' : '???', # TODO
# 'MathLog2' : '???', # TODO
# 'MathPow' : '???', # TODO
'MathSin' : 'sin',
'MathSinh' : 'sinh',
'MathSqrt' : 'sqrt',
'MathTan' : 'tan',
'MathTanh' : 'tanh',
# ---
'MathFloor' : 'floor',
# ---
# 'MathIsclose' : '???', # TODO
# 'MathIsfinite': '???', # TODO
# 'MathIsinf' : '???', # TODO
# --------------------------- internal functions --------------------------
'MathFactorial' : 'pyc_factorial',
'MathGcd' : 'pyc_gcd',
'MathDegrees' : 'pyc_degrees',
'MathRadians' : 'pyc_radians',
'MathLcm' : 'pyc_lcm',
# --------------------------- cmath functions --------------------------
'CmathAcos' : 'acos',
'CmathAcosh' : 'acosh',
'CmathAsin' : 'asin',
'CmathAsinh' : 'asinh',
'CmathAtan' : 'atan',
'CmathAtanh' : 'atanh',
'CmathCos' : 'cos',
'CmathCosh' : 'cosh',
'CmathExp' : 'exp',
'CmathSin' : 'sin',
'CmathSinh' : 'sinh',
'CmathSqrt' : 'sqrt',
'CmathTan' : 'tan',
'CmathTanh' : 'tanh',
}
INF = math_constants['inf']
_default_methods = {
'__new__' : 'alloc',
'__init__': 'create',
'__del__' : 'free',
}
#==============================================================================
iso_c_binding = {
PrimitiveIntegerType() : {
1 : 'C_INT8_T',
2 : 'C_INT16_T',
4 : 'C_INT32_T',
8 : 'C_INT64_T',
16 : 'C_INT128_T'}, #not supported yet
PrimitiveFloatingPointType() : {
4 : 'C_FLOAT',
8 : 'C_DOUBLE',
16 : 'C_LONG_DOUBLE'}, #not supported yet
PrimitiveComplexType() : {
4 : 'C_FLOAT_COMPLEX',
8 : 'C_DOUBLE_COMPLEX',
16 : 'C_LONG_DOUBLE_COMPLEX'}, #not supported yet
PrimitiveBooleanType() : {
-1 : "C_BOOL"}
}
iso_c_binding_shortcut_mapping = {
'C_INT8_T' : 'i8',
'C_INT16_T' : 'i16',
'C_INT32_T' : 'i32',
'C_INT64_T' : 'i64',
'C_INT128_T' : 'i128',
'C_FLOAT' : 'f32',
'C_DOUBLE' : 'f64',
'C_LONG_DOUBLE' : 'f128',
'C_FLOAT_COMPLEX' : 'c32',
'C_DOUBLE_COMPLEX' : 'c64',
'C_LONG_DOUBLE_COMPLEX' : 'c128',
'C_BOOL' : 'b1'
}
inc_keyword = (r'do\b', r'if\b',
r'else\b', r'type\b\s*[^\(]',
r'(elemental )?(pure )?(recursive )?((subroutine)|(function))\b',
r'interface\b',r'module\b(?! *procedure)',r'program\b')
inc_regex = re.compile('|'.join('({})'.format(i) for i in inc_keyword))
end_keyword = ('do', 'if', 'type', 'function',
'subroutine', 'interface','module','program')
end_regex_str = '(end ?({}))|(else)'.format('|'.join('({})'.format(k) for k in end_keyword))
dec_regex = re.compile(end_regex_str)
errors = Errors()
class FCodePrinter(CodePrinter):
"""
A printer for printing code in Fortran.
A printer to convert Pyccel's AST to strings of Fortran 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 = "_fcode"
language = "Fortran"
_default_settings = {
'tabwidth': 2,
}
def __init__(self, filename, prefix_module = None):
errors.set_target(filename, 'file')
super().__init__()
self._constantImports = {}
self._current_class = None
self._additional_code = None
self._additional_imports = set()
self.prefix_module = prefix_module
def print_constant_imports(self):
"""Prints the use line for the constant imports used"""
macros = []
for (name, imports) in self._constantImports.items():
macro = f"use, intrinsic :: {name}, only : "
rename = [c if isinstance(c, str) else c[0] + ' => ' + c[1] for c in imports]
if len(rename) == 0:
continue
macro += " , ".join(rename)
macros.append(macro)
return "\n".join(macros)
def get_additional_imports(self):
"""return the additional modules collected for importing in printing stage"""
return [i.source for i in self._additional_imports]
def set_current_class(self, name):
self._current_class = name
def get_method(self, cls_name, method_name):
container = self.scope
while container:
if cls_name in container.classes:
cls = container.classes[cls_name]
methods = cls.methods_as_dict
if method_name in methods:
return methods[method_name]
else:
interface_funcs = {f.name:f for i in cls.interfaces for f in i.functions}
if method_name in interface_funcs:
return interface_funcs[method_name]
errors.report(UNDEFINED_METHOD, symbol=method_name,
severity='fatal')
container = container.parent_scope
if isinstance(method_name, DottedName):
return self.get_function(DottedName(method_name.name[1:]))
errors.report(UNDEFINED_FUNCTION, symbol=method_name,
severity='fatal')
def get_function(self, name):
container = self.scope
while container:
if name in container.functions:
return container.functions[name]
container = container.parent_scope
if isinstance(name, DottedName):
return self.get_function(name.name[-1])
errors.report(UNDEFINED_FUNCTION, symbol=name,
severity='fatal')
def _get_statement(self, codestring):
return codestring
def _format_code(self, lines):
return self._wrap_fortran(self.indent_code(lines))
def print_kind(self, expr):
"""
Print the kind(precision) of a literal value or its shortcut if possible.
Print the kind(precision) of a literal value or its shortcut if possible.
Parameters
----------
expr : TypedAstNode
The object whose precision should be investigated.
Returns
-------
str
The code for the kind parameter.
"""
dtype = expr.dtype
constant_name = iso_c_binding[dtype.primitive_type][dtype.precision]
constant_shortcut = iso_c_binding_shortcut_mapping[constant_name]
if constant_shortcut not in self.scope.all_used_symbols and constant_name != constant_shortcut:
self._constantImports.setdefault('ISO_C_Binding', set())\
.add((constant_shortcut, constant_name))
constant_name = constant_shortcut
else:
self._constantImports.setdefault('ISO_C_Binding', set())\
.add(constant_name)
return constant_name
def _handle_inline_func_call(self, expr, assign_lhs = None):
"""
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.
assign_lhs : List
A list of lhs provided.
Returns
-------
str
The code for the inline function.
"""
scope = self.scope
func = expr.funcdef
# 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 = [v.clone(self.scope.get_new_name(v.name)) \
for v in func.local_vars]
for v in new_local_vars:
self.scope.insert_variable(v)
# Put functions into current scope
for entry in ['variables', 'classes', 'functions']:
self.scope.imports[entry].update(func.namespace_imports[entry])
func.swap_in_args(args, new_local_vars)
func.remove_presence_checks()
body = func.body
if len(func.results) == 0:
# If there is no return then the code is already ok
code = self._print(body)
else:
# Search for the return and replace it with an empty node
result = body.get_attribute_nodes(Return)[0]
empty_return = EmptyNode()
body.substitute(result, empty_return, invalidate = False)
# Everything before the return node needs handling before the line
# which calls the inline function is executed
code = self._print(body)
if (not self._additional_code):
self._additional_code = ''
self._additional_code += code
# Collect statements from results to return object
if result.stmt:
assigns = {i.lhs: i.rhs for i in result.stmt.body if isinstance(i, Assign)}
self._additional_code += ''.join([self._print(i) for i in result.stmt.body if not isinstance(i, Assign)])
else:
assigns = {}
# Put return statement back into function
body.substitute(empty_return, result)
if assign_lhs:
assigns = [Assign(l, r) for l,r in zip(assign_lhs, assigns.values())]
code = ''.join([self._print(a) for a in assigns])
else:
res_return_vars = [assigns.get(v,v) for v in result.expr]
if len(res_return_vars) == 1:
return_val = res_return_vars[0]
parent_assign = return_val.get_direct_user_nodes(lambda x: isinstance(x, Assign))
if parent_assign:
return_val.remove_user_node(parent_assign[0], invalidate = False)
code = self._print(return_val)
return_val.set_current_user_node(parent_assign[0])
else:
code = self._print(return_val)
else:
code = self._print(tuple(res_return_vars))
# Put back original arguments
func.reinstate_presence_checks()
func.swap_out_args()
self._additional_imports.update(func.imports)
if func.global_vars or func.global_funcs:
mod = func.get_direct_user_nodes(lambda x: isinstance(x, Module))[0]
current_mod = expr.get_user_nodes(Module, excluded_nodes=(FunctionCall,))[0]
if current_mod is not mod:
self._additional_imports.add(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)
self.set_scope(scope)
return code
def _get_external_declarations(self, decs):
"""
Find external functions and declare their result type.
Look for any external functions in the local imports from
the scope and use their definitions to create declarations
from the results. These declarations are stored in the list
passed as argument.
Parameters
----------
decs : list
The list where the declarations necessary to use the external
functions will be stored.
"""
for key,f in self.scope.imports['functions'].items():
if isinstance(f, FunctionDef) and f.is_external:
v = f.results[0].var.clone(str(key))
decs.append(Declare(v, external=True))
def _calculate_class_names(self, expr):
"""
Calculate the class names of the functions in a class.
Calculate the names that will be referenced from the class
for each function in a class. Also rename magic methods.
Parameters
----------
expr : ClassDef
The class whose functions should be renamed.
"""
scope = expr.scope
name = expr.name.lower()
for method in expr.methods:
if not method.is_inline:
m_name = method.name
if m_name in _default_methods:
suggested_name = _default_methods[m_name]
scope.rename_function(method, suggested_name)
method.cls_name = scope.get_new_name(f'{name}_{method.name}')
for i in expr.interfaces:
for f in i.functions:
if not f.is_inline:
i_name = f.name
if i_name in _default_methods:
suggested_name = _default_methods[i_name]
scope.rename_function(f, suggested_name)
f.cls_name = scope.get_new_name(f'{name}_{f.name}')
# ============ Elements ============ #
def _print_PyccelSymbol(self, expr):
return expr
def _print_Module(self, expr):
self.set_scope(expr.scope)
if isinstance(expr.name, AsName):
name = self._print(expr.name.target)
else:
name = self._print(expr.name)
name = name.replace('.', '_')
if not name.startswith('mod_') and self.prefix_module:
name = f'{self.prefix_module}_{name}'
imports = ''.join(self._print(i) for i in expr.imports)
# Define declarations
decs = ''
# ...
for c in expr.classes:
if not isinstance(c, BindCClassDef):
self._calculate_class_names(c)
class_decs_and_methods = [self._print(i) for i in expr.classes]
decs += '\n'.join(c[0] for c in class_decs_and_methods)
# ...
declarations = list(expr.declarations)
# look for external functions and declare their result type
self._get_external_declarations(declarations)
decs += ''.join(self._print(d) for d in declarations)
# ... TODO add other elements
private_funcs = [f.name for f in expr.funcs if f.is_private]
private = private_funcs
if private:
private = ','.join(self._print(i) for i in private)
private = 'private :: {}\n'.format(private)
else:
private = ''
# ...
# ...
sep = self._print(SeparatorComment(40))
interfaces = ''
if expr.interfaces and not isinstance(expr, BindCModule):
interfaces = '\n'.join(self._print(i) for i in expr.interfaces)
func_strings = []
# Get class functions
func_strings += [c[1] for c in class_decs_and_methods]
if expr.funcs:
func_strings += [''.join([sep, self._print(i), sep]) for i in expr.funcs]
if isinstance(expr, BindCModule):
func_strings += [''.join([sep, self._print(i), sep]) for i in expr.variable_wrappers]
body = '\n'.join(func_strings)
# ...
contains = 'contains\n' if (expr.funcs or expr.classes or expr.interfaces) else ''
imports += ''.join(self._print(i) for i in self._additional_imports)
imports += "\n" + self.print_constant_imports()
parts = ['module {}\n'.format(name),
imports,
'implicit none\n',
private,
decs,
interfaces,
contains,
body,
'end module {}\n'.format(name)]
self.exit_scope()
return '\n'.join([a for a in parts if a])
def _print_Program(self, expr):
self.set_scope(expr.scope)
name = 'prog_{0}'.format(self._print(expr.name)).replace('.', '_')
imports = ''.join(self._print(i) for i in expr.imports)
body = self._print(expr.body)
# Print the declarations of all variables in the scope, which include:
# - user-defined variables (available in Program.variables)
# - pyccel-generated variables added to Scope when printing 'expr.body'
variables = self.scope.variables.values()
decs = ''.join(self._print(Declare(v)) for v in variables)
# Detect if we are using mpi4py
# TODO should we find a better way to do this?
mpi = any('mpi4py' == str(getattr(i.source, 'name', i.source)) for i in expr.imports)
# Additional code and variable declarations for MPI usage
# TODO: check if we should really add them like this
if mpi:
body = 'call mpi_init(ierr)\n'+\
'\nallocate(status(0:-1 + mpi_status_size)) '+\
'\nstatus = 0\n'+\
body +\
'\ncall mpi_finalize(ierr)'
decs += '\ninteger :: ierr = -1' +\
'\ninteger, allocatable :: status (:)'
imports += ''.join(self._print(i) for i in self._additional_imports)
imports += "\n" + self.print_constant_imports()
parts = ['program {}\n'.format(name),
imports,
'implicit none\n',
decs,
body,
'end program {}\n'.format(name)]
self.exit_scope()
return '\n'.join(a for a in parts if a)
def _print_Import(self, expr):
source = ''
if expr.ignore:
return ''
if isinstance(expr.source, AsName):
source = expr.source.target
else:
source = expr.source
if isinstance(source, DottedName):
source = source.name[-1]
else:
source = self._print(source)
# importing of pyccel extensions is not printed
if source in pyccel_builtin_import_registry:
return ''
if expr.source_module:
source = expr.source_module.scope.get_expected_name(source)
if 'mpi4py' == str(getattr(expr.source,'name',expr.source)):
return 'use mpi\n' + 'use mpiext\n'
targets = [t for t in expr.target if not isinstance(t.object, Module)]
if len(targets) == 0:
return 'use {}\n'.format(source)
targets = [t for t in targets if not getattr(t.object, 'is_inline', False)]
if len(targets) == 0:
return ''
prefix = 'use {}, only:'.format(source)
code = ''
for i in targets:
old_name = i.name
new_name = i.target
if old_name != new_name:
target = '{target} => {name}'.format(target=new_name,
name=old_name)
line = '{prefix} {target}'.format(prefix=prefix,
target=target)
elif isinstance(new_name, DottedName):
target = '_'.join(self._print(j) for j in new_name.name)
line = '{prefix} {target}'.format(prefix=prefix,
target=target)
elif isinstance(new_name, str):
line = '{prefix} {target}'.format(prefix=prefix,
target=new_name)
else:
raise TypeError('Expecting str, PyccelSymbol, DottedName or AsName, '
'given {}'.format(type(i)))
code = (code + '\n' + line) if code else line
# in some cases, the source is given as a string (when using metavar)
code = code.replace("'", '')
return self._get_statement(code) + '\n'
def _print_PythonPrint(self, expr):
end = LiteralString('\n')
sep = LiteralString(' ')
code = ''
empty_end = FunctionCallArgument(LiteralString(''), 'end')
space_end = FunctionCallArgument(LiteralString(' '), 'end')
empty_sep = FunctionCallArgument(LiteralString(''), 'sep')
for f in expr.expr:
if f.has_keyword:
if f.keyword == 'sep':
sep = f.value
elif f.keyword == 'end':
end = f.value
else:
errors.report("{} not implemented as a keyworded argument".format(f.keyword), severity='fatal')
args_format = []
args = []
orig_args = [f for f in expr.expr if not f.has_keyword]
separator = self._print(sep)
tuple_start = FunctionCallArgument(LiteralString('('))
tuple_sep = LiteralString(', ')
tuple_end = FunctionCallArgument(LiteralString(')'))
for i, f in enumerate(orig_args):
if f.keyword:
continue
else:
f = f.value
if isinstance(f, (InhomogeneousTupleVariable, PythonTuple, str)):
if args_format:
code += self._formatted_args_to_print(args_format, args, sep, separator, expr)
args_format = []
args = []
if i + 1 == len(orig_args):
end_of_tuple = empty_end
else:
end_of_tuple = FunctionCallArgument(sep, 'end')
args = [FunctionCallArgument(print_arg) for tuple_elem in f for print_arg in (tuple_elem, tuple_sep)][:-1]
if len(f) == 1:
args.append(FunctionCallArgument(LiteralString(',')))
code += self._print(PythonPrint([tuple_start, *args, tuple_end, empty_sep, end_of_tuple], file=expr.file))
args = []
elif isinstance(f, PythonType):
args_format.append('A')
args.append(self._print(f.print_string))
elif f.rank > 0 and not isinstance(f, FunctionCall):
if args_format:
code += self._formatted_args_to_print(args_format, args, sep, separator, expr)
args_format = []
args = []
loop_scope = self.scope.create_new_loop_scope()
for_index = self.scope.get_temporary_variable(PythonNativeInt(), name='i')
max_index = PyccelMinus(f.shape[0], LiteralInteger(1), simplify=True)
for_range = PythonRange(max_index)
print_body = [FunctionCallArgument(f[for_index])]
if f.rank == 1:
print_body.append(space_end)
for_body = [PythonPrint(print_body, file=expr.file)]
for_loop = For(for_index, for_range, for_body, scope=loop_scope)
for_end_char = LiteralString(']')
for_end = FunctionCallArgument(for_end_char,
keyword='end')
body = CodeBlock([PythonPrint([FunctionCallArgument(LiteralString('[')), empty_end],
file=expr.file),
for_loop,
PythonPrint([FunctionCallArgument(f[max_index]), for_end],
file=expr.file)],
unravelled=True)
code += self._print(body)
else:
arg_format, arg = self._get_print_format_and_arg(f)
args_format.append(arg_format)
args.append(arg)
code += self._formatted_args_to_print(args_format, args, end, separator, expr)
return code
def _formatted_args_to_print(self, fargs_format, fargs, fend, fsep, expr):
"""
Produce a write statement from all necessary information.
Produce a write statement from a list of formats, arguments, an end
statement, and a separator.
Parameters
----------
fargs_format : iterable
The format strings for the objects described by fargs.
fargs : iterable
The arguments to be printed.
fend : TypedAstNode
The character describing the end of the line.
fsep : TypedAstNode
The character describing the separator between elements.
expr : TypedAstNode
The PythonPrint currently printed.
Returns
-------
str
The Fortran code describing the write statement.
"""
if fargs_format == ['*']:
# To print the result of a FunctionCall
return ', '.join(['print *', *fargs]) + '\n'
args_list = [a_c if a_c != '' else "''" for a_c in fargs]
fend_code = self._print(fend)
advance = "yes" if fend_code == 'ACHAR(10)' else "no"
if fsep != '':
fargs_format = [af for a in fargs_format for af in (a, 'A')][:-1]
args_list = [af for a in args_list for af in (a, fsep)][:-1]
if fend_code not in ('ACHAR(10)', ''):
fargs_format.append('A')
args_list.append(fend_code)
args_code = ' , '.join(args_list)
args_formatting = ', '.join(fargs_format)
if expr.file == "stderr":
self._constantImports.setdefault('ISO_FORTRAN_ENV', set())\
.add(("stderr", "error_unit"))
return f"write(stderr, '({args_formatting})', advance=\"{advance}\") {args_code}\n"
self._constantImports.setdefault('ISO_FORTRAN_ENV', set())\
.add(("stdout", "output_unit"))
return f"write(stdout, '({args_formatting})', advance=\"{advance}\") {args_code}\n"
def _get_print_format_and_arg(self, var, var_code = None):
"""
Get the format string and the printable argument for an object.
Get the format string and the printable argument for an object.
In other words get arg_format and arg such that var can be printed
by doing:
> write(*, arg_format) arg
Parameters
----------
var : TypedAstNode
The object to be printed.
var_code : str, optional
The code which will print the variable (this is mostly useful when calling
this function recursively, e.g. to print an inhomogenoeus tuple of function
call results).
Returns
-------
arg_format : str
The format string.
arg : str
The Fortran code which represents var.
"""
if var_code is None:
var_code = self._print(var)
arg = var_code
var_type = var.dtype
if isinstance(var.class_type, StringType):
arg_format = 'A'
elif isinstance(var, FunctionCall) and len(var.funcdef.results)>1 or \
isinstance(var.class_type, InhomogeneousTupleType):
var_elem_code = var_code[1:-1].split(', ')
args_and_formats = [self._get_print_format_and_arg(v.var, c) for v,c in zip(var.funcdef.results, var_elem_code)]
formats = ',", ",'.join(af[0] for af in args_and_formats)
arg_format = f'"(",{formats},")"'
arg = ', '.join(af[1] for af in args_and_formats)
elif isinstance(var_type, FixedSizeNumericType):
if isinstance(var_type.primitive_type, PrimitiveComplexType):
float_format, real_arg = self._get_print_format_and_arg(NumpyReal(var))
imag_arg = self._print(NumpyImag(var))
arg_format = f'"(",{float_format}," + ",{float_format},"j)"'
arg = f'{real_arg}, {imag_arg}'
elif isinstance(var_type.primitive_type, PrimitiveFloatingPointType):
dps = np.finfo(pyccel_type_to_original_type[var_type]).precision
arg_format = f'F0.{dps}'
elif isinstance(var_type.primitive_type, PrimitiveIntegerType):
arg_format = 'I0'
elif isinstance(var_type.primitive_type, PrimitiveBooleanType):
arg_format = 'A'
if isinstance(var, LiteralTrue):
arg = "'True'"
elif isinstance(var, LiteralFalse):
arg = "'False'"
else:
arg = f'merge("True ", "False", {var_code})'
else:
errors.report(f"Printing {var_type} type is not supported currently", severity='fatal')
else:
errors.report(f"Printing {var_type} type is not supported currently", severity='fatal')
return arg_format, arg
def _print_SymbolicPrint(self, expr):
# for every expression we will generate a print
code = '\n'.join("print *, 'sympy> {}'".format(a) for a in expr.expr)
return self._get_statement(code) + '\n'
def _print_Comment(self, expr):
comments = self._print(expr.text)
return '!' + comments + '\n'
def _print_CommentBlock(self, expr):
txts = expr.comments
header = expr.header
header_size = len(expr.header)
ln = max(len(i) for i in txts)
if ln<max(20, header_size+2):
ln = 20
top = '!' + '_'*int((ln-header_size)/2) + header + '_'*int((ln-header_size)/2) + '!'
ln = len(top) - 2
bottom = '!' + '_'*ln + '!'
txts = ['!' + txt + ' '*(ln - len(txt)) + '!' for txt in txts]
body = '\n'.join(i for i in txts)
return ('{0}\n'
'{1}\n'
'{2}\n').format(top, body, bottom)
def _print_EmptyNode(self, expr):
return ''
def _print_AnnotatedComment(self, expr):
accel = self._print(expr.accel)
txt = str(expr.txt)
return '!${0} {1}\n'.format(accel, txt)
def _print_tuple(self, expr):
if expr[0].rank>0:
raise NotImplementedError(' tuple with elements of rank > 0 is not implemented')
fs = ', '.join(self._print(f) for f in expr)
return '[{0}]'.format(fs)
def _print_PythonAbs(self, expr):
""" print the python builtin function abs
args : variable
"""
return "abs({})".format(self._print(expr.arg))
def _print_PythonTuple(self, expr):
shape = tuple(reversed(expr.shape))
if len(shape)>1:
elements = ', '.join(self._print(i) for i in expr)
shape = ', '.join(self._print(i) for i in shape)
return 'reshape(['+ elements + '], '+ '[' + shape + ']' + ')'
fs = ', '.join(self._print(f) for f in expr)
return '[{0}]'.format(fs)
def _print_PythonList(self, expr):
return self._print_PythonTuple(expr)
def _print_InhomogeneousTupleVariable(self, expr):
fs = ', '.join(self._print(f) for f in expr)
return '[{0}]'.format(fs)
def _print_Variable(self, expr):
return self._print(expr.name)
def _print_FunctionDefArgument(self, expr):
return self._print(expr.name)
def _print_FunctionCallArgument(self, expr):
if expr.keyword:
return '{} = {}'.format(expr.keyword, self._print(expr.value))
else:
return '{}'.format(self._print(expr.value))
def _print_Constant(self, expr):
val = LiteralFloat(expr.value)
return self._print(val)
def _print_DottedVariable(self, expr):
if isinstance(expr.lhs, FunctionCall):
base = expr.lhs.funcdef.results[0].var
if (not self._additional_code):
self._additional_code = ''
var_name = self.scope.get_new_name()
var = base.clone(var_name)
self.scope.insert_variable(var)
self._additional_code = self._additional_code + self._print(Assign(var,expr.lhs)) + '\n'
return self._print(var) + '%' +self._print(expr.name)
else:
return self._print(expr.lhs) + '%' +self._print(expr.name)
def _print_DottedName(self, expr):
return ' % '.join(self._print(n) for n in expr.name)
def _print_Lambda(self, expr):
return '"{args} -> {expr}"'.format(args=expr.variables, expr=expr.expr)
def _print_PythonSum(self, expr):
args = [self._print(arg) for arg in expr.args]
return "sum({})".format(", ".join(args))
def _print_PythonReal(self, expr):
value = self._print(expr.internal_var)
return 'real({0})'.format(value)
def _print_PythonImag(self, expr):
value = self._print(expr.internal_var)
return 'aimag({0})'.format(value)