PyForTool
Python-fortran-tool
Loading...
Searching...
No Matches
cosmetics.py
1"""
2Code formatting and style transformations.
3
4Provides the Cosmetics class for modifying FORTRAN code appearance including
5case, indentation, spacing, comments, and line continuation.
6
7Key Features
8-----------
9- Case conversion (upper/lower FORTRAN keywords)
10- Indentation fixing with directive exclusion
11- Comment removal with directive preservation
12- Whitespace normalization
13- Line continuation alignment
14- USE statement ordering and grouping
15
16Classes
17-------
18Cosmetics : Mixin class providing code formatting methods
19
20Examples
21--------
22>>> pft = PYFT('input.F90')
23>>> pft.upperCase() # Convert keywords to UPPER CASE
24>>> pft.lowerCase() # Convert keywords to lower case
25>>> pft.indent() # Fix indentation
26>>> pft.removeComments() # Remove comments (keep directives)
27>>> pft.prettify() # Full formatting (indent + case + spaces)
28"""
29
30import re
31import logging
32from pyfortool.util import debugDecor, nonCode, tag, tofortran, PYFTError
33from pyfortool.expressions import createElem
34from pyfortool.variables import updateVarList
35from pyfortool import NAMESPACE
36
37
38class Cosmetics():
39 """
40 Code formatting and style transformation methods.
41
42 Provides utilities for modifying code appearance including case,
43 indentation, spacing, and comment handling.
44 """
45
46 @debugDecor
47 def upperCase(self):
48 """
49 Convert all FORTRAN keywords to uppercase.
50
51 Examples
52 --------
53 >>> pft = PYFT('mixed.F90')
54 >>> pft.upperCase()
55 # WRITE -> write becomes WRITE
56 """
57 for elem in self.iter():
58 if (not nonCode(elem)) and elem is not None and elem.text is not None:
59 elem.text = elem.text.upper()
60
61 @debugDecor
62 def lowerCase(self):
63 """
64 Convert all FORTRAN keywords to lowercase.
65
66 Examples
67 --------
68 >>> pft = PYFT('MIXED.F90')
69 >>> pft.lowerCase()
70 # WRITE -> write
71 """
72 for elem in self.iter():
73 if (not nonCode(elem)) and elem is not None and elem.text is not None:
74 elem.text = elem.text.lower()
75
76 @debugDecor
77 def indent(self, nodeToUpdate=None, indentProgramunit=0, indentBranch=2,
78 exclDirectives=None):
79 """
80 Fix code indentation.
81
82 Parameters
83 ----------
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.
95
96 Returns
97 -------
98 self
99 Returns self for chaining.
100
101 Examples
102 --------
103 >>> pft = PYFT('input.F90')
104 >>> pft.indent() # Default indentation
105 >>> pft.indent(indentProgramunit=0, indentBranch=4) # Custom
106 """
107
108 if nodeToUpdate is None:
109 nodeToUpdate = self
110
111 if exclDirectives is None:
112 exclDirectives = ['!$OMP']
113
114 def setLevel(elem, level, nextElem):
115 """
116 :param elem: element whose tail must be modifies
117 :param level: level of indentation
118 :param nextElem: next element
119 """
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)))
126 if not excl:
127 elem.tail = re.sub('\n[ ]*', '\n' + ' ' * level, elem.tail)
128
129 def indentRecur(elem, level, inConstruct):
130 """
131 :param elem: dom element
132 :param level: current level for elem
133 :param inConstruct: True if we are inside a construct
134 """
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']
142
143 currlevel = level
144 laste = None
145 firstnumselect = True
146 for ie, sElem in enumerate(elem):
147 # Indentation does not apply to these lines (eg SUBROUTINE statement, DO construct)
148 # but apply to the lines inside
149 if tag(sElem) in progstmt:
150 currlevel += indentProgramunit
151 elif tag(sElem) in branchstmt + [inConstruct + '-stmt']:
152 currlevel += indentBranch
153
154 # Add indentation *to the tail*, thus for the next line
155 setLevel(sElem, currlevel, elem[ie + 1] if ie + 1 < len(elem) else None)
156
157 if tag(elem) == 'selectcase-construct':
158 # Structure is:
159 # <selectcase-construct>
160 # <selectcase-block><select-case-stmt>SELECT
161 # CASE (...)</select-case-stmt> \n +2
162 # </selectcase-block>
163 # <selectcase-block><case-stmt>CASE<case-selector>(...)
164 # </case-selector></case-stmt> \n +4
165 # statement \n +4
166 # statement \n +2
167 # </selectcase-block>
168 # <selectcase-block><case-stmt>CASE<case-selector>(...)
169 # </case-selector></case-stmt> \n +4
170 # statement \n +4
171 # statement \n +0
172 # <end-select-case-stmt>END SELECT</end-select-case-stmt>
173 # </selectcase-block></selectcase-construct>
174 if firstnumselect:
175 firstnumselect = False
176 else:
177 # previous line was a CASE line, we must indent it only once
178 # pylint: disable-next=unsubscriptable-object
179 setLevel(laste[-1], level + indentBranch, sElem)
180 # statements are indented twice
181 indentRecur(sElem, level + indentBranch * 2, "")
182 if tag(sElem[-1]) == 'end-select-case-stmt':
183 setLevel(sElem[-2], level, sElem[-1])
184
185 elif tag(sElem) in blocs or tag(sElem).endswith('-construct'):
186 # This xml tag contains other tags, we iterate on them
187 if tag(sElem[0]) in interbranchstmt:
188 # Structure is <if-construct><if-block><if-then-stmt>IF...
189 # ...THEN</if-then-stmt>
190 # statement (the identation of the ELSE line is
191 # in the tail of this stetement)
192 # </if-block><if-block><else-stmt>ELSE</else-stmt>
193 # statement
194 # <end-if-stmt>ENDIF</end-if-stmt></if-block></if-construct>
195 # pylint: disable-next=unsubscriptable-object
196 setLevel(laste[-1], level, sElem)
197 construct = tag(sElem)[:-10] if tag(sElem).endswith('-construct') else ""
198 indentRecur(sElem, currlevel, construct)
199
200 # This line contains the end statement, we must remove the indentation contained
201 # in the tail of the previous item
202 if tag(sElem) in endprogstmt + endbranchstmt + ['end-' + inConstruct + '-stmt']:
203 setLevel(laste, level, sElem)
204 laste = sElem
205
206 indentRecur(nodeToUpdate, 0, "")
207 return nodeToUpdate
208
209 @debugDecor
211 """
212 Remove empty lines
213 """
214 elem = self.find('{*}file')
215 if elem is not None and elem.text is not None:
216 elem.text = elem.text.replace('\n', '')
217 for elem in self.iter():
218 if elem.tail is not None and '\n' in elem.tail:
219 elem.tail = elem.tail.replace('\t', ' ')
220 elem.tail = re.sub(r"\n[  \n]*\n", r"\n", elem.tail)
221
222 @debugDecor
223 def removeComments(self, exclDirectives=None, pattern=None):
224 """
225 Remove comments from the source code.
226
227 Parameters
228 ----------
229 exclDirectives : list, optional
230 Comments to preserve (directives to exclude):
231 - None: Preserve '!$OMP', '!$mnh', '!$ACC' lines (default).
232 - []: Remove all comments.
233 - ['!$acc']: Preserve only specific directives.
234 pattern : str or re.Pattern, optional
235 Only remove comments matching this pattern.
236
237 Examples
238 --------
239 >>> pft = PYFT('input.F90')
240 >>> pft.removeComments() # Keep OpenMP/directives
241 >>> pft.removeComments(exclDirectives=[]) # Remove all
242 >>> pft.removeComments(pattern=re.compile(r'!.*TODO'))
243 """
244 if exclDirectives is None:
245 exclDirectives = ['!$OMP', '!$mnh', '!$ACC', '!$acc']
246
247 if isinstance(pattern, str):
248 pattern = re.compile(pattern)
249
250 def recur(elem):
251 tailUpper = None
252 for ie in range(len(elem))[::-1]: # Loop from the end to the begining
253 sElem = elem[ie]
254 if tag(sElem) == 'C' and \
255 not any(sElem.text.startswith(d) for d in exclDirectives) and \
256 (pattern is None or pattern.match(sElem.text)):
257 # Don't loose the tail (containing new line character and indentation)
258 if ie != 0:
259 # It exists an element before,
260 # we add the current tail to this previsous element
261 if elem[ie - 1].tail is None:
262 elem[ie - 1].tail = sElem.tail
263 elif sElem.tail is not None:
264 elem[ie - 1].tail += sElem.tail
265 else:
266 # The's no previsous element, tail is givent back the container element
267 tailUpper = sElem.tail
268 elem.remove(sElem)
269 if len(sElem) >= 1:
270 tail = recur(sElem) # recursive call to inner elements
271 if tail is not None:
272 # The first element was a comment,
273 # its tail must be added to the text attribute
274 if sElem.text is None:
275 sElem.text = tail
276 else:
277 sElem.text += tail
278 return tailUpper
279 recur(self)
280
281 @debugDecor
282 def updateContinuation(self, nodeToUpdate=None, align=True,
283 removeALL=False, addBegin=True, removeBegin=False):
284 """
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
292
293 When suppressed, the '&' are replaced by a space character
294 Comments after a '&' are lost
295 """
296
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"
300
301 if nodeToUpdate is None:
302 nodeToUpdate = self
303
304 parents = {} # cache to be used in recurDirect
305
306 def recurReverse(elem, tail):
307 for ie in range(len(elem))[::-1]: # Loop from the end to the begining
308 sElem = elem[ie]
309 parents[sElem] = elem
310 if tag(sElem) == 'cnt':
311 # Search for comments or cpp after the cnt node
312 commentsAfter = []
313 j = ie + 1
314 while j < len(elem) and tag(elem[j]) in ('C', 'cpp'):
315 commentsAfter.append(elem[j])
316 j += 1
317 nextNode = elem[j] if j < len(elem) else None
318
319 # Is it a '&' at the end of a line (or at the begining)?
320 isend = ((sElem.tail is not None and '\n' in sElem.tail) or
321 len(commentsAfter) > 0)
322
323 # Add missing continuation character at the begining of line
324 if isend and addBegin:
325 if sElem.tail is not None and \
326 sElem.tail.replace('\n', '').replace('\t', '').lstrip(' ') != '':
327 # tail contains text, probably an endding ')', after a carriage return
328 # Thus, there is no '&' to begin line
329 new = createElem('cnt', text='&')
330 # '&' must be put before any text on the following line containing code
331 i = 0
332 while sElem.tail[i] in (' ', '\n', '\t'):
333 i += 1
334 new.tail = ' ' + sElem.tail[i:]
335 sElem.tail = sElem.tail[:i]
336 elem.insert(ie + 1, new)
337 elif tag(nextNode) != 'cnt':
338 # There is no '&' to begin next line
339 new = createElem('cnt', text='&')
340 if len(commentsAfter) > 0:
341 # '&' must be put before any text on the following
342 # line containing code
343 i = 0
344 while i < len(commentsAfter[-1].tail) and \
345 commentsAfter[-1].tail[i] in (' ', '\n', '\t'):
346 i += 1
347 new.tail = ' ' + commentsAfter[-1].tail[i:]
348 commentsAfter[-1].tail = commentsAfter[-1].tail[:i]
349 else:
350 new.tail = ' '
351 elem.insert(ie + 1 + len(commentsAfter), new)
352
353 # Suppression
354 if removeALL or (removeBegin and not isend):
355 cpp = False
356 for com in commentsAfter[::-1]:
357 if tag(com) != 'cpp':
358 elem.remove(com)
359 else:
360 cpp = True
361 if not cpp:
362 # We cannot remove a continuation line followed by a cpp
363 elem.remove(sElem) # OK because we loop in reverse order
364 if sElem.tail is not None:
365 txt = sElem.tail.strip() + ' '
366 else:
367 txt = ' '
368 if ie != 0:
369 if elem[ie - 1].tail is None:
370 elem[ie - 1].tail = txt
371 else:
372 elem[ie - 1].tail += txt
373
374 # Recursively enter blocs
375 if len(sElem) >= 1:
376 recurReverse(sElem, tail)
377
378 def recurDirect(elem, ct, inCnt):
379 """
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
383 """
384 ignoreComment = False
385 if align:
386 for ie, sElem in enumerate(list(elem)):
387 # It is a '&' character marking the end of the line
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
392 (isendcnt and
393 (ie + 1 < len(elem) and tag(elem[ie + 1]) == 'C')))
394
395 # REAL :: X1, & !comment 1
396 # !comment 2
397 # X2, &
398 # #ifdef XXX
399 # X3, &
400 # #endif
401 # X4
402 if isendcnt or ignoreComment or (inCnt != -1 and tag(sElem) == 'cpp'):
403 # Number of spaces for alignment not already determined
404 # (first line of the continuation)
405 if isendcnt and inCnt == -1:
406 # Search for the container statement
407 topstmt = elem
408 while not tag(topstmt).endswith('-stmt'):
409 topstmt = parents[topstmt]
410
411 # Character to align on
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')
436 else:
437 patList = ('::', ':', r'\‍(', '=>', '=', '[', ':', '/')
438
439 # Compute indentation value
440 inCnt = None
441 for pat in patList:
442 if inCnt is None:
443 mat = re.search(pat, ct, flags=re.IGNORECASE)
444 if mat is not None:
445 if ie + 1 < len(elem) and tag(elem[ie + 1]) != 'cnt':
446 # If there is no continuation character at the begining,
447 # align the text with the position after the delimiter
448 # found
449 inCnt = mat.end()
450 else:
451 inCnt = mat.end() - 1
452 if inCnt is None:
453 inCnt = 4
454
455 # Align the next line exept if it is a cpp line
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)
459 else:
460 sElem.tail = '\n' + ' ' * inCnt
461
462 if tag(sElem) not in ('C', 'cnt'):
463 ct += (sElem.text if sElem.text is not None else '')
464 ignoreComment = False
465
466 # Recursively enter the inner blocks
467 if len(sElem) >= 1:
468 ct, inCnt = recurDirect(sElem, ct, inCnt)
469
470 # Text after the end of block
471 ct += (sElem.tail if sElem.tail is not None else '')
472 if '\n' in ct:
473 ct = ct.split('\n')[-1]
474 if tag(sElem) not in ('cnt', 'C', 'cpp'):
475 inCnt = -1
476
477 return ct, inCnt
478
479 recurReverse(nodeToUpdate, 0)
480 recurDirect(nodeToUpdate, "", -1)
481 return nodeToUpdate
482
483 __NO_VALUE__ = '__NO_VALUE__'
484
485 @debugDecor
486 def updateSpaces(self, beforeOp=1, afterOp=1, inOperator=True,
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,
499 afterProgunit=1,
500 endOfLine=True, afterName=0, inName=True,
501 beforeCmdsep=0, afterCmdsep=1,
502 adjacentKeywords=__NO_VALUE__, afterKeywords=__NO_VALUE__):
503 """
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
519 FORALL statements
520 :param beforeEqCall, afterEqCall: number of spaces before and after '=' sign
521 in CALL statement
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
532 statement and
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:
546 - block_data
547 - double_precision
548 - else_if
549 - else_where
550 - end_associate
551 - end_block
552 - end_block_data
553 - end_critical
554 - end_do
555 - end_enum
556 - end_file
557 - end_forall
558 - end_function
559 - end_if
560 - end_interface
561 - end_module
562 - end_procedure
563 - end_program
564 - end_selec
565 - end_select
566 - end_submodule
567 - end_subroutine
568 - end_team
569 - end_type
570 - end_where
571 - go_to
572 - in_out
573 - select_case
574 - select_type
575 - implicit_none
576 - module_procedure
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.
588
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
591
592 Updates are done in the following order:
593 """
594
595 adjaKeyDesc = {
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'),
627 }
628
629 afterKey = {
630 'print': 0,
631 'call': 1,
632 'use': 1,
633 'do': 1,
634 'end-file': 1,
635 'save': 1,
636 }
637
638 assert adjacentKeywords is None or adjacentKeywords == self.__NO_VALUE__ or \
639 all(k in adjaKeyDesc
640 for k in adjacentKeywords), "Unknown key in **adjacentKeywords"
641
642 def getvalAdja(key):
643 if adjacentKeywords is None:
644 return None
645 if adjacentKeywords == self.__NO_VALUE__:
646 return adjaKeyDesc[key][0]
647 return adjacentKeywords.get(key, adjaKeyDesc[key][0])
648
649 def getvalAfter(key):
650 key = key[:-5]
651 if afterKeywords != self.__NO_VALUE__:
652 num = afterKeywords.get(key, afterKey.get(key, None))
653 else:
654 num = afterKey.get(key, None)
655 return num
656
657 assert afterProgunit is None or afterProgunit >= 1
658 assert afterTypeDecl is None or afterTypeDecl >= 1
659 for k in ('implicit_none', 'module_procedure'):
660 num = getvalAdja(k)
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) + ")"
667
668 for elem in self.iter():
669 isNotC = tag(elem) != 'C'
670 # security
671 if elem.tail is None:
672 elem.tail = ""
673 elem.tail = elem.tail.replace('\t', ' ')
674
675 # Around parenthesis
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)
688
689 # Around commas
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)
698
699 # End of line
700 if endOfLine:
701 elem.tail = re.sub(r"[  ]*\n", r"\n", elem.tail)
702
703 # In names or around names (identifier, type, attribute)
704 if tag(elem) in ('N', 'T-N', 'attribute-N'):
705 if inName:
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(' ')
711
712 # Around range delimiter
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
718
719 # Around ':' in USE statements
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)
725
726 # Around and in '::' in declaration statements
727 # After the type in a declaration
728 elif tag(elem) in ('attribute', '_T-spec_') and elem.tail is not None:
729 if inDeclDelim:
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
737
738 # Around and in '::' in enumerators
739 # After the enumerator keyword
740 elif tag(elem) == 'enumerator-stmt' and elem.text is not None:
741 if ':' in elem.text:
742 if inDeclDelim:
743 elem.text = re.sub(r":[  ]*:", r"::", elem.text)
744 if beforeDeclDelim is not None:
745 elem.text = re.sub(r"[ ]*(:[  ]*:)", ' ' * beforeDeclDelim + r"\1",
746 elem.text)
747 if afterDeclDelim is not None:
748 elem.text = re.sub(r"(:[  ]*:)[ ]*", r"\1" + ' ' * afterDeclDelim,
749 elem.text)
750 elif afterTypeDecl is not None:
751 elem.text = elem.text.rstrip(' ') + ' ' * afterTypeDecl
752
753 # Between the program unit type and its name
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
762
763 # Around '=' sign in DO and FORALL statements
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)
769
770 # Around '=' sign in CALL statements
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)
776
777 # Around '=' sign for init values
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)
784 # Around the command separator ';'
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
792
793 # Around and in association operators (affectation case done after)
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)
799 if inAffectation:
800 elem.tail = re.sub(r'=[ ]*>', '=>', elem.tail)
801
802 # After a reserved keyword
803 # elif afterKeywords is not None and tag(elem).endswith('-stmt'):
804 # num = getvalAfter(tag(elem))
805 # if num is not None and elem.text is not None:
806 # elem.text = elem.text.rstrip(' ') + ' ' * num
807
808 # Another loop on elements
809 # All the transformations are not put in a single loop because the following one act
810 # on sub-elements. Putting them all in the same loop would prevent to control in which order
811 # the different transformations occur.
812 # For instance, the suppression on the space after the parenthesis must be done before
813 # the adding of a space before a THEN keyword
814 for elem in self.iter():
815 # Around and in operators
816 if tag(elem) == 'op-E': # op are always (?) in op-E nodes
817 for op in elem.findall('{*}op'):
818 if beforeOp is not None:
819 io = list(elem).index(op)
820 if io != 0:
821 prev = elem[io - 1]
822 if prev.tail is None:
823 prev.tail = ' ' * beforeOp
824 else:
825 prev.tail = prev.tail.rstrip(' ') + ' ' * beforeOp
826 if afterOp is not None:
827 if op.tail is None:
828 op.tail = ' ' * afterOp
829 else:
830 op.tail = op.tail.lstrip(' ') + ' ' * afterOp
831 if inOperator:
832 for oo in op.findall('{*}o'):
833 if oo.tail is not None:
834 oo.tail = oo.tail.strip(' ')
835
836 # Around and in affectation operators (association case done before)
837 elif tag(elem) in ('a-stmt', 'pointer-a-stmt'):
838 # a are always (?) in a-stmt or pointer-a-stmt nodes
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
844 else:
845 prev.tail = prev.tail.rstrip(' ') + ' ' * beforeAffectation
846 if afterAffectation is not None:
847 if aff.tail is None:
848 aff.tail = ' ' * afterAffectation
849 else:
850 aff.tail = aff.tail.lstrip(' ') + ' ' * afterAffectation
851 if inAffectation:
852 aff.text = aff.text.replace(' ', '')
853
854 # After a IF, WHERE, ELSEIF, ELSEWHERE, SELECTCASE, CASE and FORALL keyword,
855 # and before THEN keyword
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':
862 # the (eventual) parenthesis is not in the text of the node
863 elem.text = elem.text.rstrip(' ') + ' ' * afterIfwherecase
864 else:
865 elem.text = re.sub(r'[ ]*\‍(', ' ' * afterIfwherecase + '(',
866 elem.text, count=1)
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',
870 cond.tail)
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)
880
881 # Direct search to prevent using the costly getParent function
882 if beforeEndcnt is not None or afterBegincnt is not None:
883 for elem in self.findall('.//{*}cnt/..'): # node containing continuation characters
884 for cnt in elem.findall('{*}cnt'): # continuation characters
885 ic = list(elem).index(cnt)
886 if ic == 0:
887 # the string before the continuation character is in the parent text
888 prev = elem
889 pstring = prev.text
890 else:
891 # the string before the continuation character is in previsous sibling tail
892 prev = elem[ic - 1]
893 pstring = prev.tail
894 if '\n' in pstring and '\n' in cnt.tail:
895 # continuation character alone on a line
896 pass
897 elif '\n' in pstring and afterBegincnt is not None:
898 # continuation character at the begining of a line
899 cnt.tail = ' ' * afterBegincnt + cnt.tail.lstrip(' ')
900 elif beforeEndcnt is not None:
901 # continuation character at the end of a line
902 # (eventually followed by a comment)
903 if prev == elem:
904 prev.text = prev.text.rstrip(' ') + ' ' * beforeEndcnt
905 else:
906 prev.tail = prev.tail.rstrip(' ') + ' ' * beforeEndcnt
907
908 # In adjacent keywords
909 for key, val in adjaKeyDesc.items():
910 num = getvalAdja(key)
911 if num is not None:
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)
917
918 @debugDecor
919 def changeIfStatementsInIfConstructs(self, singleItem=None):
920 """
921 Convert one-line IF statements to IF-THEN-ENDIF blocks.
922
923 Parameters
924 ----------
925 singleItem : Element, optional
926 Specific IF statement node to convert. If None, converts all.
927
928 Transformation
929 -------------
930 Before:
931 IF(A=B) print*, "C"
932
933 After:
934 IF(A=B) THEN
935 print*, "C"
936 END IF
937
938 Examples
939 --------
940 >>> pft = PYFT('input.F90')
941 >>> pft.changeIfStatementsInIfConstructs()
942 """
943 if singleItem is not None:
944 ifstmt = [singleItem]
945 else:
946 ifstmt = self.findall('.//{*}if-stmt')
947 for item in ifstmt:
948 cycleStmt = item.findall('.//{*}cycle-stmt')
949 if len(cycleStmt) == 0:
950 # Get indentation from last sibling
951 par = self.getParent(item)
952 ind = par[:].index(item)
953 if ind != 0 and par[ind - 1].tail is not None:
954 # if tail of previous sibling exists
955 currIndent = len(par[ind - 1].tail) - len(par[ind - 1].tail.rstrip(' '))
956 else:
957 # no tail = no indentation
958 currIndent = 0
959
960 # Convert if-stmt into if-construct
961 # <if-stmt>IF(<condition-E>...</condition-E>) <f:action-stmt>...
962 # ...</f:action-stmt></f:if-stmt>
963 # <if-construct><if-block><if-then-stmt>IF(<f:condition-E>...
964 # ...</condition-E>) THEN</f:if-then-stmt>
965 # ...
966 # <f:end-if-stmt>ENDIF</f:end-if-stmt></f:if-block></f:if-construct>
967 # 1 create missing blocks
968 item.tag = f'{{{NAMESPACE}}}if-construct'
969 ifBlock = createElem('if-block')
970 ifThenStmt = createElem('if-then-stmt')
971 endif = createElem('end-if-stmt')
972 ifBlock.append(ifThenStmt)
973 item.append(ifBlock)
974 # 2 move 'IF(' text
975 ifThenStmt.text = item.text # copy 'IF(' text
976 ifThenStmt.tail = '\n' + (2 + currIndent) * ' ' # indentation for main statement
977 item.text = None # remove olf 'IF(' text
978 # 3 move condition and add THEN
979 condition = item.find('{*}condition-E')
980 if not condition.tail.endswith(' '):
981 condition.tail += ' '
982 condition.tail += 'THEN'
983 ifThenStmt.append(condition)
984 item.remove(condition)
985 # 4 move action
986 action = item.find('{*}action-stmt')
987 action[0].tail = '\n' + currIndent * ' ' # indentation for the ENDIF
988 ifBlock.append(action[0])
989 item.remove(action)
990 # 5 add ENDIF
991 endif.text = 'END IF'
992 ifBlock.append(endif)
993 # 6 remove any cnt which was directly in the if-stmt node
994 # (replaced by '\n' after THEN)
995 for cnt in item.findall('./{*}cnt'):
996 item.remove(cnt)
997
998 @debugDecor
1000 """
1001 Remove the CONTAINS statement if this section is empty
1002 """
1003 for contains in self.findall('.//{*}contains-stmt'):
1004 par = self.getParent(contains)
1005 index = list(par).index(contains)
1006 nextStmt = index + 1
1007 while tag(par[nextStmt]) == 'C':
1008 nextStmt += 1
1009 if tag(par[nextStmt]) in ('end-subroutine-stmt', 'end-function-stmt',
1010 'end-module-stmt'):
1011 # CONTAINS bloc is empty
1012 par.remove(contains)
1013
1014 @debugDecor
1015 def formatModuleUse(self, upper=True):
1016 """
1017 Order USE declarations by module type and alphabetically.
1018
1019 Groups USE statements by module type prefix and sorts alphabetically
1020 within each group. The group order is: MODD_, MODE_, MODI_, MODN_,
1021 followed by any other modules sorted alphabetically.
1022 Module names are optionally converted to uppercase.
1023 Trailing comments after USE statements are preserved.
1024
1025 Parameters
1026 ----------
1027 upper : bool, optional
1028 If True, convert module names to uppercase. Default is True.
1029
1030 Returns
1031 -------
1032 self
1033 Returns self for method chaining.
1034
1035 Examples
1036 --------
1037 >>> pft = PYFT('input.F90')
1038 >>> pft.formatModuleUse()
1039 >>> pft.formatModuleUse(upper=False)
1040
1041 Notes
1042 -----
1043 Before:
1044 USE modi_foo
1045 USE modd_bar
1046 USE mode_baz
1047
1048 After (upper=True):
1049 USE MODD_BAR
1050 USE MODE_BAZ
1051 USE MODI_FOO
1052 """
1053 SORTED_GROUPS = ('MODD', 'MODE', 'MODI', 'MODN')
1054
1055 for progUnit in self.findall('.//{*}program-unit'):
1056 children = list(progUnit)
1057 useGroups = []
1058 i = 0
1059 while i < len(children):
1060 child = children[i]
1061 if tag(child) == 'use-stmt':
1062 comments = []
1063 i += 1
1064 while i < len(children) and tag(children[i]) == 'C':
1065 comments.append(children[i])
1066 i += 1
1067 useGroups.append([child, comments])
1068 else:
1069 i += 1
1070
1071 if not useGroups:
1072 continue
1073
1074 def _getModuleName(stmt):
1075 n = stmt.find('.//{*}module-N/{*}N/{*}n')
1076 return n.text if n is not None and n.text is not None else ''
1077
1078 groups = {prefix: [] for prefix in SORTED_GROUPS}
1079 other = []
1080
1081 for stmt, comments in useGroups:
1082 name = _getModuleName(stmt).upper()
1083 categorized = False
1084 for prefix in SORTED_GROUPS:
1085 if name.startswith(prefix + '_'):
1086 groups[prefix].append([stmt, comments])
1087 categorized = True
1088 break
1089 if not categorized:
1090 other.append([stmt, comments])
1091
1092 for prefix in SORTED_GROUPS:
1093 groups[prefix].sort(key=lambda g: _getModuleName(g[0]).upper())
1094 other.sort(key=lambda g: _getModuleName(g[0]).upper())
1095
1096 def _addSep(ordered):
1097 prev_stmt, prev_comments = ordered[-1]
1098 if prev_comments:
1099 prev_comments[-1].tail = (prev_comments[-1].tail or '').rstrip('\n') + '\n!\n'
1100 else:
1101 prev_stmt.tail = (prev_stmt.tail or '').rstrip('\n') + '\n!\n'
1102
1103 ordered = []
1104 for prefix in SORTED_GROUPS:
1105 if groups[prefix]:
1106 if ordered:
1107 _addSep(ordered)
1108 ordered.extend(groups[prefix])
1109 if other:
1110 if ordered:
1111 _addSep(ordered)
1112 ordered.extend(other)
1113
1114 firstIdx = None
1115 for i, child in enumerate(progUnit):
1116 if tag(child) == 'use-stmt':
1117 firstIdx = i
1118 break
1119
1120 if firstIdx is not None:
1121 for stmt, comments in useGroups:
1122 progUnit.remove(stmt)
1123 for c in comments:
1124 progUnit.remove(c)
1125 idx = firstIdx
1126 for stmt, comments in ordered:
1127 progUnit.insert(idx, stmt)
1128 idx += 1
1129 for c in comments:
1130 progUnit.insert(idx, c)
1131 idx += 1
1132
1133 if upper:
1134 for stmt, _ in ordered:
1135 modN = stmt.find('.//{*}module-N')
1136 modNNs = set(modN.findall('.//{*}n')) if modN is not None else set()
1137 for n in stmt.findall('.//{*}n'):
1138 if n not in modNNs and n.text:
1139 n.text = n.text.upper()
1140
1141 return self
1142
1143 @debugDecor
1144 def checkLineLength(self, maxLength=132, mustRaise=False):
1145 """
1146 Check that no line exceeds a maximum length.
1147
1148 Issue a logging.warning for each line longer than maxLength characters.
1149 If mustRaise is True, issue a logging.error instead and raise an error.
1150
1151 All lines are checked (code, comments, directives...) and the length is
1152 computed in characters, trailing spaces included. Because the line length
1153 is a property of the file, the whole file is always checked, even if the
1154 method is called on a sub-scope; line numbers are those of the file.
1155
1156 Parameters
1157 ----------
1158 maxLength : int, optional
1159 Maximum allowed line length in characters. Default is 132
1160 (limit of the FORTRAN free source form).
1161 mustRaise : bool, optional
1162 If True, issue a logging.error instead of a logging.warning
1163 and raise a PYFTError. Default is False.
1164
1165 Returns
1166 -------
1167 bool
1168 True if no line exceeds maxLength.
1169
1170 Raises
1171 ------
1172 PYFTError
1173 If mustRaise is True and at least one line exceeds maxLength.
1174
1175 Examples
1176 --------
1177 >>> pft = PYFT('input.F90')
1178 >>> pft.checkLineLength() # Warn for lines longer than 132 characters
1179 >>> pft.checkLineLength(maxLength=100, mustRaise=True) # Raise for lines > 100
1180 """
1181 ok = True
1182 log = logging.error if mustRaise else logging.warning
1183 for iline, line in enumerate(tofortran(self.mainScope).split('\n'), start=1):
1184 if len(line) > maxLength:
1185 log(("The line {} has {} characters (maximum is {}), in file '{}'"
1186 ).format(iline, len(line), maxLength, self.getFileName()))
1187 ok = False
1188 if not ok and mustRaise:
1189 raise PYFTError(("There are lines longer than {} characters in file '{}'"
1190 ).format(maxLength, self.getFileName()))
1191 return ok
1192
1193 @debugDecor
1194 @updateVarList
1195 def splitLongLines(self, maxLength=132):
1196 """
1197 Split the lines longer than a maximum length.
1198
1199 The transformation is done on the XML tree:
1200
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
1212 modified;
1213 - trailing blanks are removed from the lines that are too long only
1214 because of them.
1215
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
1219 logging.warning.
1220
1221 Parameters
1222 ----------
1223 maxLength : int, optional
1224 Maximum allowed line length in characters. Default is 132
1225 (limit of the FORTRAN free source form).
1226
1227 Returns
1228 -------
1229 bool
1230 True if, after the transformation, no line exceeds maxLength.
1231
1232 Raises
1233 ------
1234 PYFTError
1235 If the file is written in fixed source form.
1236
1237 Examples
1238 --------
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
1242 """
1243 # pylint: disable=protected-access
1244 root = self.mainScope._xml
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()))
1248
1249 def dec(text):
1250 """
1251 fxtran stores each byte of a UTF-8 character as a separate character
1252 :return: (decoded text, True if decoding was done)
1253 """
1254 try:
1255 decoded = text.encode('latin-1').decode('UTF-8')
1256 return decoded, decoded != text
1257 except (UnicodeEncodeError, UnicodeDecodeError):
1258 return text, False
1259
1260 def enc(text, decoded):
1261 """Inverse of dec"""
1262 return text.encode('UTF-8').decode('latin-1') if decoded else text
1263
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()}
1266 forbiddenCache = {}
1267
1268 def getParent(node):
1269 return parentOf.get(id(node))
1270
1271 def getScope(node):
1272 while id(node) not in scopeOf:
1273 node = parentOf[id(node)]
1274 return scopeOf[id(node)]
1275
1276 def isForbidden(node):
1277 """
1278 :param node: xml node containing a text
1279 :return: True if no continuation can be inserted in this node
1280 """
1281 chain = []
1282 result = False
1283 while node is not None:
1284 if id(node) in forbiddenCache:
1285 result = forbiddenCache[id(node)]
1286 break
1287 chain.append(node)
1288 if tag(node) in ('C', 'S', 'cpp', 'cnt', 'l', 'label') or \
1289 self.isArrayIndexSelection(node, getParent, getScope):
1290 result = True
1291 break
1292 node = getParent(node)
1293 for item in chain:
1294 forbiddenCache[id(item)] = result
1295 return result
1296
1297 # List of the pieces of text in document order. Each piece is a list:
1298 # [node, 'text' or 'tail', decoded text, True if decoding was done]
1299 pieces = []
1300
1301 def walk(node):
1302 pieces.append([node, 'text', *dec(node.text or '')])
1303 for child in node:
1304 walk(child)
1305 pieces.append([child, 'tail', *dec(child.tail or '')])
1306 walk(root)
1307
1308 def setText(ipiece, text):
1309 piece = pieces[ipiece]
1310 piece[2] = text
1311 if piece[1] == 'text':
1312 piece[0].text = enc(text, piece[3])
1313 else:
1314 piece[0].tail = enc(text, piece[3])
1315
1316 def insertNodes(ipiece, nodes, newPieces):
1317 """
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
1320 """
1321 node, kind = pieces[ipiece][:2]
1322 if kind == 'text':
1323 parent, index = node, 0
1324 else:
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
1331
1332 def getLine(ipiece, offset):
1333 """
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)
1340 """
1341 line = ''
1342 linePieces = []
1343 while ipiece < len(pieces):
1344 text = pieces[ipiece][2]
1345 end = text.find('\n', offset)
1346 if end == -1:
1347 linePieces.append((ipiece, len(line), offset, len(text)))
1348 line += text[offset:]
1349 ipiece, offset = ipiece + 1, 0
1350 else:
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
1355
1356 def isDirective(comment):
1357 return re.match(r'!(\$|dir\$|dec\$)', comment, re.IGNORECASE) is not None
1358
1359 ok = True
1360 iline = 0
1361 lineStart = (0, 0) # (index of piece, offset in piece) of the current line
1362 while lineStart[0] is not None:
1363 line, linePieces, *nextLine = getLine(*lineStart)
1364 if len(line) <= maxLength:
1365 lineStart = tuple(nextLine)
1366 iline += 1
1367 continue
1368 indent = len(line) - len(line.lstrip(' '))
1369
1370 # Comment on the line
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(' '))
1376
1377 modified = False
1378 if codeLength > maxLength:
1379 # The code must be split, we look for the best candidate
1380 candidates = [] # list of (column, index of piece, offset in piece)
1381 for ipiece, column, segStart, segEnd in linePieces:
1382 if column > codeEnd:
1383 break
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':
1388 # Before an operator
1389 candidates.append((column, ipiece - 1, len(pieces[ipiece - 1][2])))
1390 else:
1391 # After '=', in the tail of the 'a' node
1392 candidates.append((column + len(text), ipiece + 1, 0))
1393 elif not isForbidden(node if kind == 'text' else parentOf[id(node)]):
1394 # After a comma or after '::'
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:
1407 contIndent = 0
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]])
1416 modified = True
1417 elif comment is not None and not isDirective(pieces[comment[0]][2]):
1418 # The code part is short enough, the comment must be modified
1419 icomment, column = comment
1420 text, decoded = pieces[icomment][2:4]
1421 prefix = re.match(r'!+ *', text).group(0)
1422 width = maxLength - column
1423 # Position where to split the comment (last space before the limit)
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:
1427 # Only blanks or a decoration (e.g. '!!!!!' or '-----') beyond the limit:
1428 # the comment is truncated
1429 setText(icomment, text[:width].rstrip(' '))
1430 modified = True
1431 elif codeLength > 0 and (width < len(prefix) + 20 or cut == -1):
1432 # Trailing comment without enough room: we move it on its own line
1433 # Last piece ending at the comment position (comment is not at column 0)
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 +
1439 text[offset:])
1440 modified = True
1441 else:
1442 if cut == -1:
1443 # No space before the limit, words are not cut: we split at the
1444 # first space after the limit (the line remains too long)
1445 cut = text.find(' ', max(width, len(prefix)))
1446 rest = text[cut:].lstrip(' ') if cut != -1 else ''
1447 if rest != '':
1448 # New comment line aligned with the comment if there is enough room
1449 # (for at least 20 characters and the first word), otherwise indented
1450 # as the line
1451 room = len(prefix) + max(20, len(rest.split(' ')[0]))
1452 newColumn = column if column + room <= maxLength else indent
1453 # The comment node has no child, its tail is the next piece
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)
1459 # Insertion after the comment node (using its 'tail' piece)
1460 insertNodes(icomment + 1, [newComment],
1461 [[newComment, 'text', prefix + rest, decoded],
1462 [newComment, 'tail', tail, pieces[icomment + 1][3]]])
1463 modified = True
1464 elif len(line.rstrip(' ')) <= maxLength:
1465 # Only trailing blanks
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:])
1472 modified = True
1473
1474 if not modified:
1475 logging.warning("The line %i (%i characters) cannot be split, in file '%s'",
1476 iline + 1, len(line), self.getFileName())
1477 ok = False
1478 lineStart = tuple(nextLine)
1479 iline += 1
1480 return ok
updateContinuation(self, nodeToUpdate=None, align=True, removeALL=False, addBegin=True, removeBegin=False)
Definition cosmetics.py:283
checkLineLength(self, maxLength=132, mustRaise=False)
removeComments(self, exclDirectives=None, pattern=None)
Definition cosmetics.py:223
formatModuleUse(self, upper=True)
updateSpaces(self, beforeOp=1, afterOp=1, inOperator=True, beforeComma=0, afterComma=1, beforeParenthesis=0, afterParenthesis=0, beforeAffectation=1, afterAffectation=1, inAffectation=True, beforeRangeDelim=0, afterRangeDelim=0, beforeUseDelim=0, afterUseDelim=1, beforeDeclDelim=1, afterDeclDelim=1, inDeclDelim=True, afterTypeDecl=1, beforeEqDo=0, afterEqDo=0, beforeEqCall=0, afterEqCall=0, beforeEqInit=0, afterEqInit=0, beforeEndcnt=1, afterBegincnt=1, afterIfwherecase=1, beforeThen=1, beforeIfaction=1, afterProgunit=1, endOfLine=True, afterName=0, inName=True, beforeCmdsep=0, afterCmdsep=1, adjacentKeywords=__NO_VALUE__, afterKeywords=__NO_VALUE__)
Definition cosmetics.py:502
splitLongLines(self, maxLength=132)
indent(self, nodeToUpdate=None, indentProgramunit=0, indentBranch=2, exclDirectives=None)
Definition cosmetics.py:78
changeIfStatementsInIfConstructs(self, singleItem=None)
Definition cosmetics.py:919