-
Notifications
You must be signed in to change notification settings - Fork 56
/
utilities.py
676 lines (575 loc) · 28.7 KB
/
utilities.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
#!/usr/bin/python
# -*- 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 inspect
import sys
from itertools import chain
from collections import namedtuple
from numpy import pi
import pyccel.decorators as pyccel_decorators
from pyccel.symbolic import lambdify
from pyccel.errors.errors import Errors, PyccelError
from .core import (AsName, Import, FunctionDef, FunctionCall,
Allocate, Duplicate, Assign, For, CodeBlock,
Concatenate)
from .builtins import (builtin_functions_dict, PythonMap,
PythonRange, PythonList, PythonTuple)
from .internals import PyccelInternalFunction, Slice
from .itertoolsext import Product
from .mathext import math_functions, math_constants
from .literals import LiteralString, LiteralInteger, Literal, Nil
from .numpyext import (NumpyEmpty, numpy_functions, numpy_linalg_functions,
numpy_random_functions, numpy_constants, NumpyArray,
NumpyTranspose)
from .operators import PyccelAdd, PyccelMul, PyccelIs, PyccelArithmeticOperator
from .variable import (Constant, Variable, ValuedVariable,
IndexedElement, InhomogeneousTupleVariable, VariableAddress,
HomogeneousTupleVariable )
errors = Errors()
__all__ = (
'builtin_function',
'builtin_import',
'builtin_import_registery',
'split_positional_keyword_arguments',
)
scipy_constants = {
'pi': Constant('real', 'pi', value=pi),
}
#==============================================================================
def builtin_function(expr, args=None):
"""Returns a builtin-function call applied to given arguments."""
if isinstance(expr, FunctionCall):
name = str(expr.funcdef)
elif isinstance(expr, str):
name = expr
else:
raise TypeError('expr must be of type str or FunctionCall')
dic = builtin_functions_dict
if name in dic.keys() :
try:
return dic[name](*args)
except PyccelError as e:
errors.report(e,
symbol=expr,
severity='fatal')
if name == 'lambdify':
return lambdify(expr, args)
return None
# TODO add documentation
builtin_import_registery = {'numpy': {
**numpy_functions,
**numpy_constants,
'linalg':numpy_linalg_functions,
'random':numpy_random_functions
},
'numpy.linalg': numpy_linalg_functions,
'numpy.random': numpy_random_functions,
'scipy.constants': scipy_constants,
'itertools': {'product': Product},
'math': {**math_functions, ** math_constants},
'pyccel.decorators': pyccel_decorators.__all__}
if sys.version_info < (3, 10):
from .builtin_imports import python_builtin_libs
else:
python_builtin_libs = set(sys.stdlib_module_names) # pylint: disable=no-member
recognised_libs = python_builtin_libs.union(builtin_import_registery.keys())
#==============================================================================
def collect_relevant_imports(func_dictionary, targets):
if len(targets) == 0:
return func_dictionary
imports = []
for target in targets:
if isinstance(target, AsName):
import_name = target.name
code_name = target.target
else:
import_name = target
code_name = import_name
if import_name in func_dictionary.keys():
imports.append((code_name, func_dictionary[import_name]))
return imports
def builtin_import(expr):
"""Returns a builtin pyccel-extension function/object from an import."""
if not isinstance(expr, Import):
raise TypeError('Expecting an Import expression')
if isinstance(expr.source, AsName):
source = expr.source.name
else:
source = str(expr.source)
if source == 'pyccel.decorators':
funcs = [f[0] for f in inspect.getmembers(pyccel_decorators, inspect.isfunction)]
for target in expr.target:
search_target = target.name if isinstance(target, AsName) else target
if search_target not in funcs:
errors.report("{} does not exist in pyccel.decorators".format(target),
symbol = expr, severity='error')
elif source in builtin_import_registery:
return collect_relevant_imports(builtin_import_registery[source], expr.target)
return []
#==============================================================================
def get_function_from_ast(ast, func_name):
node = None
for stmt in ast:
if isinstance(stmt, FunctionDef) and str(stmt.name) == func_name:
node = stmt
break
if node is None:
print('> could not find {}'.format(func_name))
return node
#==============================================================================
def split_positional_keyword_arguments(*args):
""" Create a list of positional arguments and a dictionary of keyword arguments
"""
# Distinguish between positional and keyword arguments
val_args = ()
for i, a in enumerate(args):
if isinstance(a, ValuedVariable):
args, val_args = args[:i], args[i:]
break
# Convert list of keyword arguments into dictionary
kwargs = {}
for v in val_args:
key = str(v.name)
value = v.value
kwargs[key] = value
return args, kwargs
#==============================================================================
def compatible_operation(*args, language_has_vectors = True):
"""
Indicates whether an operation requires an index to be
correctly understood
Parameters
==========
args : list of PyccelAstNode
The operator arguments
language_has_vectors : bool
Indicates if the language has support for vector
operations of the same shape
Results
=======
compatible : bool
A boolean indicating if the operation is compatible
"""
if language_has_vectors:
# If the shapes don't match then an index must be required
shapes = [a.shape[::-1] if a.order == 'F' else a.shape for a in args if a.shape != ()]
shapes = set(tuple(d if isinstance(d, Literal) else -1 for d in s) for s in shapes)
order = set(a.order for a in args if a.order is not None)
return len(shapes) <= 1 and len(order) <= 1
else:
return all(a.shape==() for a in args)
#==============================================================================
def insert_index(expr, pos, index_var):
"""
Function to insert an index into an expression at a given position
Parameters
==========
expr : Ast Node
The expression to be modified
pos : int
The index at which the expression is modified
(If negative then there is no index to insert)
index_var : Variable
The variable which will be used for indexing
Returns
=======
expr : Ast Node
Either a modified version of expr or expr itself
Examples
--------
>>> from pyccel.ast.core import Variable, Assign
>>> from pyccel.ast.operators import PyccelAdd
>>> from pyccel.ast.utilities import insert_index
>>> a = Variable('int', 'a', shape=(4,), rank=1)
>>> b = Variable('int', 'b', shape=(4,), rank=1)
>>> c = Variable('int', 'c', shape=(4,), rank=1)
>>> i = Variable('int', 'i', shape=())
>>> d = PyccelAdd(a,b)
>>> expr = Assign(c,d)
>>> insert_index(expr, 0, i, language_has_vectors = False)
IndexedElement(c, i) := IndexedElement(a, i) + IndexedElement(b, i)
>>> insert_index(expr, 0, i, language_has_vectors = True)
c := a + b
"""
if expr.rank==0:
return expr
elif isinstance(expr, (Variable, VariableAddress)):
if expr.rank==0 or -pos>expr.rank:
return expr
if expr.shape[pos]==1:
# If there is no dimension in this axis, reduce the rank
index_var = LiteralInteger(0)
# Add index at the required position
indexes = [Slice(None,None)]*(expr.rank+pos) + [index_var]+[Slice(None,None)]*(-1-pos)
return IndexedElement(expr, *indexes)
elif isinstance(expr, NumpyTranspose):
if expr.rank==0 or -pos>expr.rank:
return expr
if expr.shape[pos]==1:
# If there is no dimension in this axis, reduce the rank
index_var = LiteralInteger(0)
# Add index at the required position
if expr.rank<2:
return insert_index(expr.internal_var, expr.rank-1+pos, index_var)
else:
return NumpyTranspose(insert_index(expr.internal_var, expr.rank-1+pos, index_var))
elif isinstance(expr, IndexedElement):
base = expr.base
indices = list(expr.indices)
while -pos<=expr.base.rank and not isinstance(indices[pos], Slice):
pos -= 1
if -pos>expr.base.rank:
return expr
# Add index at the required position
if expr.base.shape[pos]==1:
# If there is no dimension in this axis, reduce the rank
assert(indices[pos].start is None)
index_var = LiteralInteger(0)
else:
# Calculate new index to preserve slice behaviour
if indices[pos].step is not None:
index_var = PyccelMul(index_var, indices[pos].step, simplify=True)
if indices[pos].start is not None:
index_var = PyccelAdd(index_var, indices[pos].start, simplify=True)
indices[pos] = index_var
return IndexedElement(base, *indices)
elif isinstance(expr, PyccelArithmeticOperator):
return type(expr)(insert_index(expr.args[0], pos, index_var),
insert_index(expr.args[1], pos, index_var))
else:
raise NotImplementedError("Expansion not implemented for type : {}".format(type(expr)))
#==============================================================================
LoopCollection = namedtuple('LoopCollection', ['body', 'length', 'modified_vars'])
#==============================================================================
def collect_loops(block, indices, new_index_name, tmp_vars, language_has_vectors = False, result = None):
"""
Run through a code block and split it into lists of tuples of lists where
each inner list represents a code block and the tuples contain the lists
and the size of the code block.
So the following:
a = a+b
for a: int[:,:] and b: int[:]
Would be returned as:
[
([
([a[i,j]=a[i,j]+b[j]],a.shape[1])
]
, a.shape[0]
)
]
Parameters
==========
block : list of Ast Nodes
The expressions to be modified
indices : list
An empty list to be filled with the temporary variables created
new_index_name : function
A function which provides a new variable name from a base name,
avoiding name collisions
tmp_vars : list
A list to which any temporary variables created can be appended
language_has_vectors : bool
Indicates if the language has support for vector
operations of the same shape
Results
=======
block : list of tuples of lists
The modified expression
"""
if result is None:
result = []
current_level = 0
array_creator_types = (Allocate, PythonList, PythonTuple, Concatenate, Duplicate)
is_function_call = lambda f: ((isinstance(f, FunctionCall) and not f.funcdef.is_elemental)
or (isinstance(f, PyccelInternalFunction) and not f.is_elemental))
for line in block:
if (isinstance(line, Assign) and
not isinstance(line.rhs, (array_creator_types, Nil)) and # not creating array
not line.rhs.get_attribute_nodes(array_creator_types, excluded_nodes = (ValuedVariable)) and # not creating array
not is_function_call(line.rhs)): # not a basic function call
# Collect lhs variable
# This is needed to know what has already been modified in the loop
if isinstance(line.lhs, Variable):
lhs_vars = [line.lhs]
elif isinstance(line.lhs, IndexedElement):
lhs_vars = [line.lhs.base]
else:
lhs_vars = set(line.lhs.get_attribute_nodes((Variable, IndexedElement)))
lhs_vars = [v.base if isinstance(v, IndexedElement) else v for v in lhs_vars]
# Get all objects which affect where indices are inserted
notable_nodes = line.get_attribute_nodes((Variable,
IndexedElement,
VariableAddress,
NumpyTranspose,
FunctionCall,
PyccelInternalFunction,
PyccelIs))
# Find all elemental function calls. Normally function call arguments are not indexed
# However elemental functions are an exception
elemental_func_calls = [f for f in notable_nodes if (isinstance(f, FunctionCall) \
and f.funcdef.is_elemental)]
elemental_func_calls += [f for f in notable_nodes if (isinstance(f, PyccelInternalFunction) \
and f.is_elemental)]
# Collect all objects into which indices may be inserted
variables = [v for v in notable_nodes if isinstance(v, (Variable,
IndexedElement,
VariableAddress))]
variables += [v for f in elemental_func_calls \
for v in f.get_attribute_nodes((Variable, IndexedElement, VariableAddress),
excluded_nodes = (FunctionDef))]
transposed_vars = [v for v in notable_nodes if isinstance(v, NumpyTranspose)] \
+ [v for f in elemental_func_calls \
for v in f.get_attribute_nodes(NumpyTranspose,
excluded_nodes = (FunctionDef))]
is_checks = [n for n in notable_nodes if isinstance(n, PyccelIs)]
variables = list(set(variables))
# Check if the expression is already satisfactory
if compatible_operation(*variables, *transposed_vars, *is_checks,
language_has_vectors = language_has_vectors):
result.append(line)
current_level = 0
continue
# Find function calls in this line
funcs = [f for f in notable_nodes+transposed_vars if (isinstance(f, FunctionCall) \
and not f.funcdef.is_elemental)]
internal_funcs = [f for f in notable_nodes+transposed_vars if (isinstance(f, PyccelInternalFunction) \
and not f.is_elemental) \
and not isinstance(f, NumpyTranspose)]
# Collect all variables for which values other than the value indexed in the loop are important
# E.g. x = np.sum(a) has a dependence on a
dependencies = set(v for f in chain(funcs, internal_funcs) \
for v in f.get_attribute_nodes((Variable, IndexedElement, VariableAddress),
excluded_nodes = (FunctionDef)))
# Replace function calls with temporary variables
# This ensures that the function is only called once and stops problems
# for expressions such as:
# c += b*np.sum(c)
func_vars1 = [Variable(f.dtype, new_index_name('tmp')) for f in internal_funcs]
_ = [v.copy_attributes(f) for v,f in zip(func_vars1, internal_funcs)]
assigns = [Assign(v, f) for v,f in zip(func_vars1, internal_funcs)]
if any(len(f.funcdef.results)!=1 for f in funcs):
errors.report("Loop unravelling cannot handle function calls "\
"which return tuples or None",
symbol=line, severity='fatal')
func_vars2 = [f.funcdef.results[0].clone(new_index_name('tmp')) for f in funcs]
assigns += [Assign(v, f) for v,f in zip(func_vars2, funcs)]
if assigns:
# For now we do not handle memory allocation in loop unravelling
if any(v.rank > 0 for v in func_vars1) or any(v.rank > 0 for v in func_vars1):
errors.report("Loop unravelling cannot handle extraction of function calls "\
"which return arrays as this requires allocation. Please place the function "\
"call on its own line",
symbol=line, severity='fatal')
line.substitute(internal_funcs, func_vars1, excluded_nodes=(FunctionCall))
line.substitute(funcs, func_vars2)
tmp_vars.extend(func_vars1)
tmp_vars.extend(func_vars2)
result.extend(assigns)
current_level = 0
rank = line.lhs.rank
shape = line.lhs.shape
new_vars = variables
new_vars_t = transposed_vars
# Loop over indexes, inserting until the expression can be evaluated
# in the desired language
new_level = 0
for index in range(-rank,0):
new_level += 1
# If an index exists at the same depth, reuse it if not create one
if rank+index >= len(indices):
indices.append(Variable('int',new_index_name('i')))
index_var = indices[rank+index]
new_vars = [insert_index(v, index, index_var) for v in new_vars]
new_vars_t = [insert_index(v, index, index_var) for v in new_vars_t]
if compatible_operation(*new_vars, *new_vars_t, language_has_vectors = language_has_vectors):
break
# Replace variable expressions with Indexed versions
line.substitute(variables, new_vars, excluded_nodes = (FunctionCall, PyccelInternalFunction))
line.substitute(transposed_vars, new_vars_t, excluded_nodes = (FunctionCall))
_ = [f.substitute(variables, new_vars, excluded_nodes = (FunctionDef)) for f in elemental_func_calls]
_ = [f.substitute(transposed_vars, new_vars_t, excluded_nodes = (FunctionDef)) for f in elemental_func_calls]
# Recurse through result tree to save line with lines which need
# the same set of for loops
save_spot = result
j = 0
for _ in range(min(new_level,current_level)):
# Select the existing loop if the shape matches the shape of the expression
# and the loop is not used to modify one of the variable dependencies
if save_spot[-1].length == shape[j] and not any(u in save_spot[-1].modified_vars for u in dependencies):
save_spot[-1].modified_vars.update(lhs_vars)
save_spot = save_spot[-1].body
j+=1
else:
break
for k in range(j,new_level):
# Create new loops until we have the neccesary depth
save_spot.append(LoopCollection([], shape[k], set(lhs_vars)))
save_spot = save_spot[-1].body
# Save results
save_spot.append(line)
current_level = new_level
elif isinstance(line, Assign) and isinstance(line.lhs, IndexedElement) \
and isinstance(line.rhs, (PythonTuple, NumpyArray)) and not language_has_vectors:
lhs = line.lhs
rhs = line.rhs
if isinstance(rhs, NumpyArray):
rhs = rhs.arg
lhs_rank = lhs.rank
new_assigns = [Assign(
insert_index(expr=lhs,
pos = -lhs_rank,
index_var = LiteralInteger(j)),
rj) # lhs[j] = rhs[j]
for j, rj in enumerate(rhs)]
collect_loops(new_assigns, indices, new_index_name, tmp_vars, language_has_vectors, result = result)
elif isinstance(line, Assign) and isinstance(line.rhs, Concatenate):
lhs = line.lhs
rhs = line.rhs
arg1, arg2 = rhs.args
assign1 = Assign(lhs[Slice(LiteralInteger(0), arg1.shape[0])], arg1)
assign2 = Assign(lhs[Slice(arg1.shape[0], PyccelAdd(arg1.shape[0], arg2.shape[0], simplify=True))], arg2)
collect_loops([assign1, assign2], indices, new_index_name, tmp_vars, language_has_vectors, result = result)
elif isinstance(line, Assign) and isinstance(line.rhs, Duplicate):
lhs = line.lhs
rhs = line.rhs
if not isinstance(rhs.length, LiteralInteger):
if len(indices) == 0:
indices.append(Variable('int',new_index_name('i')))
idx = indices[0]
assign = Assign(lhs[Slice(PyccelMul(rhs.val.shape[0], idx, simplify=True),
PyccelMul(rhs.val.shape[0],
PyccelAdd(idx, LiteralInteger(1), simplify=True),
simplify=True))],
rhs.val)
tmp_indices = indices[1:]
block = collect_loops([assign], tmp_indices, new_index_name, tmp_vars, language_has_vectors)
if len(tmp_indices)>len(indices)-1:
indices.extend(tmp_indices[len(indices)-1:])
result.append(LoopCollection(block, rhs.length, set([lhs])))
else:
assigns = [Assign(lhs[Slice(PyccelMul(rhs.val.shape[0], LiteralInteger(idx), simplify=True),
PyccelMul(rhs.val.shape[0],
PyccelAdd(LiteralInteger(idx), LiteralInteger(1), simplify=True),
simplify=True))],
rhs.val) for idx in range(rhs.length)]
collect_loops(assigns, indices, new_index_name, tmp_vars, language_has_vectors, result = result)
else:
# Save line in top level (no for loop)
result.append(line)
current_level = 0
return result
#==============================================================================
def insert_fors(blocks, indices, level = 0):
"""
Run through the output of collect_loops and create For loops of the
requested sizes
Parameters
==========
block : list of LoopCollection
The result of a call to collect_loops
indices : list
The index variables
level : int
The index of the index variable used in the outermost loop
Results
=======
block : list of PyccelAstNodes
The modified expression
"""
if all(not isinstance(b, LoopCollection) for b in blocks.body):
body = blocks.body
else:
body = [insert_fors(b, indices, level+1) if isinstance(b, LoopCollection) else [b] \
for b in blocks.body]
body = [bi for b in body for bi in b]
if blocks.length == 1:
return body
else:
body = CodeBlock(body, unravelled = True)
return [For(indices[level], PythonRange(0,blocks.length), body)]
#==============================================================================
def expand_inhomog_tuple_assignments(block, language_has_vectors = False):
"""
Simplify expressions in a CodeBlock by unravelling tuple assignments into multiple lines
Parameters
==========
block : CodeBlock
The expression to be modified
Examples
--------
>>> from pyccel.ast.builtins import PythonTuple
>>> from pyccel.ast.core import Assign, CodeBlock
>>> from pyccel.ast.literals import LiteralInteger
>>> from pyccel.ast.utilities import expand_to_loops
>>> from pyccel.ast.variable import Variable
>>> a = Variable('int', 'a', shape=(,), rank=0)
>>> b = Variable('int', 'b', shape=(,), rank=0)
>>> c = Variable('int', 'c', shape=(,), rank=0)
>>> expr = [Assign(PythonTuple(a,b,c),PythonTuple(LiteralInteger(0),LiteralInteger(1),LiteralInteger(2))]
>>> expand_inhomog_tuple_assignments(CodeBlock(expr))
[Assign(a, LiteralInteger(0)), Assign(b, LiteralInteger(1)), Assign(c, LiteralInteger(2))]
"""
if not language_has_vectors:
allocs_to_unravel = [a for a in block.get_attribute_nodes(Assign) \
if isinstance(a.lhs, HomogeneousTupleVariable) \
and isinstance(a.rhs, (HomogeneousTupleVariable, Duplicate, Concatenate))]
new_allocs = [(Assign(a.lhs, NumpyEmpty(a.lhs.shape,
dtype=a.lhs.dtype,
order=a.lhs.order)
), a) if a.lhs.is_stack_array
else (a) if a.lhs.allocatable
else (Allocate(a.lhs,
shape=a.lhs.shape,
order = a.lhs.order,
status="unknown"), a)
for a in allocs_to_unravel]
block.substitute(allocs_to_unravel, new_allocs)
assigns = [a for a in block.get_attribute_nodes(Assign) \
if isinstance(a.lhs, InhomogeneousTupleVariable) \
and isinstance(a.rhs, (PythonTuple, InhomogeneousTupleVariable))]
if len(assigns) != 0:
new_assigns = [[Assign(l,r) for l,r in zip(a.lhs, a.rhs)] for a in assigns]
block.substitute(assigns, new_assigns)
expand_inhomog_tuple_assignments(block)
#==============================================================================
def expand_to_loops(block, new_index_name, language_has_vectors = False):
"""
Re-write a list of expressions to include explicit loops where necessary
Parameters
==========
block : CodeBlock
The expressions to be modified
new_index_name : function
A function which provides a new variable name from a base name,
avoiding name collisions
language_has_vectors : bool
Indicates if the language has support for vector
operations of the same shape
Returns
=======
expr : list of Ast Nodes
The expressions with For loops inserted where necessary
Examples
--------
>>> from pyccel.ast.core import Variable, Assign
>>> from pyccel.ast.operators import PyccelAdd
>>> from pyccel.ast.utilities import expand_to_loops
>>> a = Variable('int', 'a', shape=(4,), rank=1)
>>> b = Variable('int', 'b', shape=(4,), rank=1)
>>> c = Variable('int', 'c', shape=(4,), rank=1)
>>> i = Variable('int', 'i', shape=())
>>> d = PyccelAdd(a,b)
>>> expr = [Assign(c,d)]
>>> expand_to_loops(expr, language_has_vectors = False)
[For(i_0, PythonRange(0, LiteralInteger(4), LiteralInteger(1)), CodeBlock([IndexedElement(c, i_0) := PyccelAdd(IndexedElement(a, i_0), IndexedElement(b, i_0))]), [])]
"""
expand_inhomog_tuple_assignments(block)
indices = []
tmp_vars = []
res = collect_loops(block.body, indices, new_index_name, tmp_vars, language_has_vectors)
body = [insert_fors(b, indices) if isinstance(b, tuple) else [b] for b in res]
body = [bi for b in body for bi in b]
return body, indices+tmp_vars