274 loopVar=None, reuseLoop=True, funcList=None,
275 updateMemSet=False, updateCopy=False, addAccIndependentCollapse=True):
277 Transform array syntax assignments into explicit DO loops.
279 Converts Fortran array syntax (e.g., A(:) = B(:)) into equivalent DO loop form.
283 concurrent : bool, optional
284 If True, use 'DO CONCURRENT' loops instead of simple 'DO' loops.
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.
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.
318 Transformation Examples
319 ----------------------
326 DO J1 = LBOUND(A, 1), UBOUND(A, 1)
327 A(J1) = B(J1) + C(J1)
331 DO CONCURRENT (J1=LBOUND(A, 1):UBOUND(A, 1))
332 A(J1) = B(J1) + C(J1)
338 WHERE (MASK(:)) X(:) = Y(:)
341 DO J1 = 1, SIZE(X, 1)
342 IF (MASK(J1)) X(J1) = Y(J1)
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)
391 def decode(directive):
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
398 kind is 'array' or 'where'
406 table = directive.split(
'(')[1].split(
')')[0].split(
',')
407 table = {c.split(
'=')[0]: c.split(
'=')[1].split(
':')
409 table.pop(
'OPENACC',
None)
410 if directive.lstrip(
' ').startswith(
'!$mnh_expand'):
411 kind = directive[13:].lstrip(
' ').split(
'(')[0].strip()
413 kind = directive[17:].lstrip(
' ').split(
'(')[0].strip()
416 def updateStmt(stmt, table, kind, extraindent, parent, scope):
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
425 :param scope: current scope
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:
436 node.tail = re.sub(
r"(\n[ ]*)(\Z|[^\n ]+)",
437 r"\1" + extra *
' ' +
r"\2", node.tail)
439 addExtra(stmt, extraindent)
442 elif tag(stmt) ==
'cpp':
443 i = list(parent).index(stmt)
448 parent[i - 1].tail = parent[i - 1].tail.rstrip(
' ')
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.")
462 for namedE
in stmt.findall(
'.//{*}R-LT/..'):
463 scope.arrayR2parensR(namedE, table)
464 for cnt
in stmt.findall(
'.//{*}cnt'):
465 addExtra(cnt, extraindent)
466 elif tag(stmt) ==
'if-stmt':
468 "An if statement is inside a code section transformed in DO loop in %s",
471 updateStmt(stmt.find(
'./{*}action-stmt')[0], table, kind, 0, stmt, scope)
472 elif tag(stmt) ==
'if-construct':
474 "An if construct is inside a code section transformed in DO loop in %s",
477 for ifBlock
in stmt.findall(
'./{*}if-block'):
478 for child
in ifBlock:
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)
484 addExtra(child, extraindent)
485 for cnt
in child.findall(
'.//{*}cnt'):
487 addExtra(cnt, extraindent)
488 elif tag(stmt) ==
'where-stmt':
490 stmt.tag = f
'{{{NAMESPACE}}}if-stmt'
491 stmt.text =
'IF (' + stmt.text.split(
'(', 1)[1]
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'
497 for namedE
in mask.findall(
'.//{*}R-LT/..'):
498 scope.arrayR2parensR(namedE, table)
499 for cnt
in stmt.findall(
'.//{*}cnt'):
500 addExtra(cnt, extraindent)
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.')
507 stmt.tag = f
'{{{NAMESPACE}}}if-construct'
509 for whereBlock
in stmt.findall(
'./{*}where-block'):
510 whereBlock.tag = f
'{{{NAMESPACE}}}if-block'
511 for child
in whereBlock:
512 if tag(child) ==
'end-where-stmt':
514 child.tag = f
'{{{NAMESPACE}}}end-if-stmt'
515 child.text =
'END IF'
517 addExtra(child, extraindent)
518 elif tag(child)
in (
'where-construct-stmt',
'else-where-stmt'):
520 addExtra(child, extraindent)
521 if tag(child) ==
'where-construct-stmt':
523 child.tag = f
'{{{NAMESPACE}}}if-then-stmt'
524 child.text =
'IF (' + child.text.split(
'(', 1)[1]
529 if '(' in child.text:
531 child.tag = f
'{{{NAMESPACE}}}else-if-stmt'
532 child.text =
'ELSE IF (' + child.text.split(
'(', 1)[1]
535 child.tag = f
'{{{NAMESPACE}}}else-stmt'
537 for mask
in child.findall(
'./{*}mask-E'):
539 mask.tag = f
'{{{NAMESPACE}}}condition-E'
541 for namedE
in mask.findall(
'.//{*}R-LT/..'):
543 scope.arrayR2parensR(namedE, table)
544 for cnt
in child.findall(
'.//{*}cnt'):
546 addExtra(cnt, extraindent)
548 updateStmt(child, table, kind, extraindent, whereBlock, scope)
550 raise PYFTError(
'Unexpected tag found in mnh_expand ' +
551 'directives: {t}'.format(t=tag(stmt)))
554 def closeLoop(loopdesc):
555 """Helper function to deal with indentation"""
557 inner, outer, indent, extraindent = loopdesc
558 if inner[-2].tail
is not None:
560 outer.tail = inner[-2].tail[:-extraindent]
561 inner[-2].tail =
'\n' + (indent + extraindent - 2) *
' '
568 def recur(elem, scope):
572 for ie, sElem
in enumerate(list(elem)):
573 if tag(sElem) ==
'C' and sElem.text.lstrip(
' ').startswith(
'!$mnh_expand')
and \
577 raise PYFTError(
'Nested mnh_directives are not allowed')
579 inEverywhere = closeLoop(inEverywhere)
582 table, kind = decode(sElem.text)
584 indent = len(sElem.tail) - len(sElem.tail.rstrip(
' '))
585 toremove.append((elem, sElem))
589 if elem[ie - 1].tail
is None:
590 elem[ie - 1].tail =
''
591 elem[ie - 1].tail += sElem.tail.replace(
'\n',
'', 1).rstrip(
' ')
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))
601 inner, outer, extraindent = scope.createDoConstruct(table, indent=indent,
602 concurrent=concurrent)
603 toinsert.append((elem, outer, ie))
605 elif (tag(sElem) ==
'C' and
606 sElem.text.lstrip(
' ').startswith(
'!$mnh_end_expand')
and useMnhExpand):
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()))
615 toremove.append((elem, sElem))
619 outer.tail += sElem.tail.replace(
'\n',
'', 1)
621 elem[ie - 1].tail = elem[ie - 1].tail[:-2]
625 toremove.append((elem, sElem))
626 inner.insert(-1, sElem)
628 updateStmt(sElem, table, kind, extraindent, inner, scope)
630 elif everywhere
and tag(sElem)
in (
'a-stmt',
'if-stmt',
'where-stmt',
635 if tag(sElem) ==
'a-stmt':
637 arr = sElem.find(
'./{*}E-1/{*}named-E/{*}R-LT/{*}array-R/../..')
641 nodeE2 = sElem.find(
'./{*}E-2')
643 num = len(nodeE2.findall(
'.//{*}array-R'))
650 elif (len(nodeE2) == 1
and tag(nodeE2[0]) ==
'named-E' and num == 1
and
651 nodeE2[0].find(
'.//{*}parens-R')
is None):
657 if (isMemSet
and not updateMemSet)
or (isCopy
and not updateCopy):
659 elif tag(sElem) ==
'if-stmt':
661 arr = sElem.find(
'./{*}action-stmt/{*}a-stmt/{*}E-1/' +
662 '{*}named-E/{*}R-LT/{*}array-R/../..')
665 scope.changeIfStatementsInIfConstructs(singleItem=sElem)
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/../..')
679 elif len(set(alltext(a).count(
':')
680 for a
in sElem.findall(
'.//{*}R-LT/{*}array-R'))) > 1:
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:
697 newtable, varNew = scope.findArrayBounds(arr, loopVar, newVarList)
700 if var
not in newVarList:
701 newVarList.append(var)
708 inEverywhere = closeLoop(inEverywhere)
711 if not (inEverywhere
and table == newtable):
713 inEverywhere = closeLoop(inEverywhere)
715 if ie != 0
and elem[ie - 1].tail
is not None:
718 tail = tailSave.get(elem[ie - 1], elem[ie - 1].tail)
719 indent = len(tail) - len(tail.rstrip(
' '))
725 inner, outer, extraindent = scope.createDoConstruct(
726 table, indent=indent, concurrent=concurrent)
727 toinsert.append((elem, outer, ie))
728 inEverywhere = (inner, outer, indent, extraindent)
729 tailSave[sElem] = sElem.tail
730 toremove.append((elem, sElem))
731 inner.insert(-1, sElem)
733 updateStmt(sElem, table, kind, extraindent, inner, scope)
736 inEverywhere = closeLoop(inEverywhere)
739 inEverywhere = closeLoop(inEverywhere)
743 inEverywhere = closeLoop(inEverywhere)
745 for scope
in self.getScopes():
748 for elem, outer, ie
in toinsert[::-1]:
749 elem.insert(ie, outer)
751 for parent, elem
in toremove:
754 for scopePath
in sorted(set(v[
'scopePath']
for v
in newVarList)):
755 self.getScopeNode(scopePath).addVar([(v[
'n'], f
"INTEGER :: {v['n']}",
None)
757 if v[
'scopePath'] == scopePath])
841 def inline(self, subContained, callStmt, mainScope,
842 simplify=False, loopVar=None):
844 Inline a single contained subroutine at its call site.
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
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).
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.
877 def setPRESENTby(node, var, val):
879 Replace PRESENT(var) by .TRUE. if val is True, by .FALSE. otherwise on node
881 :param node: xml node to work on (a contained subroutine)
882 :param var: string of the name of the optional variable to check
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[:]:
891 namedE.tag = f
'{{{NAMESPACE}}}literal-E'
892 namedE.text =
'.TRUE.' if val
else '.FALSE.'
895 parent = mainScope.getParent(callStmt)
898 if tag(parent) ==
'action-stmt':
899 mainScope.changeIfStatementsInIfConstructs(mainScope.getParent(parent))
900 parent = mainScope.getParent(callStmt)
904 prefix = subContained.findall(
'.//{*}prefix')
905 if len(prefix) > 0
and 'ELEMENTAL' in [p.text.upper()
for p
in prefix]:
907 mainScope.addArrayParenthesesInNode(callStmt)
910 mainScope.addExplicitArrayBounds(node=callStmt)
913 arrayRincallStmt = callStmt.findall(
'.//{*}array-R')
914 if len(arrayRincallStmt) > 0:
916 table, _ = mainScope.findArrayBounds(mainScope.getParent(arrayRincallStmt[0], 2),
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]])
929 inner, outer, _ = mainScope.createDoConstruct(table)
932 inner.insert(-1, callStmt)
934 parent.insert(list(parent).index(callStmt), outer)
935 parent.remove(callStmt)
937 for namedE
in callStmt.findall(
'./{*}arg-spec/{*}arg/{*}named-E'):
939 if namedE.find(
'./{*}R-LT'):
940 mainScope.arrayR2parensR(namedE, table)
943 node = copy.deepcopy(subContained)
948 varList = copy.deepcopy(self.varList)
949 for var
in [var
for var
in varList.restrict(subContained.path,
True)
950 if not var[
'arg']
and not var[
'use']]:
952 if varList.restrict(mainScope.path,
True).findVar(var[
'n']):
955 newName = re.sub(
r'_\d+$',
'', var[
'n'])
957 while (varList.restrict(subContained.path,
True).findVar(newName +
'_' + str(i))
or
958 varList.restrict(mainScope.path,
True).findVar(newName +
'_' + str(i))):
960 newName +=
'_' + str(i)
961 node.renameVar(var[
'n'], newName)
962 subst.append((var[
'n'], newName))
965 var[
'scopePath'] = mainScope.path
966 localVarToAdd.append(var)
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
975 for dim
in var[
'as']]
982 localUseToAdd = node.findall(
'./{*}use-stmt')
983 for sNode
in node.findall(
'./{*}T-decl-stmt') + localUseToAdd + \
984 node.findall(
'./{*}implicit-none-stmt'):
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])
994 node.remove(node[icom])
1002 for argN
in subContained.findall(
'.//{*}subroutine-stmt/{*}dummy-arg-LT/{*}arg-N'):
1003 vartable[alltext(argN).upper()] =
None
1004 for iarg, arg
in enumerate(callStmt.findall(
'.//{*}arg')):
1005 key = arg.find(
'.//{*}arg-N')
1008 dummyName = alltext(key).upper()
1011 dummyName = list(vartable.keys())[iarg]
1013 nodeRLTarray = argnode.findall(
'.//{*}R-LT/{*}array-R')
1014 if len(nodeRLTarray) > 0:
1016 if len(nodeRLTarray) > 1
or \
1017 argnode.find(
'./{*}R-LT/{*}array-R')
is None or \
1018 tag(argnode) !=
'named-E':
1020 raise PYFTError(
'Argument to complicated: ' + str(alltext(argnode)))
1021 dim = nodeRLTarray[0].find(
'./{*}section-subscript-LT')[:]
1027 argname =
"".join(argnode.itertext())
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}
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()
1042 setPRESENTby(node, dummyName,
False)
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]:
1050 par = node.getParent(nodeN, level=2)
1051 allreadySuppressed = []
1052 while par
and not removed
and par
not in allreadySuppressed:
1055 if tagName
in (
'a-stmt',
'print-stmt'):
1058 elif tagName ==
'call-stmt':
1063 raise NotImplementedError(
'call-stmt not (yet?) implemented')
1064 elif tagName
in (
'if-stmt',
'where-stmt'):
1067 elif tagName
in (
'if-then-stmt',
'else-if-stmt',
'where-construct-stmt',
1071 toSuppress = node.getParent(par, 2)
1072 elif tagName
in (
'select-case-stmt',
'case-stmt'):
1075 toSuppress = node.getParent(par, 2)
1076 elif tagName.endswith(
'-block')
or tagName.endswith(
'-stmt')
or \
1077 tagName.endswith(
'-construct'):
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:
1088 if toSuppress
not in allreadySuppressed:
1091 node.removeStmtNode(toSuppress,
False, simplify)
1092 allreadySuppressed.extend(list(toSuppress.iter()))
1094 par = node.getParent(par)
1097 for name, dummy
in vartable.items():
1101 for namedE
in [namedE
for namedE
in node.findall(
'.//{*}named-E/{*}N/{*}n/../..')
1102 if n2name(namedE.find(
'{*}N')).upper() == name]:
1104 nodeN = namedE.find(
'./{*}N')
1105 ns = nodeN.findall(
'./{*}n')
1106 ns[0].text = n2name(nodeN)
1112 descMain = varList.restrict(mainScope.path,
True).findVar(dummy[
'name'])
1113 descSub = varList.restrict(subContained.path,
True).findVar(name)
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
1121 for dim
in var[
'as']]
1126 nodeRLT = namedE.find(
'./{*}R-LT')
1127 if nodeRLT
is not None and tag(nodeRLT[0]) !=
'component-R':
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')
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:
1139 if len(descSub[
'as']) > 0:
1140 ndim = len(descSub[
'as'])
1143 if dummy[
'dim']
is not None:
1146 ndim = len([d
for d
in dummy[
'dim']
if ':' in alltext(d)])
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[:]:
1156 namedE.extend(updatedNamedE[:])
1157 slices = namedE.find(
'./{*}R-LT')[0].findall(
1158 './{*}section-subscript-LT/{*}section-subscript')
1164 namedE.find(
'./{*}N')[0].text = dummy[
'name']
1172 for isl, sl
in enumerate(slices):
1174 if len(descSub[
'as']) == 0
or descSub[
'as'][isl][1]
is None:
1177 if dummy[
'dim']
is not None:
1179 tagName =
'./{*}lower-bound' if i == 0
else './{*}upper-bound'
1180 descSub[i] = dummy[
'dim'][isl].find(tagName)
1183 if descSub[i]
is not None:
1185 descSub[i] = alltext(descSub[i])
1188 if descMain
is not None and descMain[
'as'][isl][1]
is not None:
1190 descSub[i] = descMain[
'as'][isl][i]
1191 if i == 0
and descSub[i]
is None:
1194 descSub[i] =
"L" if i == 0
else "U"
1195 descSub[i] +=
"BOUND({name}, {isl})".format(
1196 name=dummy[
'name'], isl=isl + 1)
1198 descSub[0] = descSub[
'as'][isl][0]
1199 if descSub[0]
is None:
1201 descSub[1] = descSub[
'as'][isl][1]
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'))
1217 if descMain
is not None and descMain[
'as']
is not None:
1218 offset = descMain[
'as'][isl][0]
1221 elif offset.strip().startswith(
'-'):
1222 offset =
'(' + offset +
')'
1224 offset =
"LBOUND({name}, {isl})".format(
1225 name=dummy[
'name'], isl=isl + 1)
1226 if offset.upper() == descSub[0].upper():
1229 if descSub[0].strip().startswith(
'-'):
1230 offset +=
'- (' + descSub[0] +
')'
1232 offset +=
'-' + descSub[0]
1236 if tag(sl) ==
'element' or \
1237 (tag(sl) ==
'section-subscript' and ':' not in alltext(sl)):
1241 low = sl.find(
'./{*}lower-bound')
1243 low = createElem(
'lower-bound', tail=sl.text)
1244 low.append(createExprPart(descSub[0]))
1247 up = sl.find(
'./{*}upper-bound')
1249 up = createElem(
'upper-bound')
1250 up.append(createExprPart(descSub[1]))
1253 for bound
in bounds:
1255 if bound[-1].tail
is None:
1257 bound[-1].tail +=
'+' + offset
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):])
1271 updatedNamedE = createExprPart(alltext(namedE))
1272 namedE.tag = updatedNamedE.tag
1273 namedE.text = updatedNamedE.text
1274 for nnn
in namedE[:]:
1276 namedE.extend(updatedNamedE[:])
1278 node.remove(node.find(
'./{*}subroutine-stmt'))
1279 node.remove(node.find(
'./{*}end-subroutine-stmt'))
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])
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
1296 node[-1].tail = node[-1].tail + callStmt.tail
1297 for node
in node[::-1]:
1299 parent.insert(index, node)
1594 Remove statement nodes with optional code simplification.
1598 nodes : xml element or list of xml elements
1599 Node(s) to remove from the code tree.
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.
1609 >>> pft = PYFT('input.F90')
1610 >>> nodes = pft.findall('.//{*}call-stmt')
1611 >>> pft.removeStmtNode(nodes, simplifyVar=True, simplifyStruct=True)
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
1627 nodesToSuppress = []
1628 if not isinstance(nodes, list):
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])
1636 nodesToSuppress.append(node)
1637 elif tag(node) ==
'}action-stmt':
1639 nodesToSuppress.append(node[0])
1641 nodesToSuppress.append(node)
1643 nodesToSuppress.append(node)
1648 for node
in nodesToSuppress:
1649 scopePath = self.getScopePath(node)
1650 if tag(node) ==
'do-construct':
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'):
1656 varToCheck.extend([(scopePath, n2name(arg))
1657 for arg
in node.findall(
'.//{*}condition-E//{*}N')])
1658 elif tag(node)
in (
'where-construct',
'where-stmt'):
1660 varToCheck.extend([(scopePath, n2name(arg))
1661 for arg
in node.findall(
'.//{*}mask-E//{*}N')])
1662 elif tag(node) ==
'call-stmt':
1664 varToCheck.extend([(scopePath, n2name(arg))
1665 for arg
in node.findall(
'./{*}arg-spec//{*}N')])
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':
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')])
1680 for node
in nodesToSuppress:
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:
1689 previous = previous[-1]
1690 if previous.tail
is None:
1692 previous.tail = (previous.tail.replace(
'\n',
'') +
1693 (node.tail
if node.tail
is not None else ''))
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)
1703 newNodesToSuppress = []
1704 for node
in nodesToSuppress:
1705 parent = parents[id(node)]
1708 if tag(parent) ==
'action-stmt':
1709 newNodesToSuppress.append(self.
getParent(parent))
1711 elif simplifyStruct:
1712 if tag(parent) ==
'do-construct' and len(
_nodesInDo(parent)) == 0:
1713 newNodesToSuppress.append(parent)
1714 elif tag(parent) ==
'if-block':
1717 newNodesToSuppress.append(parPar)
1718 elif tag(parent) ==
'where-block':
1721 newNodesToSuppress.append(parPar)
1722 elif tag(parent) ==
'selectcase-block':
1725 newNodesToSuppress.append(parPar)
1727 constructNodes, otherNodes = [], []
1728 for nnn
in newNodesToSuppress:
1729 if tag(nnn).endswith(
'-construct'):
1730 if nnn
not in constructNodes:
1731 constructNodes.append(nnn)
1733 if nnn
not in otherNodes:
1734 otherNodes.append(nnn)
1736 if len(otherNodes) > 0:
1739 for nnn
in constructNodes:
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))
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')
1839 triplet = createElem(
'forall-triplet-spec')
1840 triplet.extend([nodeV, lower, upper])
1842 triplets.append(triplet)
1844 tripletLT = createElem(
'forall-triplet-spec-LT', tail=
')')
1845 for triplet
in triplets[:-1]:
1847 tripletLT.extend(triplets)
1849 dostmt = createElem(
'do-stmt', text=
'DO CONCURRENT (', tail=
'\n')
1850 dostmt.append(tripletLT)
1851 enddostmt = createElem(
'end-do-stmt', text=
'END DO')
1853 doconstruct = createElem(
'do-construct', tail=
'\n')
1854 doconstruct.extend([dostmt, enddostmt])
1855 inner = outer = doconstruct
1856 doconstruct[0].tail += (indent + 2) *
' '
1867 def makeDo(var, lo, up):
1868 doV = createElem(
'do-V', tail=
'=')
1869 doV.append(createExprPart(var))
1870 lower, upper = createArrayBounds(lo, up,
'DO')
1872 dostmt = createElem(
'do-stmt', text=
'DO ', tail=
'\n')
1873 dostmt.extend([doV, lower, upper])
1875 enddostmt = createElem(
'end-do-stmt', text=
'END DO')
1877 doconstruct = createElem(
'do-construct', tail=
'\n')
1878 doconstruct.extend([dostmt, enddostmt])
1883 for i, (var, (lo, up))
in enumerate(list(loopVariables.items())[::-1]):
1884 doconstruct = makeDo(var, lo, up)
1886 doconstruct[0].tail += (indent + 2 * i + 2) *
' '
1891 inner.insert(1, doconstruct)
1894 doconstruct.tail += (indent + 2 * i - 2) *
' '
1895 return inner, outer, 2
if concurrent
else 2 * len(loopVariables)
1920 :param item: item to remove from list
1921 :param itemPar: the parent of item (the list)
1924 nodesToSuppress = [item]
1927 i = list(itemPar).index(item)
1928 if item.tail
is not None and ',' in item.tail:
1931 item.tail = tail.replace(
',',
'')
1932 elif i != 0
and ',' in itemPar[i - 1].tail:
1934 tail = itemPar[i - 1].tail
1935 itemPar[i - 1].tail = tail.replace(
',',
'')
1941 while j < len(itemPar)
and not found:
1942 if nonCode(itemPar[j]):
1944 if itemPar[j].tail
is not None and ',' in itemPar[j].tail:
1947 tail = itemPar[j].tail
1948 itemPar[j].tail = tail.replace(
',',
'')
1958 while j >= 0
and not found:
1959 if itemPar[j].tail
is not None and ',' in itemPar[j].tail:
1962 tail = itemPar[j].tail
1963 itemPar[j].tail = tail.replace(
',',
'')
1965 if nonCode(itemPar[j]):
1973 len([e
for e
in itemPar
if not nonCode(e)]) != 1:
1974 raise RuntimeError(
"Something went wrong here....")
1977 if i + 1 < len(itemPar)
and tag(itemPar[i + 1]) ==
'cnt':
1979 reason =
'lastOnLine'
1991 elif len([itemPar[j]
for j
in range(i + 1, len(itemPar))
if not nonCode(itemPar[j])]) == 0:
2005 if reason
is not None:
2006 def _getPrecedingCnt(itemPar, i):
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
2017 - In the general case the preceding '&' belongs to the same list:
2018 USE MODD, ONLY: X, &
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):
2026 while j >= 0
and tag(itemPar[j]) ==
'C':
2028 if j >= 0
and tag(itemPar[j]) ==
'cnt':
2029 return itemPar[j], itemPar, j
2035 siblings = self.getSiblings(itemPar, before=
True, after=
False)
2036 j2 = len(siblings) - 1
2037 while j2 >= 0
and tag(siblings[j2]) ==
'C':
2039 if j2 >= 0
and tag(siblings[j2]) ==
'cnt':
2040 return siblings[j2], siblings, j2
2041 return None,
None,
None
2043 precCnt, newl, j = _getPrecedingCnt(itemPar, i)
2044 if precCnt
is not None:
2046 nodesToSuppress.append(precCnt
if reason ==
'last' else itemPar[i + 1])
2048 precCnt2, _, _ = _getPrecedingCnt(newl, j)
2049 if precCnt2
is not None:
2051 nodesToSuppress.append(precCnt2
if reason ==
'last' else precCnt)
2054 for node
in nodesToSuppress:
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