77 def indent(self, nodeToUpdate=None, indentProgramunit=0, indentBranch=2,
84 nodeToUpdate : Element, optional
85 Specific node to indent. If None, indents entire scope.
86 indentProgramunit : int, optional
87 Number of spaces for program unit contents. Default is 0.
88 indentBranch : int, optional
89 Number of spaces for nested constructs (do, if, etc.). Default is 2.
90 exclDirectives : list, optional
91 Lines to exclude from indentation:
92 - None: Exclude '!$OMP' lines (default).
93 - []: Include all lines.
94 - ['!$acc', '!$mnh']: Custom directive list.
99 Returns self for chaining.
103 >>> pft = PYFT('input.F90')
104 >>> pft.indent() # Default indentation
105 >>> pft.indent(indentProgramunit=0, indentBranch=4) # Custom
108 if nodeToUpdate
is None:
111 if exclDirectives
is None:
112 exclDirectives = [
'!$OMP']
114 def setLevel(elem, level, nextElem):
116 :param elem: element whose tail must be modifies
117 :param level: level of indentation
118 :param nextElem: next element
120 if elem.tail
is not None:
121 elem.tail = elem.tail.replace(
'\t',
' ')
122 excl = (nextElem
is not None and
123 (tag(nextElem) ==
'cpp' or
124 tag(nextElem) ==
'C' and
125 any(nextElem.text.startswith(d)
for d
in exclDirectives)))
127 elem.tail = re.sub(
'\n[ ]*',
'\n' +
' ' * level, elem.tail)
129 def indentRecur(elem, level, inConstruct):
131 :param elem: dom element
132 :param level: current level for elem
133 :param inConstruct: True if we are inside a construct
135 blocs = [
'file',
'program-unit',
'if-block',
'where-block',
'selectcase-block']
136 progstmt = [
'subroutine-stmt',
'program-stmt',
'module-stmt',
'function-stmt',
137 'submodule-stmt',
'procedure-stmt',
'interface-stmt']
138 endprogstmt = [
'end-' + s
for s
in progstmt]
139 interbranchstmt = [
'else-stmt',
'else-if-stmt',
'else-where-stmt']
140 branchstmt = [
'if-then-stmt',
'where-construct-stmt'] + interbranchstmt
141 endbranchstmt = [
'end-if-stmt',
'end-where-stmt']
145 firstnumselect =
True
146 for ie, sElem
in enumerate(elem):
149 if tag(sElem)
in progstmt:
150 currlevel += indentProgramunit
151 elif tag(sElem)
in branchstmt + [inConstruct +
'-stmt']:
152 currlevel += indentBranch
155 setLevel(sElem, currlevel, elem[ie + 1]
if ie + 1 < len(elem)
else None)
157 if tag(elem) ==
'selectcase-construct':
175 firstnumselect =
False
179 setLevel(laste[-1], level + indentBranch, sElem)
181 indentRecur(sElem, level + indentBranch * 2,
"")
182 if tag(sElem[-1]) ==
'end-select-case-stmt':
183 setLevel(sElem[-2], level, sElem[-1])
185 elif tag(sElem)
in blocs
or tag(sElem).endswith(
'-construct'):
187 if tag(sElem[0])
in interbranchstmt:
196 setLevel(laste[-1], level, sElem)
197 construct = tag(sElem)[:-10]
if tag(sElem).endswith(
'-construct')
else ""
198 indentRecur(sElem, currlevel, construct)
202 if tag(sElem)
in endprogstmt + endbranchstmt + [
'end-' + inConstruct +
'-stmt']:
203 setLevel(laste, level, sElem)
206 indentRecur(nodeToUpdate, 0,
"")
283 removeALL=False, addBegin=True, removeBegin=False):
285 :param nodeToUpdate: if None, the entire xml is updated
286 :param align: True to align begin of continued lines
287 :param removeALL: True to suppress all the continuation line characters ('&')
288 :param addBegin: True to add missing continuation line characters ('&')
289 at the begining of lines
290 :param removeBegin: True to suppress continuation line characters ('&')
291 at the begining of lines
293 When suppressed, the '&' are replaced by a space character
294 Comments after a '&' are lost
297 assert not (align
and removeALL),
"We cannot remove and align at the same time"
298 assert not (addBegin
and (removeALL
or removeBegin)), \
299 "We cannot remove and add, at the same time, continuation characters"
301 if nodeToUpdate
is None:
306 def recurReverse(elem, tail):
307 for ie
in range(len(elem))[::-1]:
309 parents[sElem] = elem
310 if tag(sElem) ==
'cnt':
314 while j < len(elem)
and tag(elem[j])
in (
'C',
'cpp'):
315 commentsAfter.append(elem[j])
317 nextNode = elem[j]
if j < len(elem)
else None
320 isend = ((sElem.tail
is not None and '\n' in sElem.tail)
or
321 len(commentsAfter) > 0)
324 if isend
and addBegin:
325 if sElem.tail
is not None and \
326 sElem.tail.replace(
'\n',
'').replace(
'\t',
'').lstrip(
' ') !=
'':
329 new = createElem(
'cnt', text=
'&')
332 while sElem.tail[i]
in (
' ',
'\n',
'\t'):
334 new.tail =
' ' + sElem.tail[i:]
335 sElem.tail = sElem.tail[:i]
336 elem.insert(ie + 1, new)
337 elif tag(nextNode) !=
'cnt':
339 new = createElem(
'cnt', text=
'&')
340 if len(commentsAfter) > 0:
344 while i < len(commentsAfter[-1].tail)
and \
345 commentsAfter[-1].tail[i]
in (
' ',
'\n',
'\t'):
347 new.tail =
' ' + commentsAfter[-1].tail[i:]
348 commentsAfter[-1].tail = commentsAfter[-1].tail[:i]
351 elem.insert(ie + 1 + len(commentsAfter), new)
354 if removeALL
or (removeBegin
and not isend):
356 for com
in commentsAfter[::-1]:
357 if tag(com) !=
'cpp':
364 if sElem.tail
is not None:
365 txt = sElem.tail.strip() +
' '
369 if elem[ie - 1].tail
is None:
370 elem[ie - 1].tail = txt
372 elem[ie - 1].tail += txt
376 recurReverse(sElem, tail)
378 def recurDirect(elem, ct, inCnt):
380 :param ct: current text
381 :param inCnt: -1 if we are not in a statement spanning several lines
382 elswhere contains the number of spaces to add
384 ignoreComment =
False
386 for ie, sElem
in enumerate(list(elem)):
388 isendcnt = tag(sElem) ==
'cnt' and \
389 ((sElem.tail
is not None and '\n' in sElem.tail)
or
390 (ie + 1 < len(elem)
and tag(elem[ie + 1]) ==
'C'))
391 ignoreComment = (ignoreComment
or
393 (ie + 1 < len(elem)
and tag(elem[ie + 1]) ==
'C')))
402 if isendcnt
or ignoreComment
or (inCnt != -1
and tag(sElem) ==
'cpp'):
405 if isendcnt
and inCnt == -1:
408 while not tag(topstmt).endswith(
'-stmt'):
409 topstmt = parents[topstmt]
412 if tag(topstmt) ==
'a-stmt':
413 patList = (
'=>',
'=',
r'\(')
414 elif tag(topstmt) ==
'call-stmt':
415 patList = (
r'\(',
r'call[ ]+\w',
'call ',
'call')
416 elif tag(topstmt) ==
'if-stmt':
417 patList = (
r'\(',
r'\)',
'if ',
'if')
418 elif tag(topstmt) ==
'where-stmt':
419 patList = (
r'\(',
r'\)',
'where ',
'where')
420 elif tag(topstmt) ==
'forall-stmt':
421 patList = (
r'\(',
r'\)',
'forall ',
'forall')
422 elif tag(topstmt) ==
'namelist-stmt':
423 patList = (
'/.*/',
'/',
'namelist')
424 elif tag(topstmt) ==
'subroutine-stmt':
425 patList = (
r'\(',
r'subroutine[ ]+\w',
'subroutine ',
'subroutine')
426 elif tag(topstmt) ==
'use-stmt':
427 patList = (
':',
r'use[ ]+\w',
'use ',
'use')
428 elif tag(topstmt) ==
'T-decl-stmt':
429 patList = (
'::',
r'\w,',
r'\w ',
r'\w')
430 elif tag(topstmt) ==
'print-stmt':
431 patList = (
'print', )
432 elif tag(topstmt) ==
'write-stmt':
433 patList = (
r'\)',
r'write[ ]*\(',
'write[ ]*',
'write')
434 elif tag(topstmt) ==
'procedure-stmt':
435 patList = (
'module[ ]+procedure[ ]*',
'module[ ]*',
'module')
437 patList = (
'::',
':',
r'\(',
'=>',
'=',
'[',
':',
'/')
443 mat = re.search(pat, ct, flags=re.IGNORECASE)
445 if ie + 1 < len(elem)
and tag(elem[ie + 1]) !=
'cnt':
451 inCnt = mat.end() - 1
456 if not (ie + 1 < len(elem)
and tag(elem[ie + 1]) ==
'cpp'):
457 if sElem.tail
is not None:
458 sElem.tail = re.sub(
'\n[ ]*',
'\n' +
' ' * inCnt, sElem.tail)
460 sElem.tail =
'\n' +
' ' * inCnt
462 if tag(sElem)
not in (
'C',
'cnt'):
463 ct += (sElem.text
if sElem.text
is not None else '')
464 ignoreComment =
False
468 ct, inCnt = recurDirect(sElem, ct, inCnt)
471 ct += (sElem.tail
if sElem.tail
is not None else '')
473 ct = ct.split(
'\n')[-1]
474 if tag(sElem)
not in (
'cnt',
'C',
'cpp'):
479 recurReverse(nodeToUpdate, 0)
480 recurDirect(nodeToUpdate,
"", -1)
487 beforeComma=0, afterComma=1,
488 beforeParenthesis=0, afterParenthesis=0,
489 beforeAffectation=1, afterAffectation=1, inAffectation=True,
490 beforeRangeDelim=0, afterRangeDelim=0,
491 beforeUseDelim=0, afterUseDelim=1,
492 beforeDeclDelim=1, afterDeclDelim=1,
493 inDeclDelim=True, afterTypeDecl=1,
494 beforeEqDo=0, afterEqDo=0,
495 beforeEqCall=0, afterEqCall=0,
496 beforeEqInit=0, afterEqInit=0,
497 beforeEndcnt=1, afterBegincnt=1,
498 afterIfwherecase=1, beforeThen=1, beforeIfaction=1,
500 endOfLine=True, afterName=0, inName=True,
501 beforeCmdsep=0, afterCmdsep=1,
502 adjacentKeywords=__NO_VALUE__, afterKeywords=__NO_VALUE__):
504 :param beforeOp, afterOp: number of spaces before and after operators
505 :param inOperator: True to suppress spaces in operators
506 :param beforeComma, afterComma: number of spaces before and after commas
507 :param beforeParenthesis, afterParenthesis: number of spaces before and after parenthesis
508 :param beforeAffectation, afterAffectation: number of spaces before and after
509 affectations or associations
510 :param inAffectation: True to suppress spaces in affectations and in association ('= >')
511 :param beforeRangeDelim, afterRangeDelim: number of spaces before and after range delimiters
512 :param beforeUseDelim, afterUseDelim: number of spaces before and after use delimiters (':')
513 :param beforeDeclDelim, afterDeclDelim: number of spaces before and after declaration and
514 enumerator delimiter ('::')
515 :param inDeclDelim: True to suppress spaces in declaration and enumerator delimiter (': :')
516 :param afterTypeDecl: number of spaces after the type in a declaration w/o '::'
517 (e.g. 'INTEGER I'); also for enumerators (minimum 1)
518 :param beforeEqDo, afterEqDo: number of spaces before and after '=' sign in DO and
520 :param beforeEqCall, afterEqCall: number of spaces before and after '=' sign
522 :param beforeEqInit, afterEqInit: number of spaces before and after '=' sign for init values
523 :param beforeEndcnt, afterBegincnt: number of spaces before a continuation chararcter at the
524 end of the line and after a continuation character
525 at the begining of a line
526 :param afterIfwherecase: number of spaces after the IF, ELSEIF, WHERE, ELSEWHERE,
527 SELECTCASE, CASE and FORALL keywords
528 :param beforeThen: number of spaces before the THEN keyword
529 :param beforeIfaction: number of spaces
530 between IF condition and action in one-line IF statement and
531 between FORALL specification and affectation in one-line FORALL
533 between WHERE mask and action in one-line WHERE statement
534 :param afterProgunit: between the program unit type (e.g. SUBROUTINE) and its name
535 :param endOfLine: True to suppress spaces at the end of the line
536 :param afterName: number of spaces after an indentifier, type or attribute name
537 :param inName: True to suppress spaces in identifier names
538 :param beforeCmdsep, afterCmdsep: number of spaces before and after command separator (';')
539 :param adjacentKeywords: describes the number of spaces to introduce between adjancent
540 keywords when this is legal (the list comes from the table
541 "6.2 Adjacent keywords where separating blanks are optional" of the
542 F2008 norm and has been complemented by "end select",
543 "implicit none" and "module procedure"; for the last two,
544 a minimum of 1 is required).
545 The allowed dictionnary keys are:
577 For example, use {'end_do':1} to write 'END DO' or
578 {'end_do':0} to write 'ENDDO' or
579 {'end_do':None} to not update the writting
580 or use adjacentKeywords=None to disable everything
581 :param afterKeywords: describes the number of spaces to introduce after keywords.
582 Some keywords need a more sophisticated treatment and are controled
583 by specific keys (e.g. CASE).
584 The keys are the keyword in lowercase, some names can be tricky
585 to guess (e.g. the key for ENDFILE is 'end-file'). By default
586 only a few are defined.
587 Use afterKeywords=None to disable everything.
589 To not update spaces, put None instead of an integer and False in booleans.
590 For example, to not change number of spaces after a comma, use afterComma=None
592 Updates are done in the following order:
596 'block_data': (1,
'.//{*}block-data-stmt'),
597 'double_precision': (1,
'.//{*}intrinsic-T-spec/{*}T-N'),
598 'else_if': (1,
'.//{*}else-if-stmt'),
599 'else_where': (0,
'.//{*}else-where-stmt'),
600 'end_associate': (1,
'.//{*}end-associate-stmt'),
601 'end_block': (1,
'.//{*}end-block-stmt'),
602 'end_block_data': (1,
'.//{*}end-block-data-stmt'),
603 'end_critical': (1,
'.//{*}end-critical-stmt'),
604 'end_do': (1,
'.//{*}end-do-stmt'),
605 'end_enum': (1,
'.//{*}end-enum-stmt'),
606 'end_file': (1,
'.//{*}end-file-stmt'),
607 'end_forall': (1,
'.//{*}end-forall-stmt'),
608 'end_function': (1,
'.//{*}end-function-stmt'),
609 'end_if': (1,
'.//{*}end-if-stmt'),
610 'end_interface': (1,
'.//{*}end-interface-stmt'),
611 'end_module': (1,
'.//{*}end-module-stmt'),
612 'end_procedure': (1,
'.//{*}end-procedure-stmt'),
613 'end_program': (1,
'.//{*}end-program-stmt'),
614 'end_selec': (1,
'.//{*}end-select-case-stmt'),
615 'end_select': (1,
'.//{*}end-select-T-stmt'),
616 'end_submodule': (1,
'.//{*}end-submodule-stmt'),
617 'end_subroutine': (1,
'.//{*}end-subroutine-stmt'),
618 'end_team': (1,
'.//{*}end-change-team-stmt'),
619 'end_type': (1,
'.//{*}end-T-stmt'),
620 'end_where': (1,
'.//{*}end-where-stmt'),
621 'go_to': (0,
'.//{*}goto-stmt'),
622 'in_out': (0,
'.//{*}intent-spec'),
623 'select_case': (1,
'.//{*}select-case-stmt'),
624 'select_type': (1,
'.//{*}select-T-stmt'),
625 'implicit_none': (1,
'.//{*}implicit-none-stmt'),
626 'module_procedure': (1,
'.//{*}procedure-stmt'),
638 assert adjacentKeywords
is None or adjacentKeywords == self.
__NO_VALUE__ or \
640 for k
in adjacentKeywords),
"Unknown key in **adjacentKeywords"
643 if adjacentKeywords
is None:
646 return adjaKeyDesc[key][0]
647 return adjacentKeywords.get(key, adjaKeyDesc[key][0])
649 def getvalAfter(key):
652 num = afterKeywords.get(key, afterKey.get(key,
None))
654 num = afterKey.get(key,
None)
657 assert afterProgunit
is None or afterProgunit >= 1
658 assert afterTypeDecl
is None or afterTypeDecl >= 1
659 for k
in (
'implicit_none',
'module_procedure'):
661 assert num
is None or num >= 1, \
662 "adjacentKeywords['" + k +
"'] must be at least 1 (is " + str(num) +
")"
663 for k
in (
'use',
'call',
'end-file',
'do'):
664 num = getvalAfter(k +
'-stmt')
665 assert num
is None or num >= 1, \
666 "afterKeywords['" + k +
"'] must be at least 1 (is " + str(num) +
")"
668 for elem
in self.iter():
669 isNotC = tag(elem) !=
'C'
671 if elem.tail
is None:
673 elem.tail = elem.tail.replace(
'\t',
' ')
676 if beforeParenthesis
is not None:
677 elem.tail = re.sub(
r"[ ]*\(",
" " * beforeParenthesis +
r"(", elem.tail)
678 elem.tail = re.sub(
r"[ ]*\)",
" " * beforeParenthesis +
r")", elem.tail)
679 if elem.text
is not None and isNotC:
680 elem.text = re.sub(
r"[ ]*\(",
" " * beforeParenthesis +
r"(", elem.text)
681 elem.text = re.sub(
r"[ ]*\)",
" " * beforeParenthesis +
r")", elem.text)
682 if afterParenthesis
is not None:
683 elem.tail = re.sub(
r"\([ ]*",
"(" +
" " * afterParenthesis, elem.tail)
684 elem.tail = re.sub(
r"\)[ ]*",
")" +
" " * afterParenthesis, elem.tail)
685 if elem.text
is not None and isNotC:
686 elem.text = re.sub(
r"\([ ]*",
"(" +
" " * afterParenthesis, elem.text)
687 elem.text = re.sub(
r"\)[ ]*",
")" +
" " * afterParenthesis, elem.text)
690 if beforeComma
is not None:
691 elem.tail = re.sub(
r"[ ]*,",
" " * beforeComma +
r",", elem.tail)
692 if elem.text
is not None and isNotC:
693 elem.text = re.sub(
r"[ ]*,",
" " * beforeComma +
r",", elem.text)
694 if afterComma
is not None:
695 elem.tail = re.sub(
r",[ ]*",
"," +
" " * afterComma, elem.tail)
696 if elem.text
is not None and isNotC:
697 elem.text = re.sub(
r",[ ]*",
"," +
" " * afterComma, elem.text)
701 elem.tail = re.sub(
r"[ ]*\n",
r"\n", elem.tail)
704 if tag(elem)
in (
'N',
'T-N',
'attribute-N'):
706 for nnn
in elem.findall(
'{*}n'):
707 if nnn.tail
is not None:
708 nnn.tail = nnn.tail.strip(
' ')
709 if elem.tail
is not None and afterName
is not None:
710 elem.tail =
' ' * afterName + elem.tail.lstrip(
' ')
713 elif tag(elem) ==
'lower-bound' and elem.tail
is not None and ':' in elem.tail:
714 if beforeRangeDelim
is not None:
715 elem.tail =
' ' * beforeRangeDelim + elem.tail.lstrip(
' ')
716 if afterRangeDelim
is not None:
717 elem.tail = elem.tail.rstrip(
' ') +
' ' * beforeRangeDelim
720 elif tag(elem) ==
'module-N' and elem.tail
is not None and ':' in elem.tail:
721 if beforeUseDelim
is not None:
722 elem.tail = re.sub(
r"[ ]*:",
" " * beforeUseDelim +
r":", elem.tail)
723 if afterUseDelim
is not None:
724 elem.tail = re.sub(
r":[ ]*",
":" +
" " * afterUseDelim, elem.tail)
728 elif tag(elem)
in (
'attribute',
'_T-spec_')
and elem.tail
is not None:
730 elem.tail = re.sub(
r":[ ]*:",
r"::", elem.tail)
731 if beforeDeclDelim
is not None:
732 elem.tail = re.sub(
r"[ ]*(:[ ]*:)",
' ' * beforeDeclDelim +
r"\1", elem.tail)
733 if afterDeclDelim
is not None:
734 elem.tail = re.sub(
r"(:[ ]*:)[ ]*",
r"\1" +
' ' * afterDeclDelim, elem.tail)
735 if tag(elem) ==
'_T-spec_' and afterTypeDecl
is not None:
736 elem.tail = elem.tail.rstrip(
' ') +
' ' * afterTypeDecl
740 elif tag(elem) ==
'enumerator-stmt' and elem.text
is not None:
743 elem.text = re.sub(
r":[ ]*:",
r"::", elem.text)
744 if beforeDeclDelim
is not None:
745 elem.text = re.sub(
r"[ ]*(:[ ]*:)",
' ' * beforeDeclDelim +
r"\1",
747 if afterDeclDelim
is not None:
748 elem.text = re.sub(
r"(:[ ]*:)[ ]*",
r"\1" +
' ' * afterDeclDelim,
750 elif afterTypeDecl
is not None:
751 elem.text = elem.text.rstrip(
' ') +
' ' * afterTypeDecl
754 elif (tag(elem)
in (
'subroutine-stmt',
'program-stmt',
'module-stmt',
'function-stmt',
755 'submodule-stmt',
'procedure-stmt',
'interface-stmt',
756 'end-subroutine-stmt',
'end-program-stmt',
757 'end-module-stmt',
'end-function-stmt',
758 'end-submodule-stmt',
'end-procedure-stmt',
'end-interface-stmt')
759 and afterProgunit
is not None):
760 if elem.text
is not None:
761 elem.text = elem.text.rstrip(
' ') +
' ' * afterProgunit
764 elif tag(elem)
in (
'do-V',
'V')
and elem.tail
is not None and '=' in elem.tail:
765 if beforeEqDo
is not None:
766 elem.tail = re.sub(
'[ ]*=',
' ' * beforeEqDo +
'=', elem.tail)
767 if afterEqDo
is not None:
768 elem.tail = re.sub(
'=[ ]*',
'=' +
' ' * beforeEqDo, elem.tail)
771 elif tag(elem) ==
'arg-N' and elem.tail
is not None and '=' in elem.tail:
772 if beforeEqCall
is not None:
773 elem.tail = re.sub(
'[ ]*=',
' ' * beforeEqCall +
'=', elem.tail)
774 if afterEqCall
is not None:
775 elem.tail = re.sub(
'=[ ]*',
'=' +
' ' * beforeEqCall, elem.tail)
778 elif (tag(elem)
in (
'EN-N',
'named-constant')
and
779 elem.tail
is not None and '=' in elem.tail):
780 if beforeEqInit
is not None:
781 elem.tail = re.sub(
'[ ]*=',
' ' * beforeEqInit +
'=', elem.tail)
782 if afterEqInit
is not None:
783 elem.tail = re.sub(
'=[ ]*',
'=' +
' ' * beforeEqInit, elem.tail)
785 elif tag(elem) ==
'smc':
786 if beforeCmdsep
is not None:
787 prev = self.getSiblings(elem, after=
False)
788 if len(prev) != 0
and prev[-1].tail
is not None:
789 prev[-1].tail =
' ' * beforeCmdsep + prev[-1].tail.lstrip(
' ')
790 if afterCmdsep
is not None and elem.tail
is not None:
791 elem.tail = elem.tail.rstrip(
' ') +
' ' * afterCmdsep
794 elif tag(elem) ==
'associate-N' and elem.tail
is not None and '=' in elem.tail:
795 if beforeAffectation
is not None:
796 elem.tail = re.sub(
'[ ]*=',
' ' * beforeAffectation +
'=', elem.tail)
797 if afterAffectation
is not None:
798 elem.tail = re.sub(
'>[ ]*',
'>' +
' ' * beforeAffectation, elem.tail)
800 elem.tail = re.sub(
r'=[ ]*>',
'=>', elem.tail)
814 for elem
in self.iter():
816 if tag(elem) ==
'op-E':
817 for op
in elem.findall(
'{*}op'):
818 if beforeOp
is not None:
819 io = list(elem).index(op)
822 if prev.tail
is None:
823 prev.tail =
' ' * beforeOp
825 prev.tail = prev.tail.rstrip(
' ') +
' ' * beforeOp
826 if afterOp
is not None:
828 op.tail =
' ' * afterOp
830 op.tail = op.tail.lstrip(
' ') +
' ' * afterOp
832 for oo
in op.findall(
'{*}o'):
833 if oo.tail
is not None:
834 oo.tail = oo.tail.strip(
' ')
837 elif tag(elem)
in (
'a-stmt',
'pointer-a-stmt'):
839 for aff
in elem.findall(
'{*}a'):
840 if beforeAffectation
is not None:
841 prev = elem[list(elem).index(aff) - 1]
842 if prev.tail
is None:
843 prev.tail =
' ' * beforeAffectation
845 prev.tail = prev.tail.rstrip(
' ') +
' ' * beforeAffectation
846 if afterAffectation
is not None:
848 aff.tail =
' ' * afterAffectation
850 aff.tail = aff.tail.lstrip(
' ') +
' ' * afterAffectation
852 aff.text = aff.text.replace(
' ',
'')
856 elif tag(elem)
in (
'if-stmt',
'if-then-stmt',
'else-if-stmt',
857 'where-stmt',
'where-construct-stmt',
'else-where-stmt',
858 'select-case-stmt',
'case-stmt',
859 'forall-stmt',
'forall-construct-stmt'):
860 if afterIfwherecase
is not None and elem.text
is not None:
861 if tag(elem) ==
'case-stmt':
863 elem.text = elem.text.rstrip(
' ') +
' ' * afterIfwherecase
865 elem.text = re.sub(
r'[ ]*\(',
' ' * afterIfwherecase +
'(',
867 if tag(elem)
in (
'if-then-stmt',
'else-if-stmt')
and beforeThen
is not None:
868 cond = elem.find(
'{*}condition-E')
869 cond.tail = re.sub(
r'\)[ ]*([a-zA-Z]*$)',
')' +
' ' * beforeThen +
r'\1',
871 elif tag(elem) ==
'if-stmt' and beforeIfaction
is not None:
872 cond = elem.find(
'{*}condition-E')
873 cond.tail = re.sub(
r'\)[ ]*$',
')' +
' ' * beforeIfaction, cond.tail)
874 elif tag(elem) ==
'where-stmt' and beforeIfaction
is not None:
875 cond = elem.find(
'{*}mask-E')
876 cond.tail = re.sub(
r'\)[ ]*$',
')' +
' ' * beforeIfaction, cond.tail)
877 elif tag(elem) ==
'forall-stmt' and beforeIfaction
is not None:
878 sub = elem.find(
'{*}forall-triplet-spec-LT')
879 sub.tail = re.sub(
r'\)[ ]*$',
')' +
' ' * beforeIfaction, sub.tail)
882 if beforeEndcnt
is not None or afterBegincnt
is not None:
883 for elem
in self.findall(
'.//{*}cnt/..'):
884 for cnt
in elem.findall(
'{*}cnt'):
885 ic = list(elem).index(cnt)
894 if '\n' in pstring
and '\n' in cnt.tail:
897 elif '\n' in pstring
and afterBegincnt
is not None:
899 cnt.tail =
' ' * afterBegincnt + cnt.tail.lstrip(
' ')
900 elif beforeEndcnt
is not None:
904 prev.text = prev.text.rstrip(
' ') +
' ' * beforeEndcnt
906 prev.tail = prev.tail.rstrip(
' ') +
' ' * beforeEndcnt
909 for key, val
in adjaKeyDesc.items():
910 num = getvalAdja(key)
912 for node
in self.findall(val[1]):
913 lf =
"[ ]*".join([
"(" + p +
")" for p
in key.split(
'_')])
914 repl = (
" " * num).join([
r"\{i}".format(i=i + 1)
915 for i, _
in enumerate(key.split(
'_'))])
916 node.text = re.sub(lf, repl, node.text, flags=re.IGNORECASE)
1197 Split the lines longer than a maximum length.
1199 The transformation is done on the XML tree:
1201 - code lines are split by inserting continuation characters ('&' at the end
1202 of the line and '&' at the beginning of the next line). Splitting is only
1203 done after a comma, after '::', after the '=' of an assignment or before an
1204 operator. It is never done inside strings, comments, preprocessor lines,
1205 or inside an array index selection (index selection containing a ':' or
1206 applied to a variable declared as an array, see isArrayIndexSelection);
1207 - comments are split on several comment lines, at spaces (words, e.g. URLs,
1208 are never cut). A trailing comment that cannot be shortened enough is
1209 moved to its own line. Blanks or decorations (a repeated punctuation
1210 character, e.g. '!!!!!' or '-----') beyond the limit are removed.
1211 Directives (comments beginning with '!$', '!DIR$' or '!DEC$') are never
1213 - trailing blanks are removed from the lines that are too long only
1216 Because the line length is a property of the file, the whole file is always
1217 processed, even if the method is called on a sub-scope. The length is
1218 computed in characters. Lines that cannot be split are reported with a
1223 maxLength : int, optional
1224 Maximum allowed line length in characters. Default is 132
1225 (limit of the FORTRAN free source form).
1230 True if, after the transformation, no line exceeds maxLength.
1235 If the file is written in fixed source form.
1239 >>> pft = PYFT('input.F90')
1240 >>> pft.splitLongLines() # Split lines longer than 132 characters
1241 >>> pft.splitLongLines(maxLength=100) # Split lines longer than 100 characters
1245 if root.get(
'source-form',
'FREE') !=
'FREE':
1246 raise PYFTError(
"splitLongLines is only implemented for the free source form " +
1247 "(file '{}')".format(self.getFileName()))
1251 fxtran stores each byte of a UTF-8 character as a separate character
1252 :return: (decoded text, True if decoding was done)
1255 decoded = text.encode(
'latin-1').decode(
'UTF-8')
1256 return decoded, decoded != text
1257 except (UnicodeEncodeError, UnicodeDecodeError):
1260 def enc(text, decoded):
1261 """Inverse of dec"""
1262 return text.encode(
'UTF-8').decode(
'latin-1')
if decoded
else text
1264 parentOf = {id(child): node
for node
in root.iter()
for child
in node}
1265 scopeOf = {id(scope._xml): scope
for scope
in self.
mainScope.getScopes()}
1268 def getParent(node):
1269 return parentOf.get(id(node))
1272 while id(node)
not in scopeOf:
1273 node = parentOf[id(node)]
1274 return scopeOf[id(node)]
1276 def isForbidden(node):
1278 :param node: xml node containing a text
1279 :return: True if no continuation can be inserted in this node
1283 while node
is not None:
1284 if id(node)
in forbiddenCache:
1285 result = forbiddenCache[id(node)]
1288 if tag(node)
in (
'C',
'S',
'cpp',
'cnt',
'l',
'label')
or \
1289 self.isArrayIndexSelection(node, getParent, getScope):
1292 node = getParent(node)
1294 forbiddenCache[id(item)] = result
1302 pieces.append([node,
'text', *dec(node.text
or '')])
1305 pieces.append([child,
'tail', *dec(child.tail
or '')])
1308 def setText(ipiece, text):
1309 piece = pieces[ipiece]
1311 if piece[1] ==
'text':
1312 piece[0].text = enc(text, piece[3])
1314 piece[0].tail = enc(text, piece[3])
1316 def insertNodes(ipiece, nodes, newPieces):
1318 Insert nodes at the position of the piece ipiece in the xml tree,
1319 and the corresponding newPieces after ipiece in the list of pieces
1321 node, kind = pieces[ipiece][:2]
1323 parent, index = node, 0
1325 parent = parentOf[id(node)]
1326 index = list(parent).index(node) + 1
1327 for i, item
in enumerate(nodes):
1328 parent.insert(index + i, item)
1329 parentOf[id(item)] = parent
1330 pieces[ipiece + 1:ipiece + 1] = newPieces
1332 def getLine(ipiece, offset):
1334 :param ipiece, offset: index of the piece and offset in this piece of the
1335 beginning of the line
1336 :return: (line, linePieces, ipiece, offset) with linePieces the list of
1337 (index of piece, column, start offset, end offset) of the pieces
1338 composing the line, and (ipiece, offset) the beginning of the next
1339 line (ipiece is None for the last line)
1343 while ipiece < len(pieces):
1344 text = pieces[ipiece][2]
1345 end = text.find(
'\n', offset)
1347 linePieces.append((ipiece, len(line), offset, len(text)))
1348 line += text[offset:]
1349 ipiece, offset = ipiece + 1, 0
1351 linePieces.append((ipiece, len(line), offset, end))
1352 line += text[offset:end]
1353 return line, linePieces, ipiece, end + 1
1354 return line, linePieces,
None, 0
1356 def isDirective(comment):
1357 return re.match(
r'!(\$|dir\$|dec\$)', comment, re.IGNORECASE)
is not None
1362 while lineStart[0]
is not None:
1363 line, linePieces, *nextLine = getLine(*lineStart)
1364 if len(line) <= maxLength:
1365 lineStart = tuple(nextLine)
1368 indent = len(line) - len(line.lstrip(
' '))
1371 comment = [(ipiece, column)
for ipiece, column, _, _
in linePieces
1372 if tag(pieces[ipiece][0]) ==
'C' and pieces[ipiece][1] ==
'text']
1373 comment = comment[0]
if len(comment) > 0
else None
1374 codeEnd = len(line)
if comment
is None else comment[1]
1375 codeLength = len(line[:codeEnd].rstrip(
' '))
1378 if codeLength > maxLength:
1381 for ipiece, column, segStart, segEnd
in linePieces:
1382 if column > codeEnd:
1384 node, kind, text = pieces[ipiece][:3]
1385 if kind ==
'text' and tag(node)
in (
'op',
'a'):
1386 if not isForbidden(parentOf[id(node)]):
1387 if tag(node) ==
'op':
1389 candidates.append((column, ipiece - 1, len(pieces[ipiece - 1][2])))
1392 candidates.append((column + len(text), ipiece + 1, 0))
1393 elif not isForbidden(node
if kind ==
'text' else parentOf[id(node)]):
1395 for match
in re.finditer(
r',|::', text[segStart:segEnd]):
1396 candidates.append((column + match.end(), ipiece,
1397 segStart + match.end()))
1398 candidates = [cand
for cand
in candidates
1399 if 0 <= cand[0] <= codeEnd
and
1400 len(line[:cand[0]].rstrip(
' ')) + 2 <= maxLength
and
1401 line[:cand[0]].strip(
' ')
not in (
'',
'&')
and
1402 line[cand[0]:codeEnd].strip(
' ') !=
'']
1403 if len(candidates) > 0:
1404 _, ipiece, offset = max(candidates, key=
lambda cand: cand[0])
1405 contIndent = indent + (0
if line.lstrip(
' ').startswith(
'&')
else 2)
1406 if contIndent + 22 > maxLength:
1408 text, decoded = pieces[ipiece][2:4]
1409 after =
' ' + text[offset:].lstrip(
' ')
1410 setText(ipiece, text[:offset].rstrip(
' ') +
' ')
1411 cnt1 = createElem(
'cnt', text=
'&', tail=
'\n' +
' ' * contIndent)
1412 cnt2 = createElem(
'cnt', text=
'&', tail=enc(after, decoded))
1413 insertNodes(ipiece, [cnt1, cnt2],
1414 [[cnt1,
'text',
'&',
False], [cnt1,
'tail', cnt1.tail,
False],
1415 [cnt2,
'text',
'&',
False], [cnt2,
'tail', after, decoded]])
1417 elif comment
is not None and not isDirective(pieces[comment[0]][2]):
1419 icomment, column = comment
1420 text, decoded = pieces[icomment][2:4]
1421 prefix = re.match(
r'!+ *', text).group(0)
1422 width = maxLength - column
1424 cut = text.rfind(
' ', len(prefix), width + 1)
if width > len(prefix)
else -1
1425 if width > len(prefix)
and \
1426 re.fullmatch(
r' *(([^\w ])\2*)? *', text[width:])
is not None:
1429 setText(icomment, text[:width].rstrip(
' '))
1431 elif codeLength > 0
and (width < len(prefix) + 20
or cut == -1):
1434 ipiece, pcolumn, segStart, _ = [item
for item
in linePieces
1435 if item[1] < column][-1]
1436 offset = segStart + column - pcolumn
1437 text = pieces[ipiece][2]
1438 setText(ipiece, text[:offset].rstrip(
' ') +
'\n' +
' ' * indent +
1445 cut = text.find(
' ', max(width, len(prefix)))
1446 rest = text[cut:].lstrip(
' ')
if cut != -1
else ''
1451 room = len(prefix) + max(20, len(rest.split(
' ')[0]))
1452 newColumn = column
if column + room <= maxLength
else indent
1454 tail = pieces[icomment + 1][2]
1455 newComment = createElem(
'C', text=enc(prefix + rest, decoded),
1456 tail=enc(tail, pieces[icomment + 1][3]))
1457 setText(icomment, text[:cut].rstrip(
' '))
1458 setText(icomment + 1,
'\n' +
' ' * newColumn)
1460 insertNodes(icomment + 1, [newComment],
1461 [[newComment,
'text', prefix + rest, decoded],
1462 [newComment,
'tail', tail, pieces[icomment + 1][3]]])
1464 elif len(line.rstrip(
' ')) <= maxLength:
1466 length = len(line.rstrip(
' '))
1467 for ipiece, column, segStart, segEnd
in linePieces:
1468 if column + segEnd - segStart > length:
1469 start = segStart + max(length - column, 0)
1470 text = pieces[ipiece][2]
1471 setText(ipiece, text[:start] + text[segEnd:])
1475 logging.warning(
"The line %i (%i characters) cannot be split, in file '%s'",
1476 iline + 1, len(line), self.getFileName())
1478 lineStart = tuple(nextLine)