PyForTool
Python-fortran-tool
Loading...
Searching...
No Matches
statements.py
1"""
2Statement-level code transformations.
3
4Provides the Statements class for manipulating FORTRAN statements including
5CALL statements, array syntax, conditional blocks, and subroutine inlining.
6
7Key Features
8------------
9- Remove CALL statements (with optional cleanup of unused variables)
10- Transform array syntax to explicit DO loops
11- Inline contained subroutines into their parent
12- Conditional flag manipulation (set flags to .FALSE.)
13- Statement node removal with structural simplification
14
15Classes
16-------
17Statements : Mixin class providing statement manipulation methods
18
19Examples
20--------
21>>> pft = PYFT('input.F90')
22>>> pft.removeCall('FOO') # Remove all CALL FOO statements
23>>> pft.removeArraySyntax() # Convert A(:) = B(:) to DO loops
24>>> pft.inlineContainedSubroutines() # Inline helper subroutines
25>>> pft.setFalseIfStmt('LDEBUG') # Disable debug blocks
26"""
27
28import re
29import logging
30import copy
31from pyfortool.util import n2name, nonCode, debugDecor, alltext, PYFTError, tag, noParallel
32from pyfortool.expressions import createExprPart, createArrayBounds, createElem
33from pyfortool.tree import updateTree
34from pyfortool.variables import updateVarList
35from pyfortool import NAMESPACE
36
37
38def _nodesInIf(ifNode):
39 """
40 Internal method to return nodes in if structure
41 """
42 nodes = []
43 for block in ifNode.findall('./{*}if-block'):
44 for item in [i for i in block
45 if tag(i) not in ('if-then-stmt', 'else-if-stmt',
46 'else-stmt', 'end-if-stmt')]:
47 if not nonCode(item):
48 nodes.append(item)
49 return nodes
50
51
52def _nodesInWhere(whereNode):
53 """
54 Internal method to return nodes in where structure
55 """
56 nodes = []
57 for block in whereNode.findall('./{*}where-block'):
58 for item in [i for i in block
59 if tag(i) not in ('where-construct-stmt', 'else-where-stmt',
60 'end-where-stmt')]:
61 if not nonCode(item):
62 nodes.append(item)
63 return nodes
64
65
66def _nodesInDo(doNode):
67 """
68 Internal method to return nodes in do structure
69 """
70 nodes = []
71 for item in [i for i in doNode if tag(i) not in ('do-stmt', 'end-do-stmt')]:
72 if not nonCode(item):
73 nodes.append(item)
74 return nodes
75
76
77def _nodesInCase(caseNode):
78 """
79 Internal method to return nodes in do structure
80 """
81 nodes = []
82 for block in caseNode.findall('./{*}selectcase-block'):
83 for item in [i for i in block
84 if tag(i) not in ('select-case-stmt', 'case-stmt',
85 'end-select-case-stmt')]:
86 if not nonCode(item):
87 nodes.append(item)
88 return nodes
89
90
91class Statements():
92 """
93 Methods to act on statements
94 """
95
96 # No @debugDecor for this low-level method
97 def isNodeInProcedure(self, node, procList):
98 """
99 Check if a node is an argument of a specific intrinsic procedure.
100
101 Parameters
102 ----------
103 node : xml element
104 A named-E element to check.
105 procList : list of str
106 List of intrinsic procedure names (e.g., ['ALLOCATED', 'PRESENT']).
107
108 Returns
109 -------
110 bool
111 True if the node is an argument of one of the specified procedures.
112
113 Examples
114 --------
115 >>> node = pft.find('.//{*}named-E')
116 >>> is_arg = pft.isNodeInProcedure(node, ['ALLOCATED', 'PRESENT'])
117 """
118 # E.g. The xml for "ASSOCIATED(A)" is
119 # <f:named-E>
120 # <f:N><f:n>ASSOCIATED</f:n></f:N>
121 # <f:R-LT><f:parens-R>(
122 # <f:element-LT><f:element><f:named-E><f:N><f:n>A</f:n></f:N>
123 # </f:named-E></f:element></f:element-LT>)
124 # </f:parens-R></f:R-LT>
125 # </f:named-E>
126 inside = False
127 par = self.getParent(node)
128 if tag(par) == 'element':
129 par = self.getParent(par)
130 if tag(par) == 'element-LT':
131 par = self.getParent(par)
132 if tag(par) == 'parens-R':
133 par = self.getParent(par)
134 if tag(par) == 'R-LT':
135 previous = self.getSiblings(par, before=True, after=False)
136 if len(previous) > 0 and tag(previous[-1]) == 'N' and \
137 n2name(previous[-1]).upper() in [p.upper() for p in procList]:
138 inside = True
139 return inside
140
141 # No @debugDecor for this low-level method
142 def isNodeInCall(self, node):
143 """
144 Check if a node is an argument of a CALL statement.
145
146 Parameters
147 ----------
148 node : xml element
149 A named-E element to check.
150
151 Returns
152 -------
153 bool
154 True if the node is an argument in a CALL statement,
155 False otherwise.
156
157 Examples
158 --------
159 >>> node = pft.find('.//{*}named-E[{*}N/{*}n="X"]')
160 >>> is_arg = pft.isNodeInCall(node) # True if X is in CALL FOO(X)
161 """
162 # E.g. The xml for "CALL FOO(A)" is
163 # <f:call-stmt>CALL
164 # <f:procedure-designator><f:named-E><f:N><f:n>FOO</f:n></f:N>
165 # </f:named-E></f:procedure-designator>(
166 # <f:arg-spec><f:arg><f:named-E><f:N><f:n>A</f:n></f:N></f:named-E></f:arg></f:arg-spec>)
167 # </f:call-stmt>
168 inside = False
169 par = self.getParent(node)
170 if tag(par) == 'arg':
171 par = self.getParent(par)
172 if tag(par) == 'arg-spec':
173 par = self.getParent(par)
174 if tag(par) == 'call-stmt':
175 inside = True
176 return inside
177
178 @debugDecor
179 def removeCall(self, callName, simplify=False):
180 """
181 Remove all CALL statements to a specified subprogram.
182
183 Parameters
184 ----------
185 callName : str
186 Name of the subprogram to remove calls to.
187 simplify : bool, optional
188 If True, also remove variables that become unused after the deletion.
189 For example, if "CALL FOO(X)" is removed and X is not used elsewhere,
190 X will also be removed.
191
192 Returns
193 -------
194 int
195 Number of CALL statements removed.
196
197 Examples
198 --------
199 >>> pft = PYFT('input.F90')
200 >>> n = pft.removeCall('FOO') # Remove all CALL FOO statements
201 >>> print(f"Removed {n} calls")
202
203 Remove calls and simplify (remove unused variables):
204 >>> pft.removeCall('BAR', simplify=True)
205
206 Notes
207 -----
208 - When simplify=True, may cascade to remove:
209 - Empty IF constructs (if call was the only statement)
210 - Variables only used in removed calls
211 - Type declarations that become empty
212 """
213 # Select all call-stmt and filter by name
214 callNodes = [cn for cn in self.findall('.//{*}call-stmt')
215 if n2name(cn.find('.//{*}named-E/{*}N')).upper() == callName.upper()]
216 self.removeStmtNode(callNodes, simplify, simplify)
217 return len(callNodes)
218
219 @debugDecor
220 def removePrints(self, simplify=False):
221 """
222 Remove all PRINT statements from the code.
223
224 Parameters
225 ----------
226 simplify : bool, optional
227 If True, also remove variables that become unused after the deletion.
228
229 Examples
230 --------
231 >>> pft = PYFT('input.F90')
232 >>> pft.removePrints() # Remove all PRINT statements
233 >>> pft.removePrints(simplify=True) # Also remove unused variables
234
235 Notes
236 -----
237 - When simplify=True, may cascade to remove:
238 - Empty IF constructs (if print was the only statement)
239 - Variables only used in removed prints
240 """
241 self.removeStmtNode(self.findall('.//{*}print-stmt'), simplify, simplify)
242
243 @debugDecor
244 def checkEmptyParensInMnhExpand(self, mustRaise=False):
245 """
246 :param mustRaise: True to raise
247 Issue a logging.warning if there are empty parens inside mnh_expand blocks
248 If mustRaise is True, issue a logging.error instead and raise an error
249 """
250 ok = True
251 log = logging.error if mustRaise else logging.warning
252 for openmnh in [comment for comment in self.findall('.//{*}C')
253 if comment.text.lstrip(' ').startswith('!$mnh_expand')]:
254 for sibling in self.getSiblings(openmnh, before=False, after=True):
255 if tag(sibling) == 'C' and sibling.text.lstrip(' ').startswith('!$mnh_end_expand'):
256 break
257
258 for sslt in sibling.findall('.//{*}named-E/' +
259 '{*}R-LT/{*}array-R/{*}section-subscript-LT'):
260 if all(alltext(ss) == ':' for ss in sslt.findall('./{*}section-subscript')):
261 arg = self.getParent(sslt, 3)
262 log(("{} is an array with empty parens inside an mnh_expand " +
263 "directive, in file '{}'"
264 ).format(alltext(arg).replace('\n', ' \\n '), self.getFileName()))
265 ok = False
266
267 if not ok and mustRaise:
268 raise PYFTError(("There are empty parens inside mnh_expand blocks in file '{}'"
269 ).format(self.getFileName()))
270 return ok
271
272 @debugDecor
273 def removeArraySyntax(self, concurrent=False, useMnhExpand=True, everywhere=True,
274 loopVar=None, reuseLoop=True, funcList=None,
275 updateMemSet=False, updateCopy=False, addAccIndependentCollapse=True):
276 """
277 Transform array syntax assignments into explicit DO loops.
278
279 Converts Fortran array syntax (e.g., A(:) = B(:)) into equivalent DO loop form.
280
281 Parameters
282 ----------
283 concurrent : bool, optional
284 If True, use 'DO CONCURRENT' loops instead of simple 'DO' loops.
285 Default is False.
286 useMnhExpand : bool, optional
287 If True, respect mnh_expand directives to transform entire blocks
288 into a single loop. Default is True.
289 everywhere : bool, optional
290 If True, transform all array syntax in the code.
291 If False, only transform sections marked with !$mnh_expand directives.
292 Default is True.
293 loopVar : callable or None, optional
294 Function to determine loop index variable name.
295 Takes arguments: (lowerDecl, upperDecl, lowerUsed, upperUsed, name, index)
296 Returns: str (variable name), True (auto-generate name), or False (skip).
297 None (default) auto-generates variable names (J1, J2, etc.).
298 reuseLoop : bool, optional
299 If True, attempt to reuse loops when consecutive statements
300 have identical bounds. Default is True.
301 funcList : list of str, optional
302 Additional function names to recognize as array functions.
303 These functions will not be expanded. Default is None (empty list).
304 updateMemSet : bool, optional
305 If True, transform constant array initializations (e.g., A(:) = 0)
306 into DO loops. Default is False.
307 updateCopy : bool, optional
308 If True, transform array copy operations (e.g., A(:) = B(:))
309 into DO loops. Default is False.
310 addAccIndependentCollapse : bool, optional
311 If True, add !$acc loop independent collapse(N) directive
312 before DO constructs. Default is True.
313
314 Returns
315 -------
316 None
317
318 Transformation Examples
319 ----------------------
320 Simple assignment:
321
322 Before:
323 A(:) = B(:) + C(:)
324
325 After (standard):
326 DO J1 = LBOUND(A, 1), UBOUND(A, 1)
327 A(J1) = B(J1) + C(J1)
328 END DO
329
330 After (concurrent):
331 DO CONCURRENT (J1=LBOUND(A, 1):UBOUND(A, 1))
332 A(J1) = B(J1) + C(J1)
333 END DO
334
335 WHERE construct:
336
337 Before:
338 WHERE (MASK(:)) X(:) = Y(:)
339
340 After:
341 DO J1 = 1, SIZE(X, 1)
342 IF (MASK(J1)) X(J1) = Y(J1)
343 END DO
344
345 Notes
346 -----
347 - Only transforms array syntax using explicit ':' notation.
348 - Intrinsic array functions (COUNT, ANY, SUM, etc.) are preserved.
349 - Does not transform:
350 - A=A(:) (no-op on left side)
351 - A(:)=A (single array without slice on right side)
352 - When useMnhExpand=True, requires specific directive format:
353 !$mnh_expand_array(INDEX=bounds)
354 ... code to transform ...
355 !$mnh_end_expand_array(INDEX=bounds)
356 """
357
358 # Developer notes:
359 # We use recursivity to avoid the use of the 'getParent' function.
360 # We start from the top node and call 'recur'.
361 #
362 # The 'recur' function loops over the different nodes and:
363 # - search for mnh directives (if 'useMnhExpand' is True):
364 # - when it is an opening directive:
365 # - decode the directive to identify bounds and variables to use
366 # ('decode' function)
367 # - introduce the DO loops (with 'createDoConstruct')
368 # - activate the 'inMnh' flag
369 # - when it is a closing directive:
370 # - deactivate the 'inMnh' flag
371 # - while the 'inMnh' flag is activated:
372 # - update ('updateStmt' function, that uses 'arrayR2parensR') and put all statements
373 # in the DO loops
374 # - in case (if 'everywhere' is True) statement is expressed using array-syntax:
375 # - find the bounds and guess a set of variables to use ('findArrayBounds' function)
376 # - introduce the DO loops (with 'createDoConstruct') if we cannot reuse the
377 # previous one
378 # - update ('updateStmt' function, that uses 'arrayR2parensR') and put all statements
379 # in the DO loops
380 # - in case the statement contains other statements (SUBROUTINE, DO loop...), call 'recur'
381 # on it
382 #
383 # Because we iterate on the statements, the tree structure cannot be modified during the
384 # iteration.
385 # All the modifications to apply are, instead, stored in objetcs ('toinsert', 'toremove'
386 # and 'varList') are applied afterwards.
387 #
388 # In addition, a number of instructions are needed to preserve and/or modify the indentation
389 # and can somewhat obfuscate the source code.
390
391 def decode(directive):
392 """
393 Decode mnh_expand directive
394 :param directive: mnh directive text
395 :return: (table, kind) where
396 table is a dictionnary: keys are variable names, values are tuples with first
397 and last index
398 kind is 'array' or 'where'
399 """
400 # E.g. !$mnh_expand_array(JIJ=IIJB:IIJE,JK=1:IKT)
401 # We expect that the indexes are declared in the same order as the one they appear
402 # in arrays
403 # For the example given, arrays are addressed with (JIJ, JK)
404 # For this example, return would be
405 # ('array', {'JIJ':('IIJB', 'IIJE'), 'JK':('1', 'IKT')})
406 table = directive.split('(')[1].split(')')[0].split(',')
407 table = {c.split('=')[0]: c.split('=')[1].split(':')
408 for c in table} # ordered since python 3.7
409 table.pop('OPENACC', None) # OPENACC='gang' in MNH v6.0 mnh_expand
410 if directive.lstrip(' ').startswith('!$mnh_expand'):
411 kind = directive[13:].lstrip(' ').split('(')[0].strip()
412 else:
413 kind = directive[17:].lstrip(' ').split('(')[0].strip()
414 return table, kind
415
416 def updateStmt(stmt, table, kind, extraindent, parent, scope):
417 """
418 Updates the statement given the table dictionnary '(:, :)' is replaced by '(JI, JK)' if
419 table.keys() is ['JI', 'JK']
420 :param stmt: statement to update
421 :param table: dictionnary retruned by the decode function
422 :param kind: kind of mnh directives: 'array' or 'where'
423 or None if transformation is not governed by
424 mnh directive
425 :param scope: current scope
426 """
427
428 def addExtra(node, extra):
429 """Helper function to add indentation spaces"""
430 if extra != 0 and (node.tail is not None) and '\n' in node.tail:
431 # We add indentation after new line only
432 # - if tail already contains a '\n' to discard
433 # a-stmt followed by a comment
434 # or '&' immediatly followed by something at the beginning of a line
435 # - if not folowed by another new line (with optional space in between)
436 node.tail = re.sub(r"(\n[ ]*)(\Z|[^\n ]+)",
437 r"\1" + extra * ' ' + r"\2", node.tail)
438
439 addExtra(stmt, extraindent) # Set indentation for the *next* node
440 if tag(stmt) == 'C':
441 pass
442 elif tag(stmt) == 'cpp':
443 i = list(parent).index(stmt)
444 if i == 0:
445 # In this case, it would be a solution to add an empty comment before the
446 # node stmt to easilty control the indentation contained in the tail
447 raise PYFTError("How is it possible?")
448 parent[i - 1].tail = parent[i - 1].tail.rstrip(' ') # Remove the indentation
449 elif tag(stmt) == 'a-stmt':
450 sss = stmt.findall('./{*}E-1/{*}named-E/{*}R-LT/{*}array-R/' +
451 '{*}section-subscript-LT/{*}section-subscript')
452 if len([ss for ss in sss if ':' in alltext(ss)]) != len(table):
453 raise PYFTError("Inside code sections to transform in DO loops, " +
454 "all affectations must use ':'.\n" +
455 "This is not the case in:\n{stmt}".format(stmt=alltext(stmt)))
456 if stmt.find('./{*}E-1/{*}named-E/{*}N').tail is not None and kind is not None:
457 raise PYFTError("To keep the compatibility with the filepp version of loop " +
458 "expansion, nothing must appear between array names and " +
459 "opening parethesis inside mnh directive sections.")
460 # We loop on named-E nodes (and not directly on array-R nodes to prevent using
461 # the costly getParent)
462 for namedE in stmt.findall('.//{*}R-LT/..'):
463 scope.arrayR2parensR(namedE, table) # Replace slices by variable
464 for cnt in stmt.findall('.//{*}cnt'):
465 addExtra(cnt, extraindent) # Add indentation after continuation characters
466 elif tag(stmt) == 'if-stmt':
467 logging.warning(
468 "An if statement is inside a code section transformed in DO loop in %s",
469 scope.getFileName())
470 # Update the statement contained in the action node
471 updateStmt(stmt.find('./{*}action-stmt')[0], table, kind, 0, stmt, scope)
472 elif tag(stmt) == 'if-construct':
473 logging.warning(
474 "An if construct is inside a code section transformed in DO loop in %s",
475 scope.getFileName())
476 # Loop over the blocks: if, elseif, else
477 for ifBlock in stmt.findall('./{*}if-block'):
478 for child in ifBlock: # Loop over each statement inside the block
479 if tag(child) not in ('if-then-stmt', 'else-if-stmt',
480 'else-stmt', 'end-if-stmt'):
481 updateStmt(child, table, kind, extraindent, ifBlock, scope)
482 else:
483 # Update indentation because the loop is here and not in recur
484 addExtra(child, extraindent)
485 for cnt in child.findall('.//{*}cnt'):
486 # Add indentation spaces after continuation characters
487 addExtra(cnt, extraindent)
488 elif tag(stmt) == 'where-stmt':
489 # Where statement becomes if statement
490 stmt.tag = f'{{{NAMESPACE}}}if-stmt'
491 stmt.text = 'IF (' + stmt.text.split('(', 1)[1]
492 # Update the action part
493 updateStmt(stmt.find('./{*}action-stmt')[0], table, kind,
494 extraindent, stmt, scope)
495 mask = stmt.find('./{*}mask-E')
496 mask.tag = f'{{{NAMESPACE}}}condition-E' # rename the condition tag
497 for namedE in mask.findall('.//{*}R-LT/..'):
498 scope.arrayR2parensR(namedE, table) # Replace slices by variable
499 for cnt in stmt.findall('.//{*}cnt'):
500 addExtra(cnt, extraindent) # Add indentation after continuation characters
501 elif tag(stmt) == 'where-construct':
502 if kind != 'where' and kind is not None:
503 raise PYFTError('To keep the compatibility with the filepp version of loop " + \
504 "expansion, no where construct must appear " + \
505 "in mnh_expand_array blocks.')
506 # Where construct becomes if construct
507 stmt.tag = f'{{{NAMESPACE}}}if-construct'
508 # Loop over the blocks (where, elsewhere)
509 for whereBlock in stmt.findall('./{*}where-block'):
510 whereBlock.tag = f'{{{NAMESPACE}}}if-block'
511 for child in whereBlock: # Loop over each statement inside the block
512 if tag(child) == 'end-where-stmt':
513 # rename ENDWHERE into ENDIF
514 child.tag = f'{{{NAMESPACE}}}end-if-stmt'
515 child.text = 'END IF'
516 # Update indentation because the loop is here and not in recur
517 addExtra(child, extraindent)
518 elif tag(child) in ('where-construct-stmt', 'else-where-stmt'):
519 # Update indentation because the loop is here and not in recur
520 addExtra(child, extraindent)
521 if tag(child) == 'where-construct-stmt':
522 # rename WHERE into IF (the THEN part is attached to the condition)
523 child.tag = f'{{{NAMESPACE}}}if-then-stmt'
524 child.text = 'IF (' + child.text.split('(', 1)[1]
525 else:
526 # In where construct the same ELSEWHERE keyword is used with or
527 # without mask. Whereas for if structure ELSEIF is used with a
528 # condition and ELSE without condition
529 if '(' in child.text:
530 # rename ELSEWHERE into ELSEIF
531 child.tag = f'{{{NAMESPACE}}}else-if-stmt'
532 child.text = 'ELSE IF (' + child.text.split('(', 1)[1]
533 else:
534 # rename ELSEWHERE into ELSE
535 child.tag = f'{{{NAMESPACE}}}else-stmt'
536 child.text = 'ELSE'
537 for mask in child.findall('./{*}mask-E'): # would a find be enough?
538 # add THEN
539 mask.tag = f'{{{NAMESPACE}}}condition-E'
540 mask.tail += ' THEN'
541 for namedE in mask.findall('.//{*}R-LT/..'):
542 # Replace slices by variable in the condition
543 scope.arrayR2parensR(namedE, table)
544 for cnt in child.findall('.//{*}cnt'):
545 # Add indentation spaces after continuation characters
546 addExtra(cnt, extraindent)
547 else:
548 updateStmt(child, table, kind, extraindent, whereBlock, scope)
549 else:
550 raise PYFTError('Unexpected tag found in mnh_expand ' +
551 'directives: {t}'.format(t=tag(stmt)))
552 return stmt
553
554 def closeLoop(loopdesc):
555 """Helper function to deal with indentation"""
556 if loopdesc:
557 inner, outer, indent, extraindent = loopdesc
558 if inner[-2].tail is not None:
559 # tail of last statement in DO loop before transformation
560 outer.tail = inner[-2].tail[:-extraindent]
561 inner[-2].tail = '\n' + (indent + extraindent - 2) * ' ' # position of the ENDDO
562 return False
563
564 toinsert = [] # list of nodes to insert
565 toremove = [] # list of nodes to remove
566 newVarList = [] # list of new variables
567
568 def recur(elem, scope):
569 inMnh = False # are we in a DO loop created by a mnh directive
570 inEverywhere = False # are we in a created DO loop (except if done with mnh directive)
571 tailSave = {} # Save tail before transformation (to retrieve original indentation)
572 for ie, sElem in enumerate(list(elem)): # we loop on elements in the natural order
573 if tag(sElem) == 'C' and sElem.text.lstrip(' ').startswith('!$mnh_expand') and \
574 useMnhExpand:
575 # This is an opening mnh directive
576 if inMnh:
577 raise PYFTError('Nested mnh_directives are not allowed')
578 inMnh = True
579 inEverywhere = closeLoop(inEverywhere) # close other loop if needed
580
581 # Directive decoding
582 table, kind = decode(sElem.text)
583 # indentation of next statement
584 indent = len(sElem.tail) - len(sElem.tail.rstrip(' '))
585 toremove.append((elem, sElem)) # we remove the directive itself
586 if ie != 0:
587 # We add, to the tail of the previous node, the tail of
588 # the directive (except one \n)
589 if elem[ie - 1].tail is None:
590 elem[ie - 1].tail = ''
591 elem[ie - 1].tail += sElem.tail.replace('\n', '', 1).rstrip(' ')
592
593 # Building acc loop collapse independent directive
594 if addAccIndependentCollapse:
595 accCollapse = createElem('C', text='!$acc loop independent collapse(' +
596 str(len(table.keys())) + ')',
597 tail='\n' + indent * ' ')
598 toinsert.append((elem, accCollapse, ie))
599
600 # Building loop
601 inner, outer, extraindent = scope.createDoConstruct(table, indent=indent,
602 concurrent=concurrent)
603 toinsert.append((elem, outer, ie)) # Place to insert the loop
604
605 elif (tag(sElem) == 'C' and
606 sElem.text.lstrip(' ').startswith('!$mnh_end_expand') and useMnhExpand):
607 # This is a closing mnh directive
608 if not inMnh:
609 raise PYFTError('End mnh_directive found before begin directive ' +
610 'in {f}'.format(f=scope.getFileName()))
611 if (table, kind) != decode(sElem.text):
612 raise PYFTError("Opening and closing mnh directives must be conform " +
613 "in {f}".format(f=scope.getFileName()))
614 inMnh = False
615 toremove.append((elem, sElem)) # we remove the directive itself
616 # We add, to the tail of outer DO loop, the tail of the
617 # directive (except one \n)
618 # pylint: disable-next=undefined-loop-variable
619 outer.tail += sElem.tail.replace('\n', '', 1) # keep all but one new line char
620 # previous item controls the position of ENDDO
621 elem[ie - 1].tail = elem[ie - 1].tail[:-2]
622
623 elif inMnh:
624 # This statement is between the opening and closing mnh directive
625 toremove.append((elem, sElem)) # we remove it from its old place
626 inner.insert(-1, sElem) # Insert first in the DO loop
627 # then update, providing new parent in argument
628 updateStmt(sElem, table, kind, extraindent, inner, scope)
629
630 elif everywhere and tag(sElem) in ('a-stmt', 'if-stmt', 'where-stmt',
631 'where-construct'):
632 # This node could contain array-syntax
633
634 # Is the node written using array-syntax? Getting the first array...
635 if tag(sElem) == 'a-stmt':
636 # Left side of the assignment
637 arr = sElem.find('./{*}E-1/{*}named-E/{*}R-LT/{*}array-R/../..')
638 # Right side
639 isMemSet = False
640 isCopy = False
641 nodeE2 = sElem.find('./{*}E-2')
642 # Number of arrays using array-syntax
643 num = len(nodeE2.findall('.//{*}array-R'))
644 if num == 0:
645 # It is an array initialisation when there is no array-syntax
646 # on the right side
647 # If array-syntax is used without explicit '(:)', it could be
648 # detected as an initialisation
649 isMemSet = True
650 elif (len(nodeE2) == 1 and tag(nodeE2[0]) == 'named-E' and num == 1 and
651 nodeE2[0].find('.//{*}parens-R') is None):
652 # It is an array copy when there is only one child in the right
653 # hand side and this child is a named-E and this child contains only
654 # one array-R node and no parens-R
655 isCopy = True
656 # Discard?
657 if (isMemSet and not updateMemSet) or (isCopy and not updateCopy):
658 arr = None
659 elif tag(sElem) == 'if-stmt':
660 # We only deal with assignment in the if statement case
661 arr = sElem.find('./{*}action-stmt/{*}a-stmt/{*}E-1/' +
662 '{*}named-E/{*}R-LT/{*}array-R/../..')
663 if arr is not None:
664 # In this case we transform the if statement into an if-construct
665 scope.changeIfStatementsInIfConstructs(singleItem=sElem)
666 recur(sElem, scope) # to transform the content of the if
667 arr = None # to do nothing more on this node
668 elif tag(sElem) == 'where-stmt':
669 arr = sElem.find('./{*}mask-E//{*}named-E/{*}R-LT/{*}array-R/../..')
670 elif tag(sElem) == 'where-construct':
671 arr = sElem.find('./{*}where-block/{*}where-construct-stmt/' +
672 '{*}mask-E//{*}named-E/{*}R-LT/{*}array-R/../..')
673
674 # Check if it is written using array-syntax and must not be excluded;
675 # then compute bounds
676 if arr is None:
677 # There is no array-syntax
678 newtable = None
679 elif len(set(alltext(a).count(':')
680 for a in sElem.findall('.//{*}R-LT/{*}array-R'))) > 1:
681 # All the elements written using array-syntax don't have the same rank
682 # (can be due to function calls, eg: "X(:)=FUNC(Y(:,:))")
683 newtable = None
684 elif len(set(['ALL', 'ANY', 'COSHAPE', 'COUNT', 'CSHIFT', 'DIMENSION',
685 'DOT_PRODUCT', 'EOSHIFT', 'LBOUND', 'LCOBOUND', 'MATMUL',
686 'MAXLOC', 'MAXVAL', 'MERGE', 'MINLOC', 'MINVAL', 'PACK',
687 'PRODUCT', 'REDUCE', 'RESHAPE', 'SHAPE', 'SIZE', 'SPREAD',
688 'SUM', 'TRANSPOSE', 'UBOUND', 'UCOBOUND', 'UNPACK'] +
689 (funcList if funcList is not None else [])
690 ).intersection(set(n2name(nodeN) for nodeN
691 in sElem.findall('.//{*}named-E/{*}N')))) > 0:
692 # At least one intrinsic array function is used
693 newtable = None
694 else:
695 # Guess a variable name
696 if arr is not None:
697 newtable, varNew = scope.findArrayBounds(arr, loopVar, newVarList)
698 for var in varNew:
699 var['new'] = True
700 if var not in newVarList:
701 newVarList.append(var)
702 else:
703 newtable = None
704
705 if newtable is None:
706 # We cannot convert the statement (not in array-syntax,
707 # excluded or no variable found to loop)
708 inEverywhere = closeLoop(inEverywhere) # close previous loop if needed
709 else:
710 # we have to transform the statement
711 if not (inEverywhere and table == newtable):
712 # No opened previous loop, or not coresponding
713 inEverywhere = closeLoop(inEverywhere) # close previous loop, if needed
714 # We must create a DO loop
715 if ie != 0 and elem[ie - 1].tail is not None:
716 # Indentation of the current node, attached to the previous sibling
717 # get tail before transformation
718 tail = tailSave.get(elem[ie - 1], elem[ie - 1].tail)
719 indent = len(tail) - len(tail.rstrip(' '))
720 else:
721 indent = 0
722 table = newtable # save the information on the newly build loop
723 kind = None # not built from mnh directives
724 # Building loop
725 inner, outer, extraindent = scope.createDoConstruct(
726 table, indent=indent, concurrent=concurrent)
727 toinsert.append((elem, outer, ie)) # place to insert the loop
728 inEverywhere = (inner, outer, indent, extraindent) # we are now in loop
729 tailSave[sElem] = sElem.tail # save tail for future indentation computation
730 toremove.append((elem, sElem)) # we remove it from its old place
731 inner.insert(-1, sElem) # Insert first in the DO loop
732 # then update, providing new parent in argument
733 updateStmt(sElem, table, kind, extraindent, inner, scope)
734 if not reuseLoop:
735 # Prevent from reusing this DO loop
736 inEverywhere = closeLoop(inEverywhere)
737
738 else:
739 inEverywhere = closeLoop(inEverywhere) # close loop if needed
740 if len(sElem) >= 1:
741 # Iteration
742 recur(sElem, scope)
743 inEverywhere = closeLoop(inEverywhere)
744
745 for scope in self.getScopes():
746 recur(scope, scope)
747 # First, element insertion by reverse order (in order to keep the insertion index correct)
748 for elem, outer, ie in toinsert[::-1]:
749 elem.insert(ie, outer)
750 # Then, suppression
751 for parent, elem in toremove:
752 parent.remove(elem)
753 # And variable creation
754 for scopePath in sorted(set(v['scopePath'] for v in newVarList)):
755 self.getScopeNode(scopePath).addVar([(v['n'], f"INTEGER :: {v['n']}", None)
756 for v in newVarList
757 if v['scopePath'] == scopePath])
758
759 @debugDecor
760 @noParallel
761 @updateTree('signal')
762 @updateVarList
763 def inlineContainedSubroutines(self, simplify=False, loopVar=None):
764 """
765 Inline all contained subroutines into their parent.
766
767 Transforms contained subroutines (defined after CONTAINS) by:
768 1. Identifying contained subroutines
769 2. Finding all CALL statements to contained routines
770 3. Inlining the routine body where called
771 4. Removing the contained routine definitions
772
773 Parameters
774 ----------
775 simplify : bool, optional
776 If True, simplify code by removing empty constructs
777 and unused variables after inlining. Default is False.
778 loopVar : callable or None, optional
779 Function to determine loop index variable name for ELEMENTAL
780 subroutine calls on arrays.
781 Takes: (lowerDecl, upperDecl, lowerUsed, upperUsed, name, index)
782 Returns: str, True (auto-generate), or False (skip).
783
784 Examples
785 --------
786 >>> pft = PYFT('input.F90')
787 >>> pft.inlineContainedSubroutines()
788 >>> pft.write()
789
790 Notes
791 -----
792 - ELEMENTAL subroutines called on arrays get wrapped in DO loops.
793 - Optional arguments are handled (PRESENT checks are added/removed).
794 - Variables in contained routines may be renamed to avoid conflicts.
795 - Empty CONTAINS sections are removed when simplify=True.
796 """
797
798 scopes = self.getScopes()
799
800 # Inline contained subroutines : look for sub: / sub:
801 containedRoutines = {}
802 for scope in scopes:
803 if scope.path.count('sub:') >= 2:
804 containedRoutines[alltext(scope.find('.//{*}subroutine-N/{*}N/{*}n'))] = scope
805 # Start by nested contained subroutines call, and end up with the last index = the main
806 # subroutine to treat
807 scopes.reverse()
808 # Loop on all subroutines (main + contained)
809 for scope in [scope for scope in scopes if scope.path.count('sub:') >= 1]:
810 # Loop on all CALL statements
811 for callStmtNn in scope.findall('.//{*}call-stmt/{*}procedure-designator/' +
812 '{*}named-E/{*}N/{*}n'):
813 for containedRoutine in [cr for cr in containedRoutines
814 if alltext(callStmtNn) == cr]:
815 # name of the routine called = a contained subroutine => inline
816 self.inline(containedRoutines[containedRoutine],
817 self.getParent(callStmtNn, level=4),
818 scope,
819 simplify=simplify, loopVar=loopVar)
820
821 for scope in scopes: # loop on all subroutines
822 if scope.path.count('sub:') >= 2:
823 # This is a contained subroutine
824 name = scope.path.split(':')[-1].upper() # Subroutine name
825 # All nodes refering the subroutine
826 nodes = [nodeN for nodeN in self.findall('.//{*}N')
827 if n2name(nodeN).upper() == name]
828 if all(nodeN in scope.iter() for nodeN in nodes):
829 # Subroutine name not used (apart in its definition scope),
830 # we suppress it from the CONTAINS part
831 self.remove(scope)
832 self.tree.signal(self) # Tree must be updated, only in this case
833
834 if simplify:
835 self.removeEmptyCONTAINS()
836
837 @debugDecor
838 @noParallel
839 @updateTree()
840 @updateVarList
841 def inline(self, subContained, callStmt, mainScope,
842 simplify=False, loopVar=None):
843 """
844 Inline a single contained subroutine at its call site.
845
846 This method performs the actual inlining of a contained subroutine
847 into the calling scope. It handles:
848 - ELEMENTAL subroutines with array arguments
849 - Optional arguments (PRESENT intrinsic)
850 - Variable name conflicts
851 - USE statement merging
852
853 Parameters
854 ----------
855 subContained : xml element
856 XML fragment corresponding to the contained subroutine scope.
857 callStmt : xml element
858 The call-stmt node to replace with inlined code.
859 mainScope : PYFTscope
860 Scope of the main (calling) subroutine.
861 simplify : bool, optional
862 If True, remove empty constructs and unused variables
863 after inlining. Default is False.
864 loopVar : callable or None, optional
865 Function to determine loop index variable name.
866 Used when inlining ELEMENTAL subroutines called on arrays.
867 Takes: (lowerDecl, upperDecl, lowerUsed, upperUsed, name, index)
868 Returns: str, True (auto-generate), or False (skip).
869
870 Notes
871 -----
872 - For ELEMENTAL subroutines on arrays: DO loops are introduced.
873 - Optional arguments: PRESENT(var) is replaced with .TRUE. or .FALSE.
874 - Missing optional arguments: code paths using them are removed.
875 - Name conflicts: local variables are renamed with _N suffixes.
876 """
877 def setPRESENTby(node, var, val):
878 """
879 Replace PRESENT(var) by .TRUE. if val is True, by .FALSE. otherwise on node
880 if var is found
881 :param node: xml node to work on (a contained subroutine)
882 :param var: string of the name of the optional variable to check
883 """
884 for namedE in node.findall('.//{*}named-E/{*}N/..'):
885 if n2name(namedE.find('./{*}N')).upper() == 'PRESENT':
886 presentarg = n2name(namedE.find('./{*}R-LT/{*}parens-R/{*}element-LT/'
887 '{*}element/{*}named-E/{*}N'))
888 if presentarg.upper() == var.upper():
889 for nnn in namedE[:]:
890 namedE.remove(nnn)
891 namedE.tag = f'{{{NAMESPACE}}}literal-E'
892 namedE.text = '.TRUE.' if val else '.FALSE.'
893
894 # Get parent of callStmt
895 parent = mainScope.getParent(callStmt)
896
897 # Expand the if-construct if the call-stmt is in a one-line if-construct
898 if tag(parent) == 'action-stmt':
899 mainScope.changeIfStatementsInIfConstructs(mainScope.getParent(parent))
900 parent = mainScope.getParent(callStmt) # update parent
901
902 # Specific case for ELEMENTAL subroutines
903 # Introduce DO-loops if it is called on arrays
904 prefix = subContained.findall('.//{*}prefix')
905 if len(prefix) > 0 and 'ELEMENTAL' in [p.text.upper() for p in prefix]:
906 # Add missing parentheses
907 mainScope.addArrayParenthesesInNode(callStmt)
908
909 # Add explcit bounds
910 mainScope.addExplicitArrayBounds(node=callStmt)
911
912 # Detect if subroutine is called on arrays
913 arrayRincallStmt = callStmt.findall('.//{*}array-R')
914 if len(arrayRincallStmt) > 0: # Called on arrays
915 # Look for an array affectation to guess the DO loops to put around the call
916 table, _ = mainScope.findArrayBounds(mainScope.getParent(arrayRincallStmt[0], 2),
917 loopVar)
918
919 # Add declaration of loop index if missing
920 for varName in table.keys():
921 if not mainScope.varList.findVar(varName):
922 var = {'as': [], 'asx': [],
923 'n': varName, 'i': None, 't': 'INTEGER', 'arg': False,
924 'use': False, 'opt': False, 'allocatable': False,
925 'parameter': False, 'init': None, 'scopePath': mainScope.path}
926 mainScope.addVar([[var['n'], mainScope.varSpec2stmt(var), None]])
927
928 # Create the DO loops
929 inner, outer, _ = mainScope.createDoConstruct(table)
930
931 # Move the call statement in the DO loops
932 inner.insert(-1, callStmt) # callStmt in the DO-loops
933 # DO-loops near the original call stmt
934 parent.insert(list(parent).index(callStmt), outer)
935 parent.remove(callStmt) # original call stmt removed
936 parent = inner # Update parent
937 for namedE in callStmt.findall('./{*}arg-spec/{*}arg/{*}named-E'):
938 # Replace slices by indexes if any
939 if namedE.find('./{*}R-LT'):
940 mainScope.arrayR2parensR(namedE, table)
941
942 # Deep copy the object to possibly modify the original one multiple times
943 node = copy.deepcopy(subContained)
944
945 # Get local variables that are not present in the main routine for later addition
946 localVarToAdd = []
947 subst = []
948 varList = copy.deepcopy(self.varList) # Copy to be able to update it with pending changes
949 for var in [var for var in varList.restrict(subContained.path, True)
950 if not var['arg'] and not var['use']]:
951
952 if varList.restrict(mainScope.path, True).findVar(var['n']):
953 # Variable is already defined in main or upper, there is a name conflict,
954 # the local variable must be renamed before being declared in the main routine
955 newName = re.sub(r'_\d+$', '', var['n'])
956 i = 1
957 while (varList.restrict(subContained.path, True).findVar(newName + '_' + str(i)) or
958 varList.restrict(mainScope.path, True).findVar(newName + '_' + str(i))):
959 i += 1
960 newName += '_' + str(i)
961 node.renameVar(var['n'], newName)
962 subst.append((var['n'], newName))
963 var['n'] = newName
964 # important for varList.findVar(.., mainScope.path) to find it
965 var['scopePath'] = mainScope.path
966 localVarToAdd.append(var)
967
968 # In case a substituted variable is used in the declaration of another variable
969 for oldName, newName in subst:
970 for var in localVarToAdd + varList[:]:
971 if var['as'] is not None:
972 var['as'] = [[re.sub(r'\b' + oldName + r'\b', newName, dim[i])
973 if dim[i] is not None else None
974 for i in (0, 1)]
975 for dim in var['as']]
976
977 # Remove all objects that is implicit none, comment or else until reach
978 # something interesting
979 # USE statements are stored for later user
980 # subroutine-stmt and end-subroutine-stmt are kept to ensure consistency
981 # (for removeStmtNode with simplify)
982 localUseToAdd = node.findall('./{*}use-stmt')
983 for sNode in node.findall('./{*}T-decl-stmt') + localUseToAdd + \
984 node.findall('./{*}implicit-none-stmt'):
985 node.remove(sNode)
986 icom = 1
987 while tag(node[icom]) == 'C':
988 if node[icom].text.startswith('!$acc'):
989 if 'routine' in node[icom].text:
990 node.remove(node[icom])
991 else:
992 icom += 1
993 else:
994 node.remove(node[icom])
995
996 # Variable correspondance
997 # For each dummy argument, we look for the calling arg name and shape
998 # CALL FOO(Z(:))
999 # SUBROUTINE FOO(P)
1000 # variable = {'P':{'name': 'Z', dim=[':']}}
1001 vartable = {} # ordered dict
1002 for argN in subContained.findall('.//{*}subroutine-stmt/{*}dummy-arg-LT/{*}arg-N'):
1003 vartable[alltext(argN).upper()] = None # Not present by default
1004 for iarg, arg in enumerate(callStmt.findall('.//{*}arg')):
1005 key = arg.find('.//{*}arg-N')
1006 if key is not None:
1007 # arg is VAR=value
1008 dummyName = alltext(key).upper()
1009 argnode = arg[1]
1010 else:
1011 dummyName = list(vartable.keys())[iarg]
1012 argnode = arg[0]
1013 nodeRLTarray = argnode.findall('.//{*}R-LT/{*}array-R')
1014 if len(nodeRLTarray) > 0:
1015 # array
1016 if len(nodeRLTarray) > 1 or \
1017 argnode.find('./{*}R-LT/{*}array-R') is None or \
1018 tag(argnode) != 'named-E':
1019 # Only simple cases are treated
1020 raise PYFTError('Argument to complicated: ' + str(alltext(argnode)))
1021 dim = nodeRLTarray[0].find('./{*}section-subscript-LT')[:]
1022 else:
1023 dim = None
1024 if dim is None:
1025 # A%B => argname = 'A%B'
1026 # Z(1) => argname = 'Z(1)'
1027 argname = "".join(argnode.itertext())
1028 else:
1029 # Z(:) => argname = 'Z'
1030 tmp = copy.deepcopy(argnode)
1031 nodeRLT = tmp.find('./{*}R-LT')
1032 nodeRLT.remove(nodeRLT.find('./{*}array-R'))
1033 argname = "".join(tmp.itertext())
1034 vartable[dummyName] = {'node': argnode, 'name': argname, 'dim': dim}
1035
1036 # Look for PRESENT(var) and replace it by True when variable is present, by False otherwise
1037 for dummyName in [dummyName for (dummyName, value) in vartable.items()
1038 if value is not None]:
1039 setPRESENTby(node, dummyName, True)
1040 for dummyName in [dummyName for (dummyName, value) in vartable.items()
1041 if value is None]:
1042 setPRESENTby(node, dummyName, False)
1043
1044 # Look for usage of variable not present and delete corresponding code
1045 for dummyName in [dummyName for (dummyName, value) in vartable.items() if value is None]:
1046 for nodeN in [nodeN for nodeN in node.findall('.//{*}named-E/{*}N')
1047 if n2name(nodeN).upper() == dummyName]:
1048 removed = False
1049 # Parent is the named-E node, we need at least the upper level
1050 par = node.getParent(nodeN, level=2)
1051 allreadySuppressed = []
1052 while par and not removed and par not in allreadySuppressed:
1053 toSuppress = None
1054 tagName = tag(par)
1055 if tagName in ('a-stmt', 'print-stmt'):
1056 # Context 1: an a-stmt of type E1 = E2
1057 toSuppress = par
1058 elif tagName == 'call-stmt':
1059 # We should rewrite the call statement without this optional argument
1060 # But it is not easy: we must check that the argument is really optional
1061 # for the called routine and we must add (if not already present)
1062 # keywords for following arguments
1063 raise NotImplementedError('call-stmt not (yet?) implemented')
1064 elif tagName in ('if-stmt', 'where-stmt'):
1065 # Context 2: an if-stmt of type : IF(variable) ...
1066 toSuppress = par
1067 elif tagName in ('if-then-stmt', 'else-if-stmt', 'where-construct-stmt',
1068 'else-where-stmt'):
1069 # Context 3: an if-block of type : IF(variable) THEN...
1070 # We delete the entire construct
1071 toSuppress = node.getParent(par, 2)
1072 elif tagName in ('select-case-stmt', 'case-stmt'):
1073 # Context 4: SELECT CASE (variable)... or CASE (variable)
1074 # We deleted the entire construct
1075 toSuppress = node.getParent(par, 2)
1076 elif tagName.endswith('-block') or tagName.endswith('-stmt') or \
1077 tagName.endswith('-construct'):
1078 # action-stmt, do-stmt, forall-construct-stmt, forall-stmt,
1079 # if-block, where-block, selectcase-block,
1080 # must not contain directly
1081 # the variable but must contain other statements using the variable.
1082 # We target the inner statement in the previous cases.
1083 # Some cases may have been overlooked and should be added above.
1084 raise PYFTError(("We shouldn't be here. A case may have been " +
1085 "overlooked (tag={tag}).".format(tag=tagName)))
1086 if toSuppress is not None:
1087 removed = True
1088 if toSuppress not in allreadySuppressed:
1089 # We do not simplify variables to prevent side-effect with
1090 # the variable renaming
1091 node.removeStmtNode(toSuppress, False, simplify)
1092 allreadySuppressed.extend(list(toSuppress.iter()))
1093 else:
1094 par = node.getParent(par)
1095
1096 # Loop on the dummy argument
1097 for name, dummy in vartable.items():
1098 # Loop on all variables in the contained routine
1099 # It is important to build again the list of nodes, because it may have
1100 # changed during the previous dummy argument substitution
1101 for namedE in [namedE for namedE in node.findall('.//{*}named-E/{*}N/{*}n/../..')
1102 if n2name(namedE.find('{*}N')).upper() == name]:
1103 # 0 Concatenation of n nodes (a name could be split over several n nodes)
1104 nodeN = namedE.find('./{*}N')
1105 ns = nodeN.findall('./{*}n')
1106 ns[0].text = n2name(nodeN)
1107 for nnn in ns[1:]:
1108 nodeN.remove(nnn)
1109
1110 # 1 We get info about variables (such as declared in the main or in
1111 # the contained routines)
1112 descMain = varList.restrict(mainScope.path, True).findVar(dummy['name'])
1113 descSub = varList.restrict(subContained.path, True).findVar(name)
1114 # In case variable is used for the declaration of another variable,
1115 # we must update descSub
1116 for var in varList:
1117 if var['as'] is not None:
1118 var['as'] = [[re.sub(r'\b' + name + r'\b', dummy['name'], dim[i])
1119 if dim[i] is not None else None
1120 for i in (0, 1)]
1121 for dim in var['as']]
1122
1123 # 3 We select the indexes (only for array argument and not structure argument
1124 # containing an array)
1125 # using the occurrence to replace inside the subcontained routine body
1126 nodeRLT = namedE.find('./{*}R-LT')
1127 if nodeRLT is not None and tag(nodeRLT[0]) != 'component-R':
1128 # The variable name is immediately followed by a parenthesis
1129 assert tag(nodeRLT[0]) in ('array-R', 'parens-R'), 'Internal error'
1130 slices = nodeRLT[0].findall('./{*}section-subscript-LT/' +
1131 '{*}section-subscript')
1132 slices += nodeRLT[0].findall('./{*}element-LT/{*}element')
1133 else:
1134 # No parenthesis
1135 if (descMain is not None and descMain['as'] is not None and
1136 len(descMain['as']) > 0) or \
1137 len(descSub['as']) > 0 or dummy['dim'] is not None:
1138 # No parenthesis, but this is an array, we add as many ':' as needed
1139 if len(descSub['as']) > 0:
1140 ndim = len(descSub['as'])
1141 else:
1142 # ELEMENTAL routine, dummy arg is scalar
1143 if dummy['dim'] is not None:
1144 # We use the variable passed as argument because
1145 # parenthesis were used
1146 ndim = len([d for d in dummy['dim'] if ':' in alltext(d)])
1147 else:
1148 # We use the declared version in main
1149 ndim = len(descMain['as'])
1150 ns[0].text += '(' + (', '.join([':'] * ndim)) + ')'
1151 updatedNamedE = createExprPart(alltext(namedE))
1152 namedE.tag = updatedNamedE.tag
1153 namedE.text = updatedNamedE.text
1154 for nnn in namedE[:]:
1155 namedE.remove(nnn)
1156 namedE.extend(updatedNamedE[:])
1157 slices = namedE.find('./{*}R-LT')[0].findall(
1158 './{*}section-subscript-LT/{*}section-subscript')
1159 else:
1160 # This is not an array
1161 slices = []
1162
1163 # 4 New name (the resultig xml is not necessarily a valid fxtran xml)
1164 namedE.find('./{*}N')[0].text = dummy['name']
1165
1166 # 5 We update the indexes to take into account a different declaration
1167 # (lower bound especially)
1168 # in the main and in the contained routines.
1169 # Moreover, we could need to add indexes
1170 if len(slices) > 0:
1171 # This is an array
1172 for isl, sl in enumerate(slices):
1173 # 0 Compute bounds for array
1174 if len(descSub['as']) == 0 or descSub['as'][isl][1] is None:
1175 # ELEMENTAL or array with implicit shape
1176 for i in (0, 1): # 0 for lower bound and 1 for upper bound
1177 if dummy['dim'] is not None:
1178 # Parenthesis in the call statement
1179 tagName = './{*}lower-bound' if i == 0 else './{*}upper-bound'
1180 descSub[i] = dummy['dim'][isl].find(tagName)
1181 else:
1182 descSub[i] = None
1183 if descSub[i] is not None:
1184 # lower/upper limit was given in the call statement
1185 descSub[i] = alltext(descSub[i])
1186 else:
1187 # if available we take lower/upper limit set in the declaration
1188 if descMain is not None and descMain['as'][isl][1] is not None:
1189 # Declaration found in main, and not using implicit shape
1190 descSub[i] = descMain['as'][isl][i]
1191 if i == 0 and descSub[i] is None:
1192 descSub[i] = '1' # Default FORTRAN value
1193 else:
1194 descSub[i] = "L" if i == 0 else "U"
1195 descSub[i] += "BOUND({name}, {isl})".format(
1196 name=dummy['name'], isl=isl + 1)
1197 else:
1198 descSub[0] = descSub['as'][isl][0]
1199 if descSub[0] is None:
1200 descSub[0] = '1' # Default FORTRAN value
1201 descSub[1] = descSub['as'][isl][1]
1202
1203 # 1 Offset computation
1204 # if only a subset is passed
1205 # and/or if lower bound of array is different in main and in sub
1206 # contained routine
1207 # REAL, DIMENSION(M1:M2):: Z; CALL FOO(N1:N2)
1208 # SUBROUTINE FOO(P); REAL, DIMENSION(K1:K2):: P; P(I1:I2)
1209 # If M1 or K1 is not set, they defaults to 1; if not set, N1 defaults to
1210 # M1 and I1 to K1
1211 # P(I1:I2)=Z(I1-K1+N1:I2-K1+N1)
1212 offset = 0
1213 if dummy['dim'] is not None and \
1214 not alltext(dummy['dim'][isl]).strip().startswith(':'):
1215 offset = alltext(dummy['dim'][isl].find('./{*}lower-bound'))
1216 else:
1217 if descMain is not None and descMain['as'] is not None:
1218 offset = descMain['as'][isl][0]
1219 if offset is None:
1220 offset = '1' # Default FORTRAN value
1221 elif offset.strip().startswith('-'):
1222 offset = '(' + offset + ')'
1223 else:
1224 offset = "LBOUND({name}, {isl})".format(
1225 name=dummy['name'], isl=isl + 1)
1226 if offset.upper() == descSub[0].upper():
1227 offset = 0
1228 else:
1229 if descSub[0].strip().startswith('-'):
1230 offset += '- (' + descSub[0] + ')'
1231 else:
1232 offset += '-' + descSub[0]
1233
1234 # 2 Update index with the offset and add indexes instead of ':'
1235 if offset != 0:
1236 if tag(sl) == 'element' or \
1237 (tag(sl) == 'section-subscript' and ':' not in alltext(sl)):
1238 # Z(I) or last index of Z(:, I)
1239 bounds = sl
1240 else:
1241 low = sl.find('./{*}lower-bound')
1242 if low is None:
1243 low = createElem('lower-bound', tail=sl.text)
1244 low.append(createExprPart(descSub[0]))
1245 sl.text = None
1246 sl.insert(0, low)
1247 up = sl.find('./{*}upper-bound')
1248 if up is None:
1249 up = createElem('upper-bound')
1250 up.append(createExprPart(descSub[1]))
1251 sl.append(up)
1252 bounds = [low, up]
1253 for bound in bounds:
1254 # bound[-1] is a named-E, literal-E, op-E...
1255 if bound[-1].tail is None:
1256 bound[-1].tail = ''
1257 bound[-1].tail += '+' + offset # Not valid fxtran xml
1258
1259 # We must add extra indexes
1260 # CALL FOO(Z(:,1))
1261 # SUBROUTINE FOO(P); REAL, DIMENSION(K1:K2):: P
1262 # P(I) => Z(I, 1)
1263 if dummy['dim'] is not None and len(dummy['dim']) > len(slices):
1264 slices[-1].tail = ', '
1265 par = node.getParent(slices[-1])
1266 par.extend(dummy['dim'][len(slices):])
1267
1268 # 6 Convert (wrong) xml into text and into xml again (to obtain a valid fxtran xml)
1269 # This double conversion is not sufficient in some case.
1270 # E.g. variable (N/n tag) replaced by real value
1271 updatedNamedE = createExprPart(alltext(namedE))
1272 namedE.tag = updatedNamedE.tag
1273 namedE.text = updatedNamedE.text
1274 for nnn in namedE[:]:
1275 namedE.remove(nnn)
1276 namedE.extend(updatedNamedE[:])
1277
1278 node.remove(node.find('./{*}subroutine-stmt'))
1279 node.remove(node.find('./{*}end-subroutine-stmt'))
1280
1281 # Add local var and use to main routine
1282 mainScope.addVar([[var['n'], mainScope.varSpec2stmt(var), None]
1283 for var in localVarToAdd])
1284 mainScope.addModuleVar([[n2name(useStmt.find('.//{*}module-N//{*}N')),
1285 [n2name(v.find('.//{*}N'))
1286 for v in useStmt.findall('.//{*}use-N')]]
1287 for useStmt in localUseToAdd])
1288
1289 # Remove call statement of the contained routines
1290 index = list(parent).index(callStmt)
1291 parent.remove(callStmt)
1292 if callStmt.tail is not None:
1293 if node[-1].tail is None:
1294 node[-1].tail = callStmt.tail
1295 else:
1296 node[-1].tail = node[-1].tail + callStmt.tail
1297 for node in node[::-1]:
1298 # node is a program-unit, we must insert the subelements
1299 parent.insert(index, node)
1300
1301 @debugDecor
1302 def setFalseIfStmt(self, flags, simplify=False):
1303 """
1304 Set conditional flags to .FALSE. in IF conditions.
1305
1306 Replaces specified flag variables in IF conditions with .FALSE.,
1307 effectively disabling code paths controlled by those flags.
1308
1309 Parameters
1310 ----------
1311 flags : str or list of str
1312 Flag variable name(s) to set to .FALSE.
1313 Can be a single string or a list of strings.
1314 simplify : bool, optional
1315 If True, remove resulting dead code:
1316 - IF blocks that always evaluate to .FALSE. are removed
1317 - Unused variables are cleaned up. Default is False.
1318
1319 Examples
1320 --------
1321 >>> pft = PYFT('input.F90')
1322 >>> pft.setFalseIfStmt('LFLAG') # IF (LFLAG) -> .FALSE.
1323 >>> pft.setFalseIfStmt(['LFLAG1', 'LFLAG2'], simplify=True)
1324
1325 Before:
1326 IF (LDEBUG) THEN
1327 PRINT*, "Debug info"
1328 END IF
1329
1330 After (LDEBUG set to .FALSE.):
1331 ! Block removed when simplify=True
1332
1333 Notes
1334 -----
1335 - Multiple flags in a single condition (e.g., LFLAG1 .AND. LFLAG2)
1336 result in removal of the entire condition.
1337 - Works on both IF statements and IF constructs.
1338 """
1339 if isinstance(flags, str):
1340 flags = [flags]
1341 flags = [flag.upper() for flag in flags]
1342 for scope in self.getScopes(excludeKinds=['type']):
1343 singleFalseBlock, multipleFalseBlock = [], []
1344 # Loop on condition nodes
1345 for cond in scope.findall('.//{*}condition-E'):
1346 found = False
1347 for namedE in [namedE for namedE
1348 in cond.findall('.//{*}named-E')
1349 if alltext(namedE).upper() in flags]:
1350 # This named-E must be replaced by .FALSE.
1351 found = True
1352 namedE.tag = '{{{NAMESPACE}}}literal-E'
1353 namedE.text = '.FALSE.'
1354 for item in list(namedE):
1355 namedE.remove(item)
1356 if found:
1357 nodeOpE = cond.find('./{*}op-E')
1358 if nodeOpE is not None:
1359 # Multiple flags conditions
1360 multipleFalseBlock.append(nodeOpE)
1361 else:
1362 # Solo condition
1363 if tag(scope.getParent(cond)).startswith('if-stmt'):
1364 scope.changeIfStatementsInIfConstructs(scope.getParent(cond))
1365 # <if-construct><if-block><if-then-stmt>IF (<f:condition-E>
1366 singleFalseBlock.append(scope.getParent(cond, level=3)) # if-construct
1367 if simplify:
1368 scope.removeStmtNode(singleFalseBlock, simplify, simplify)
1369 scope.evalFalseIfStmt(multipleFalseBlock, simplify)
1370
1371 @debugDecor
1372 def evalFalseIfStmt(self, nodes, simplify=False):
1373 """
1374 Evaluate if-stmt with multiple op-E and remove the nodes if only .FALSE. are present
1375 :param nodes: list of nodes of type op-E to evaluate (containing .FALSE.)
1376 :param simplify: try to simplify code (if if-block is removed, variables used in the
1377 if condition are also checked)
1378 """
1379 nodesTorm = []
1380 for node in nodes:
1381 toRemove = True
1382 for nnn in node:
1383 if tag(nnn) == 'op' or (tag(nnn) == 'literal-E' and '.FALSE.' in alltext(nnn)):
1384 pass
1385 else:
1386 toRemove = False
1387 break
1388 if toRemove:
1389 # <if-block><if-then-stmt><condition-E>
1390 nodesTorm.append(self.getParent(level=3))
1391 self.removeStmtNode(nodesTorm, simplify, simplify)
1392
1393 @debugDecor
1394 def checkOpInCall(self, mustRaise=False):
1395 """
1396 :param mustRaise: True to raise
1397 Issue a logging.warning if some call arguments are operations
1398 If mustRaise is True, issue a logging.error instead and raise an error
1399 """
1400 ok = True
1401 log = logging.error if mustRaise else logging.warning
1402 for arg in self.findall('.//{*}call-stmt/{*}arg-spec/{*}arg/{*}op-E'):
1403 log(("The call argument {} is an operation, in file '{}'"
1404 ).format(alltext(arg).replace('\n', ' \\n '), self.getFileName()))
1405 ok = False
1406 if not ok and mustRaise:
1407 raise PYFTError(("There are call arguments which are operations in file '{}'"
1408 ).format(self.getFileName()))
1409 return ok
1410
1411 @debugDecor
1412 def checkEmptyParensInCall(self, mustRaise=False):
1413 """
1414 :param mustRaise: True to raise
1415 Issue a logging.warning if some call arguments are arrays with empty parens
1416 Example: CALL FOO(A(:))
1417 If mustRaise is True, issue a logging.error instead and raise an error
1418 """
1419 ok = True
1420 log = logging.error if mustRaise else logging.warning
1421 for sslt in self.findall('.//{*}call-stmt/{*}arg-spec/{*}arg/{*}named-E/' +
1422 '{*}R-LT/{*}array-R/{*}section-subscript-LT'):
1423 if all(alltext(ss) == ':' for ss in sslt.findall('./{*}section-subscript')):
1424 arg = self.getParent(sslt, 3)
1425 log(("The call argument {} is an array with empty parens, in file '{}'"
1426 ).format(alltext(arg).replace('\n', ' \\n '), self.getFileName()))
1427 ok = False
1428 if not ok and mustRaise:
1429 raise PYFTError(("There are call arguments which are arrays " +
1430 "with empty parens in file '{}'").format(self.getFileName()))
1431 return ok
1432
1433 @staticmethod
1434 def isArrayIndexSelection(node, getParent, getScope):
1435 """
1436 Tell if an array-R or parens-R node is an array index selection.
1437
1438 Because, syntactically, it is not possible to distinguish between an array
1439 element and a function call (e.g. 'F(1, 2)'), a node is considered as an
1440 array index selection:
1441
1442 - if it is an array-R node (index selection containing at least one ':'), or
1443 - if it is a parens-R node directly following a name declared as an array
1444 in the varList (for structure components, e.g. 'X%Y(1, 2)', the
1445 declaration is not available and the node is not considered as an array
1446 index selection).
1447
1448 Parameters
1449 ----------
1450 node : xml element
1451 array-R or parens-R node.
1452 getParent : callable
1453 Function returning the parent of an xml node.
1454 getScope : callable
1455 Function returning the scope (PYFTscope) containing an xml node.
1456
1457 Returns
1458 -------
1459 bool
1460 True if node is an array index selection.
1461 """
1462 if tag(node) == 'array-R':
1463 # Subscripts with at least one ':'
1464 return True
1465 if tag(node) != 'parens-R':
1466 return False
1467 # parens-R: array element or function call
1468 rlt = getParent(node)
1469 if rlt[0] is not node:
1470 # parens-R after a component-R (or another parens-R): we cannot
1471 # retrieve the declaration
1472 return False
1473 name = n2name(getParent(rlt).find('./{*}N'))
1474 return getScope(node).varList.findVar(name, array=True) is not None
1475
1476 @debugDecor
1477 def checkContinuationInArraySection(self, mustRaise=False):
1478 """
1479 Check that array index selections are not split over several lines.
1480
1481 Issue a logging.warning if a continuation line ('&') is found inside the
1482 parentheses of an array index selection. Example of invalid code:
1483
1484 A(:, :) = B(:, &
1485 &:)
1486
1487 Because, syntactically, it is not possible to distinguish between an array
1488 element and a function call (e.g. 'F(1, 2)'), the parentheses are checked only:
1489
1490 - if they contain at least one ':' (array section), or
1491 - if the name is declared as an array in the varList (for structure
1492 components, e.g. 'X%Y(1, 2)', the declaration is not available and the
1493 parentheses are checked only if they contain a ':').
1494
1495 Function calls and arguments of CALL statements are not concerned.
1496
1497 Parameters
1498 ----------
1499 mustRaise : bool, optional
1500 If True, issue a logging.error instead of a logging.warning
1501 and raise a PYFTError. Default is False.
1502
1503 Returns
1504 -------
1505 bool
1506 True if no continuation line was found inside an index selection.
1507
1508 Raises
1509 ------
1510 PYFTError
1511 If mustRaise is True and a continuation line is found.
1512
1513 Examples
1514 --------
1515 >>> pft = PYFT('input.F90')
1516 >>> pft.checkContinuationInArraySection() # Only warn
1517 >>> pft.checkContinuationInArraySection(mustRaise=True) # Raise on error
1518 """
1519 ok = True
1520 log = logging.error if mustRaise else logging.warning
1521 scopes = None # dictionary of scopes, built only if needed
1522
1523 def getScope(node):
1524 nonlocal scopes
1525 if scopes is None:
1526 scopes = {scope.path: scope for scope in self.getScopes()}
1527 return scopes[self.getScopePath(node)]
1528
1529 # Array index selections containing a continuation
1530 parens = [node for node in self.findall('.//{*}R-LT/*')
1531 if tag(node) in ('array-R', 'parens-R') and
1532 node.find('.//{*}cnt') is not None and
1533 self.isArrayIndexSelection(node, self.getParent, getScope)]
1534 # Report only the outermost ones (nested selections would be reported twice)
1535 nested = {id(sub) for node in parens for sub in node.iter() if sub is not node}
1536 for node in [node for node in parens if id(node) not in nested]:
1537 arg = self.getParent(node, 2) # named-E/R-LT/(array-R|parens-R)
1538 log(("The index selection {} is split over several lines, in file '{}'"
1539 ).format(alltext(arg).replace('\n', ' \\n '), self.getFileName()))
1540 ok = False
1541 if not ok and mustRaise:
1542 raise PYFTError(("There are index selections split over several lines " +
1543 "in file '{}'").format(self.getFileName()))
1544 return ok
1545
1546 @debugDecor
1547 def insertStatement(self, stmt, first):
1548 """
1549 Insert a statement to be executed first (or last)
1550 :param stmt: statement to insert
1551 :param first: True to insert it in first position, False to insert it in last position
1552 :return: the index of the stmt inserted in scope
1553 """
1554 # pylint: disable=unsubscriptable-object
1555 if first:
1556 # Statement must be inserted after all use, T-decl, implicit-non-stmt,
1557 # interface and cray pointers
1558 nodes = self.findall('./{*}T-decl-stmt') + self.findall('./{*}use-stmt') + \
1559 self.findall('./{*}implicit-none-stmt') + \
1560 self.findall('./{*}interface-construct') + \
1561 self.findall('./{*}pointer-stmt')
1562 if len(nodes) > 0:
1563 # Insertion after the last node
1564 index = max([list(self).index(n) for n in nodes]) + 1
1565 else:
1566 # Insertion after the subroutine or function node
1567 index = 2
1568 # If an include statements follows, it certainly contains an interface
1569 while (tag(self[index]) in ('C', 'include', 'include-stmt') or
1570 (tag(self[index]) == 'cpp' and self[index].text.startswith('#include'))):
1571 if not self[index].text.startswith('!$acc'):
1572 index += 1
1573 else:
1574 break
1575 else:
1576 # Statement must be inserted before the contains statement
1577 contains = self.find('./{*}contains-stmt')
1578 if contains is not None:
1579 # Insertion before the contains statement
1580 index = list(self).index(contains)
1581 else:
1582 # Insertion before the end subroutine or function statement
1583 index = -1
1584 if self[index - 1].tail is None:
1585 self[index - 1].tail = '\n'
1586 elif '\n' not in self[index - 1].tail:
1587 self[index - 1].tail += '\n'
1588 self.insert(index, stmt)
1589 return index
1590
1591 @debugDecor
1592 def removeStmtNode(self, nodes, simplifyVar, simplifyStruct):
1593 """
1594 Remove statement nodes with optional code simplification.
1595
1596 Parameters
1597 ----------
1598 nodes : xml element or list of xml elements
1599 Node(s) to remove from the code tree.
1600 simplifyVar : bool
1601 If True, also remove variables that become unused after
1602 the deletion of the nodes.
1603 simplifyStruct : bool
1604 If True, also remove empty enclosing constructs
1605 (IF blocks, loops) that become empty after node removal.
1606
1607 Examples
1608 --------
1609 >>> pft = PYFT('input.F90')
1610 >>> nodes = pft.findall('.//{*}call-stmt')
1611 >>> pft.removeStmtNode(nodes, simplifyVar=True, simplifyStruct=True)
1612
1613 Notes
1614 -----
1615 - Handles nested structures (removes inner statements first).
1616 - When simplifyStruct=True:
1617 - Empty IF blocks are removed
1618 - Empty loops are removed
1619 - WHERE constructs are handled
1620 - When simplifyVar=True:
1621 - Unused local variables are removed
1622 - Empty type declarations are cleaned up
1623 """
1624
1625 # In case the suppression of an if-stmt or where-stmt is asked,
1626 # we must start by the inner statement
1627 nodesToSuppress = []
1628 if not isinstance(nodes, list):
1629 nodes = [nodes]
1630 for node in nodes:
1631 if tag(node) in ('if-stmt', 'where-stmt'):
1632 action = node.find('./{*}action-stmt')
1633 if action is not None and len(action) != 0:
1634 nodesToSuppress.append(action[0])
1635 else:
1636 nodesToSuppress.append(node)
1637 elif tag(node) == '}action-stmt':
1638 if len(node) != 0:
1639 nodesToSuppress.append(node[0])
1640 else:
1641 nodesToSuppress.append(node)
1642 else:
1643 nodesToSuppress.append(node)
1644
1645 varToCheck = [] # List of variables to check for suppression
1646 if simplifyVar:
1647 # Loop to identify all the potential variables to remove
1648 for node in nodesToSuppress:
1649 scopePath = self.getScopePath(node)
1650 if tag(node) == 'do-construct':
1651 # Try to remove variables used in the loop
1652 varToCheck.extend([(scopePath, n2name(arg))
1653 for arg in node.find('./{*}do-stmt').findall('.//{*}N')])
1654 elif tag(node) in ('if-construct', 'if-stmt'):
1655 # Try to remove variables used in the conditions
1656 varToCheck.extend([(scopePath, n2name(arg))
1657 for arg in node.findall('.//{*}condition-E//{*}N')])
1658 elif tag(node) in ('where-construct', 'where-stmt'):
1659 # Try to remove variables used in the conditions
1660 varToCheck.extend([(scopePath, n2name(arg))
1661 for arg in node.findall('.//{*}mask-E//{*}N')])
1662 elif tag(node) == 'call-stmt':
1663 # We must check if we can suppress the variables used to call the subprogram
1664 varToCheck.extend([(scopePath, n2name(arg))
1665 for arg in node.findall('./{*}arg-spec//{*}N')])
1666 # And maybe, the subprogram comes from a module
1667 varToCheck.append((scopePath,
1668 n2name(node.find('./{*}procedure-designator//{*}N'))))
1669 elif tag(node) in ('a-stmt', 'print-stmt'):
1670 varToCheck.extend([(scopePath, n2name(arg)) for arg in node.findall('.//{*}N')])
1671 elif tag(node) == 'selectcase-construct':
1672 # Try to remove variables used in the selector and in conditions
1673 varToCheck.extend([(scopePath, n2name(arg))
1674 for arg in node.findall('.//{*}case-E//{*}N')])
1675 varToCheck.extend([(scopePath, n2name(arg))
1676 for arg in node.findall('.//{*}case-value//{*}N')])
1677
1678 # Node suppression
1679 parents = {} # cache
1680 for node in nodesToSuppress:
1681 parent = self.getParent(node)
1682 parents[id(node)] = parent
1683 newlines = '\n' * (alltext(node).count('\n') if tag(node).endswith('-construct') else 0)
1684 if node.tail is not None or len(newlines) > 0:
1685 previous = self.getSiblings(node, after=False)
1686 if len(previous) == 0:
1687 previous = parent
1688 else:
1689 previous = previous[-1]
1690 if previous.tail is None:
1691 previous.tail = ''
1692 previous.tail = (previous.tail.replace('\n', '') +
1693 (node.tail if node.tail is not None else ''))
1694 parent.remove(node)
1695
1696 # Variable simplification
1697 for scopePath in sorted(set(scopePath for scopePath, _ in varToCheck)):
1698 self.getScopeNode(scopePath).removeVarIfUnused(
1699 [name for path, name in varToCheck if path == scopePath],
1700 excludeDummy=True, excludeModule=True, simplify=simplifyVar)
1701
1702 # List the new nodes to suppress
1703 newNodesToSuppress = []
1704 for node in nodesToSuppress:
1705 parent = parents[id(node)]
1706 # If we have suppressed the statement in a if statement (one-line if) or where statement
1707 # we must suppress the entire if/where statement even when simplifyStruct is False
1708 if tag(parent) == 'action-stmt':
1709 newNodesToSuppress.append(self.getParent(parent))
1710
1711 elif simplifyStruct:
1712 if tag(parent) == 'do-construct' and len(_nodesInDo(parent)) == 0:
1713 newNodesToSuppress.append(parent)
1714 elif tag(parent) == 'if-block':
1715 parPar = self.getParent(parent)
1716 if len(_nodesInIf(parPar)) == 0:
1717 newNodesToSuppress.append(parPar)
1718 elif tag(parent) == 'where-block':
1719 parPar = self.getParent(parent)
1720 if len(_nodesInWhere(parPar)) == 0:
1721 newNodesToSuppress.append(parPar)
1722 elif tag(parent) == 'selectcase-block':
1723 parPar = self.getParent(parent)
1724 if len(_nodesInCase(parPar)) == 0:
1725 newNodesToSuppress.append(parPar)
1726
1727 constructNodes, otherNodes = [], []
1728 for nnn in newNodesToSuppress:
1729 if tag(nnn).endswith('-construct'):
1730 if nnn not in constructNodes:
1731 constructNodes.append(nnn)
1732 else:
1733 if nnn not in otherNodes:
1734 otherNodes.append(nnn)
1735 # suppress all statements at once
1736 if len(otherNodes) > 0:
1737 self.removeStmtNode(otherNodes, simplifyVar, simplifyStruct)
1738 # suppress construct nodes one by one (recursive call)
1739 for nnn in constructNodes:
1740 self.removeConstructNode(nnn, simplifyVar, simplifyStruct)
1741
1742 @debugDecor
1743 def removeConstructNode(self, node, simplifyVar, simplifyStruct):
1744 """
1745 This function removes a construct node and:
1746 - suppress variable that became useless (if simplifyVar is True)
1747 - suppress outer loop/if if useless (if simplifyStruct is True)
1748 :param node: node representing the statement to remove
1749 :param simplifyVar: try to simplify code (if we delete "CALL FOO(X)" and if X not used
1750 else where, we also delete it; or if the call was alone inside a
1751 if-then-endif construct, with simplifyStruct=True, the construct is also
1752 removed, and variables used in the if condition are also checked...)
1753 :param simplifyStruct: try to simplify code (if we delete "CALL FOO(X)" and if the call was
1754 alone inside a if-then-endif construct, the construct is also
1755 removed, and variables used in the if condition
1756 (with simplifyVar=True) are also checked...)
1757
1758 If a statement is passed, it is suppressed by removeStmtNode
1759 """
1760 assert tag(node).endswith('-stmt') or tag(node).endswith('-construct'), \
1761 "Don't know how to suppress only a part of a structure or of a statement"
1762
1763 # This function removes inner statement to give a chance to identify and suppress unused
1764 # variables
1765 # During this step, nodes are suppressed with simplifyStruct=False to prevent infinite loops
1766 # then the actual node is removed using removeStmtNode
1767
1768 if tag(node).endswith('-construct'):
1769 # inner nodes
1770 nodes = {'do-construct': _nodesInDo,
1771 'if-construct': _nodesInIf,
1772 'where-construct': _nodesInWhere,
1773 'selectcase-construct': _nodesInCase}[tag(node)](node)
1774 # sort nodes by type
1775 constructNodes, otherNodes = [], []
1776 for nnn in nodes:
1777 if tag(nnn).endswith('-construct'):
1778 constructNodes.append(nnn)
1779 else:
1780 otherNodes.append(nnn)
1781 # suppress all statements at once
1782 self.removeStmtNode(otherNodes, simplifyVar, False)
1783 # suppress construct nodes one by one (recursive call)
1784 for nnn in constructNodes:
1785 self.removeConstructNode(nnn, simplifyVar, False)
1786 # suppress current node
1787 self.removeStmtNode(node, simplifyVar, simplifyStruct)
1788 else:
1789 # At least a-stmt, print-stmt
1790 self.removeStmtNode(node, simplifyVar, simplifyStruct)
1791
1792 @staticmethod
1793 @debugDecor
1794 def createDoConstruct(loopVariables, indent=0, concurrent=False):
1795 """
1796 :param loopVariables: ordered dictionnary with loop variables as key and bounds as values.
1797 Bounds are expressed with a 2-tuple.
1798 Keys must be in the same order as the order used when addressing an
1799 element: if loopVariables.keys is [JI, JK], arrays are
1800 addressed with (JI, JK)
1801 :param indent: current indentation
1802 :param concurrent: if False, output is made of nested 'DO' loops
1803 if True, output is made of a single 'DO CONCURRENT' loop
1804 :return: (inner, outer, extraindent) with
1805 - inner the inner do-construct where statements must be added
1806 - outer the outer do-construct to be inserted somewhere
1807 - extraindent the number of added indentation
1808 (2 if concurrent else 2*len(loopVariables))
1809 """
1810 if concurrent:
1811 # <f:do-construct>
1812 # <f:do-stmt>DO CONCURRENT (
1813 # <f:forall-triplet-spec-LT>
1814 # <f:forall-triplet-spec>
1815 # <f:V><f:named-E><f:N><f:n>JIJ</f:n></f:N></f:named-E></f:V>=
1816 # <f:lower-bound><f:named-E><f:N><f:n>IIJB</f:n>
1817 # </f:N></f:named-E></f:lower-bound>:
1818 # <f:upper-bound><f:named-E><f:N><f:n>IIJE</f:n>
1819 # </f:N></f:named-E></f:upper-bound>
1820 # </f:forall-triplet-spec>,
1821 # <f:forall-triplet-spec>
1822 # <f:V><f:named-E><f:N><f:n>JK</f:n></f:N></f:named-E></f:V>=
1823 # <f:lower-bound><f:literal-E><f:l>1</f:l></f:literal-E></f:lower-bound>:
1824 # <f:upper-bound><f:named-E><f:N><f:n>IKT</f:n>
1825 # </f:N></f:named-E></f:upper-bound>
1826 # </f:forall-triplet-spec>
1827 # </f:forall-triplet-spec-LT>)
1828 # </f:do-stmt>
1829 # statements
1830 # <f:end-do-stmt>END DO</f:end-do-stmt>
1831 # </f:do-construct>
1832 triplets = []
1833 # Better for vectorisation with some compilers
1834 for var, (lo, up) in list(loopVariables.items())[::-1]:
1835 nodeV = createElem('V', tail='=')
1836 nodeV.append(createExprPart(var))
1837 lower, upper = createArrayBounds(lo, up, 'DOCONCURRENT')
1838
1839 triplet = createElem('forall-triplet-spec')
1840 triplet.extend([nodeV, lower, upper])
1841
1842 triplets.append(triplet)
1843
1844 tripletLT = createElem('forall-triplet-spec-LT', tail=')')
1845 for triplet in triplets[:-1]:
1846 triplet.tail = ', '
1847 tripletLT.extend(triplets)
1848
1849 dostmt = createElem('do-stmt', text='DO CONCURRENT (', tail='\n')
1850 dostmt.append(tripletLT)
1851 enddostmt = createElem('end-do-stmt', text='END DO')
1852
1853 doconstruct = createElem('do-construct', tail='\n')
1854 doconstruct.extend([dostmt, enddostmt])
1855 inner = outer = doconstruct
1856 doconstruct[0].tail += (indent + 2) * ' ' # Indentation for the statement after DO
1857 else:
1858 # <f:do-construct>
1859 # <f:do-stmt>DO
1860 # <f:do-V><f:named-E><f:N><f:n>JRR</f:n></f:N></f:named-E></f:do-V> =
1861 # <f:lower-bound><f:literal-E><f:l>1</f:l></f:literal-E></f:lower-bound>:
1862 # <f:upper-bound><f:named-E><f:N><f:n>IKT</f:n></f:N></f:named-E></f:upper-bound>
1863 # </f:do-stmt>\n
1864 # statements \n
1865 # <f:end-do-stmt>END DO</f:end-do-stmt>
1866 # </f:do-construct>\n
1867 def makeDo(var, lo, up):
1868 doV = createElem('do-V', tail='=')
1869 doV.append(createExprPart(var))
1870 lower, upper = createArrayBounds(lo, up, 'DO')
1871
1872 dostmt = createElem('do-stmt', text='DO ', tail='\n')
1873 dostmt.extend([doV, lower, upper])
1874
1875 enddostmt = createElem('end-do-stmt', text='END DO')
1876
1877 doconstruct = createElem('do-construct', tail='\n')
1878 doconstruct.extend([dostmt, enddostmt])
1879 return doconstruct
1880
1881 outer = None
1882 inner = None
1883 for i, (var, (lo, up)) in enumerate(list(loopVariables.items())[::-1]):
1884 doconstruct = makeDo(var, lo, up)
1885 # Indentation for the statement after DO
1886 doconstruct[0].tail += (indent + 2 * i + 2) * ' '
1887 if outer is None:
1888 outer = doconstruct
1889 inner = doconstruct
1890 else:
1891 inner.insert(1, doconstruct)
1892 inner = doconstruct
1893 # Indentation for the ENDDO statement
1894 doconstruct.tail += (indent + 2 * i - 2) * ' '
1895 return inner, outer, 2 if concurrent else 2 * len(loopVariables)
1896
1897 @staticmethod
1898 @debugDecor
1899 def insertInList(pos, item, parent):
1900 """
1901 :param pos: insertion position
1902 :param item: item to add to the list
1903 :param parent: the parent of item (the list)
1904 """
1905 # insertion
1906 if pos < 0:
1907 pos = len(parent) + 1 + pos
1908 parent.insert(pos, item)
1909 if len(parent) > 1:
1910 i = list(parent).index(item) # effective position
1911 if i == len(parent) - 1:
1912 # The item is the last one
1913 parent[i - 1].tail = ', '
1914 else:
1915 parent[i].tail = ', '
1916
1917 @debugDecor
1918 def removeFromList(self, item, itemPar):
1919 """
1920 :param item: item to remove from list
1921 :param itemPar: the parent of item (the list)
1922 """
1923
1924 nodesToSuppress = [item]
1925
1926 # Suppression of the comma
1927 i = list(itemPar).index(item)
1928 if item.tail is not None and ',' in item.tail:
1929 # There's a comma just after the node
1930 tail = item.tail
1931 item.tail = tail.replace(',', '')
1932 elif i != 0 and ',' in itemPar[i - 1].tail:
1933 # There's a comma just before the node
1934 tail = itemPar[i - 1].tail
1935 itemPar[i - 1].tail = tail.replace(',', '')
1936 else:
1937 found = False
1938 # We look for a comma in the first node after the current node that
1939 # is not after another item of the list
1940 j = i + 1
1941 while j < len(itemPar) and not found:
1942 if nonCode(itemPar[j]):
1943 # This is a candidate
1944 if itemPar[j].tail is not None and ',' in itemPar[j].tail:
1945 # Comma found and suppressed
1946 found = True
1947 tail = itemPar[j].tail
1948 itemPar[j].tail = tail.replace(',', '')
1949 else:
1950 j += 1
1951 else:
1952 # This is another item
1953 break
1954
1955 # We look for a comma in the last node before the current node that
1956 # is not a comment or a contiuation character
1957 j = i - 1
1958 while j >= 0 and not found:
1959 if itemPar[j].tail is not None and ',' in itemPar[j].tail:
1960 # Comma found and suppressed
1961 found = True
1962 tail = itemPar[j].tail
1963 itemPar[j].tail = tail.replace(',', '')
1964 else:
1965 if nonCode(itemPar[j]):
1966 # We can search before
1967 j -= 1
1968 else:
1969 # This is another item
1970 break
1971
1972 if not found and \
1973 len([e for e in itemPar if not nonCode(e)]) != 1:
1974 raise RuntimeError("Something went wrong here....")
1975
1976 # Suppression of continuation characters
1977 if i + 1 < len(itemPar) and tag(itemPar[i + 1]) == 'cnt':
1978 # Node is followed by a continuation character
1979 reason = 'lastOnLine'
1980 # If the node is followed by a continuation character and is just after another
1981 # continuation character, we must supress the continuation character which is after.
1982 # USE MODD, ONLY: X, &
1983 # Y, & !Variable to suppress, with its '&' character
1984 # Z
1985 # In addition, if the character found before is at the begining of the line,
1986 # it must also be removed. To know if it is at the begining of the line,
1987 # we can check if another continuation character is before.
1988 # USE MODD, ONLY: X, &
1989 # & Y, & !Variable to suppress, with both '&' characters
1990 # & Z
1991 elif len([itemPar[j] for j in range(i + 1, len(itemPar)) if not nonCode(itemPar[j])]) == 0:
1992 # Node is the last of the list
1993 reason = 'last'
1994 # If the removed node is the last of the list and a continuation character
1995 # is just before. We must suppress it.
1996 # USE MODD, ONLY: X, &
1997 # Y !Variable to suppress, with the preceding '&'
1998 # In addition, if the character found before is at the begining of the line,
1999 # the preceding one must also be removed.
2000 # USE MODD, ONLY: X, &
2001 # & Y !Variable to suppress, with 2 '&'
2002 else:
2003 # We must not suppress '&' characters
2004 reason = None
2005 if reason is not None:
2006 def _getPrecedingCnt(itemPar, i):
2007 """
2008 Return the index of the preceding node which is a continuation character
2009 :param itemPar: the list containig the node to suppress
2010 :param i: the index of the current node, i-1 is the starting index for the search
2011 :return: a tuple with three elements:
2012 - the node containing the preceding '&' character
2013 - the parent of the node containing the preceding '&' character
2014 - index of the preceding '&' in the parent (previsous element
2015 of the tuple)
2016 Note:
2017 - In the general case the preceding '&' belongs to the same list:
2018 USE MODD, ONLY: X, &
2019 Y
2020 - But it exists a special case, where the preceding '&' don't belong to
2021 the same list (in the following example, both '&' are attached to the parent):
2022 USE MODD, ONLY: &
2023 & X
2024 """
2025 j = i - 1
2026 while j >= 0 and tag(itemPar[j]) == 'C':
2027 j -= 1
2028 if j >= 0 and tag(itemPar[j]) == 'cnt':
2029 return itemPar[j], itemPar, j
2030 if j == -1:
2031 # In the following special case, the '&' don't belong to the list but are
2032 # siblings of the list.
2033 # USE MODD, ONLY: &
2034 # & X
2035 siblings = self.getSiblings(itemPar, before=True, after=False)
2036 j2 = len(siblings) - 1
2037 while j2 >= 0 and tag(siblings[j2]) == 'C':
2038 j2 -= 1
2039 if j2 >= 0 and tag(siblings[j2]) == 'cnt':
2040 return siblings[j2], siblings, j2
2041 return None, None, None
2042 # We test if the preceding node (excluding comments) is a continuation character
2043 precCnt, newl, j = _getPrecedingCnt(itemPar, i)
2044 if precCnt is not None:
2045 # Preceding node is a continuation character
2046 nodesToSuppress.append(precCnt if reason == 'last' else itemPar[i + 1])
2047 if j is not None:
2048 precCnt2, _, _ = _getPrecedingCnt(newl, j)
2049 if precCnt2 is not None:
2050 # There is another continuation character before
2051 nodesToSuppress.append(precCnt2 if reason == 'last' else precCnt)
2052
2053 # Suppression of nodes
2054 for node in nodesToSuppress:
2055 # Get the tail of the previous children of the list and append the item's tail
2056 # to be removed
2057 if node in itemPar:
2058 parent = itemPar
2059 else:
2060 # parent must be recomputed because previsous removal may have change it
2061 parent = self.getParent(itemPar)
2062 i = list(parent).index(node)
2063 if i != 0 and node.tail is not None:
2064 if parent[i - 1].tail is None:
2065 parent[i - 1].tail = ''
2066 parent[i - 1].tail = parent[i - 1].tail + node.tail
2067 parent.remove(node)
inlineContainedSubroutines(self, simplify=False, loopVar=None)
removePrints(self, simplify=False)
evalFalseIfStmt(self, nodes, simplify=False)
removeConstructNode(self, node, simplifyVar, simplifyStruct)
inline(self, subContained, callStmt, mainScope, simplify=False, loopVar=None)
isNodeInProcedure(self, node, procList)
Definition statements.py:97
removeArraySyntax(self, concurrent=False, useMnhExpand=True, everywhere=True, loopVar=None, reuseLoop=True, funcList=None, updateMemSet=False, updateCopy=False, addAccIndependentCollapse=True)
setFalseIfStmt(self, flags, simplify=False)
checkEmptyParensInCall(self, mustRaise=False)
insertStatement(self, stmt, first)
createDoConstruct(loopVariables, indent=0, concurrent=False)
insertInList(pos, item, parent)
isArrayIndexSelection(node, getParent, getScope)
checkOpInCall(self, mustRaise=False)
checkEmptyParensInMnhExpand(self, mustRaise=False)
removeStmtNode(self, nodes, simplifyVar, simplifyStruct)
removeCall(self, callName, simplify=False)
checkContinuationInArraySection(self, mustRaise=False)
removeFromList(self, item, itemPar)
_nodesInWhere(whereNode)
Definition statements.py:52
_nodesInCase(caseNode)
Definition statements.py:77