PyForTool
Python-fortran-tool
Loading...
Searching...
No Matches
scripting.py
1"""
2This module contains functions usefull to build scripts around the pyfortool library
3"""
4
5import sys
6from multiprocessing import cpu_count, Pool
7from multiprocessing.managers import BaseManager
8import re
9import shlex
10import os
11import argparse
12import logging
13import traceback
14
15from pyfortool.pyfortool import PYFT
16from pyfortool.tree import Tree
17from pyfortool.util import isint, PYFTError
18from pyfortool import __version__
19
20
21def task(filename):
22 """
23 Function to use on each file
24 :param clsPYFT: PYFT class to use
25 :param filename: file name
26 """
27 global PYFT
28 global allFileArgs
29 allArgs, orderedOptions = allFileArgs[filename]
30 try:
31 # Opening and reading of the FORTRAN file
32 with PYFT(filename, filename,
33 parserOptions=getParserOptions(allArgs), verbosity=allArgs.logLevel,
34 wrapH=allArgs.wrapH,
35 enableCache=allArgs.enableCache) as pft:
36
37 # apply the transformation in the order they were specified
38 for arg in orderedOptions:
39 logging.debug('Applying %s on %s', arg, filename)
40 applyTransfo(pft, arg, allArgs,
41 filename if filename == allArgs.plotCentralFile else None)
42 logging.debug(' -> Done')
43
44 # Writing
45 if not allArgs.dryRun:
46 pft.write()
47
48 # Reporting
49 return (0, filename)
50
51 except Exception as exc: # pylint: disable=broad-except
52 logging.error("The following error has occurred in the file %s", filename)
53 traceback.print_exception(exc, file=sys.stdout)
54 sys.stdout.flush()
55 return (1, filename)
56
57
59 """
60 Core of the pyfortool_parallel.py command
61 """
62
63 class MyManager(BaseManager):
64 """
65 Custom manager to deal with Tree instances
66 """
67
68 MyManager.register('Tree', Tree)
69
70 def init(cls, afa):
71 """
72 Pool initializer
73 """
74 # After many, many attempts, it seems very difficult (if not impossible)
75 # to do without global variables
76 global PYFT # pylint: disable=global-statement
77 global allFileArgs # pylint: disable=global-statement
78 PYFT = cls
79 allFileArgs = afa
80
81 parser = argparse.ArgumentParser(description='Python FORTRAN tool', allow_abbrev=False,
82 epilog="The argument order matters.")
83
84 updateParser(parser, withInput=False, withOutput=False, withXml=False, withPlotCentralFile=True,
85 treeIsOptional=False, nbPar=True, restrictScope=False)
86 commonArgs, getFileArgs = getArgs(parser)
87
88 # Manager to share the Tree instance
89 with MyManager() as manager:
90 # Set-up the Tree instance
91 sharedTree = getDescTree(commonArgs, manager.Tree)
92
93 # Prepare PYFT to be used in parallel
94 PYFT.setParallel(sharedTree)
95
96 # Set-up the processes
97 allFileArgs = {file: getFileArgs(file) for file in sharedTree.getFiles()}
98 logging.info('Executing in parallel on %i files with a maximum of %i processes',
99 len(allFileArgs), commonArgs.nbPar)
100 with Pool(commonArgs.nbPar, initializer=init, initargs=(PYFT, allFileArgs)) as pool:
101 result = pool.map(task, sharedTree.getFiles())
102
103 # Writting the descTree object
104 sharedTree.toJson(commonArgs.descTree)
105
106 # General error
107 errors = [item[1] for item in result if item[0] != 0]
108 status = len(errors)
109 if status != 0:
110 logging.error('List of files with error:')
111 for error in errors:
112 logging.error(' - %s', error)
113 raise PYFTError(f"Errors have been reported in {status} file(s).")
114
115
116def main():
117 """
118 Core of the pyfortool.py command
119 """
120 parser = argparse.ArgumentParser(description='Python FORTRAN tool', allow_abbrev=False,
121 epilog="The argument order matters.")
122
123 updateParser(parser, withInput=True, withOutput=True, withXml=True, withPlotCentralFile=False,
124 treeIsOptional=True, nbPar=False, restrictScope=True)
125 args, orderedOptions = getArgs(parser)[1]()
126
127 parserOptions = getParserOptions(args)
128 descTree = getDescTree(args)
129
130 try:
131 # Opening and reading of the FORTRAN file
132 pft = PYFT(args.INPUT, args.OUTPUT, parserOptions=parserOptions,
133 verbosity=args.logLevel, wrapH=args.wrapH, tree=descTree,
134 enableCache=args.enableCache)
135 if args.restrictScope != '':
136 pft = pft.getScopeNode(args.restrictScope)
137
138 # apply the transformation in the order they were specified
139 for arg in orderedOptions:
140 logging.debug('Applying %s on %s', arg, args.INPUT)
141 applyTransfo(pft, arg, args, plotCentralFile=args.INPUT)
142 logging.debug(' -> Done')
143
144 # Writing
145 if descTree is not None:
146 descTree.toJson(args.descTree)
147 if args.xml is not None:
148 pft.mainScope.writeXML(args.xml)
149 if not args.dryRun:
150 pft.mainScope.write()
151
152 # Closing
153 pft.mainScope.close()
154
155 except: # noqa E722
156 # 'exept' everything and re-raise error systematically
157 logging.error("The following error has occurred in the file %s", args.INPUT)
158 raise
159
160
161ARG_UPDATE_CNT = ('--alignContinuation', '--addBeginContinuation',
162 '--removeBeginContinuation',
163 '--emoveALLContinuation')
164
165
166def getArgs(parser):
167 """
168 Parse arguments and interpret the --optsByEnv option
169 :param parser: argparse parser
170 :return: a tuple with
171 - an argparse namespace containing common arguments (not using the --optsEnv option)
172 - a function taking a filename as input and returning
173 - an argparse namespace with the common arguments and the ones added by
174 interpreting the --optsEnv option
175 - an ordered list of arguments
176 """
177 args = parser.parse_args()
178
179 def getFileArgs(filename=args.INPUT if hasattr(args, 'INPUT') else None):
180 """
181 :param filename: name of source code file
182 :return: argparse namespace to use with this file and
183 a list given the order in which the arguments were provided
184 """
185 # Decode the --optsByEnv option
186 arguments = sys.argv[1:]
187 if args.optsByEnv is not None:
188 extra = ''
189 for line in [] if args.optsByEnv is None else os.environ[args.optsByEnv].split('\n'):
190 if ':=:' in line:
191 if re.match(line.split(':=:')[0], filename):
192 extra = line.split(':=:')[1]
193 else:
194 extra = line
195 index = arguments.index('--optsByEnv')
196 arguments = arguments[:index] + shlex.split(extra) + arguments[index + 2:] # keep order
197
198 # Compute the ordered list
199 updateCnt = False
200 optList = []
201 for arg in arguments:
202 if arg.startswith('--') and arg not in optList:
203 if arg in ARG_UPDATE_CNT:
204 if not updateCnt:
205 updateCnt = True
206 optList.append(arg)
207 else:
208 optList.append(arg)
209
210 return parser.parse_args(arguments), optList
211
212 return args, getFileArgs
213
214
216 """
217 Get the options to use for the fxtran parser
218 :param args: arguments parsed by the argparse parser
219 """
220 if args.parserOption is None:
221 parserOptions = PYFT.DEFAULT_FXTRAN_OPTIONS.copy()
222 else:
223 parserOptions = [el for elements in args.parserOption for el in elements]
224 if args.addIncludes:
225 parserOptions = [opt for opt in parserOptions if opt not in ('-no-include', '-noinclude')]
226 return parserOptions
227
228
229def getDescTree(args, cls=Tree):
230 """
231 get the Tree object built with the parsed arguments
232 :param args: arguments parsed by the argparse parser
233 :param cls: class to use (usefull for manager)
234 :return: a Tree instance
235 """
236 parserOptions = getParserOptions(args)
237 if args.descTree:
238 descTree = cls(tree=args.tree, descTreeFile=args.descTree,
239 parserOptions=parserOptions,
240 wrapH=args.wrapH, verbosity=args.logLevel)
241 else:
242 descTree = None
243 return descTree
244
245
246def updateParser(parser, withInput, withOutput, withXml, withPlotCentralFile, treeIsOptional,
247 nbPar, restrictScope):
248 """
249 Updates an argparse parser with arguments common to all the different tools
250 :param parser: parser in which arguments are added
251 :param withOutput: do we need the INPUT argument
252 :param withOutput: do we need the OUTPUT argument
253 :param withXml: do we need to be able to define an XML output file
254 :param withPlotCentralFile: to add the --plotCentralFile argument
255 :param treeIsOptional: is the --tree argument optional?
256 :param nbPar: number of parallel processes
257 :param restrictScope: can we specify the scope path
258 """
259
260 # ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
261 # IMPORTANT NOTE
262 # Argument order matters but argparse is not able to give the order
263 # Therefore, arguments are processed twice. The first time by argparse to fully decode them.
264 # The a second pass is made direcly on sys.argv. This mechanism has two implications:
265 # allow_abbrev must be set to False in ArgumentParser
266 # only long argument options are allowed (begining with two dashes)
267 # ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
268 assert not parser.allow_abbrev, 'parser must be created with allow_abbrev=False'
269
270 parser.add_argument('--version', action='version',
271 version='%(prog)s {version}'.format(version=__version__))
272 parser.add_argument('--simplify', default=False, action='store_true',
273 help='After a deletion, recursively deletes the code ' +
274 'and variables that have become useless')
275 parser.add_argument('--logLevel', default='warning',
276 help='Provide logging level. Example --logLevel debug (default is warning)')
277 parser.add_argument('--enableCache', default=False, action='store_true',
278 help='Precompute parent of each xml node and store the result')
279 if nbPar:
280 parser.add_argument('--nbPar', default=cpu_count(), type=int,
281 help='Number of parallel processes, 0 to get as many processes ' +
282 'as the number of cores (default=0)')
283 parser.add_argument('--optsByEnv', default=None, type=str,
284 help='Name of the environment variable containing additional arguments ' +
285 'to use. These arguments are processed after all other arguments. ' +
286 'The variable can contain a multi-lines string. The ' +
287 'variable is read line by line and the last applicable line is ' +
288 'used. A line can take one of these two forms: ' +
289 '1) "FILE_DESCRIPTOR:=:OPTIONS" (where FILE_DESCRIPTOR is a ' +
290 'regular expression to test against the filename. If there ' +
291 'is a match, the OPTIONS can be used for the file) and ' +
292 '2) "OPTIONS" (if the line doesn\'t contain the FILE_DESCRIPTOR ' +
293 'part, it applies to all source code).')
294
295 if restrictScope:
296 parser.add_argument('--restrictScope', default='', type=str, metavar='SCOPEPATH',
297 help="Limit the action to this scope path (SUBROUTINE/FUNCTION/" +
298 "MODULE/TYPE). It is '/'-separated path with each element " +
299 "having the form 'module:<name of the module>', " +
300 "'sub:<name of the subroutine>', " +
301 "'func:<name of the function>' or 'type:<name of the type>'.")
302
303 # Inputs and outputs
304 updateParserInputsOutputs(parser, withInput, withOutput, withXml)
305
306 # fxtran
307 updateParserFxtran(parser)
308
309 # Variables
311
312 # Cosmetics
314
315 # Applications
317
318 # openACC
319 updateParserOpenACC(parser)
320
321 # Checks
322 updateParserChecks(parser)
323
324 # Statements
326
327 # Misc
328 updateParserMisc(parser)
329
330 # Tree
331 updateParserTree(parser, withPlotCentralFile, treeIsOptional)
332
333 # Preprocessot
335
336
337def updateParserInputsOutputs(parser, withInput, withOutput, withXml):
338 """
339 Updates an argparse parser with input/output arguments
340 :param parser: parser in which arguments are added
341 :param withOutput: do we need the INPUT argument
342 :param withOutput: do we need the OUTPUT argument
343 :param withXml: do we need to be able to define an XML output file
344 """
345 gInOut = parser.add_argument_group('Input and output')
346 if withInput:
347 gInOut.add_argument('INPUT', help='FORTRAN input file')
348 if withOutput:
349 gInOut.add_argument('OUTPUT', default=None, help='FORTRAN output file', nargs='?')
350 gInOut.add_argument('--renamefF', default=False, action='store_true',
351 help='Put file extension in upper case')
352 gInOut.add_argument('--renameFf', default=False, action='store_true',
353 help='Put file extension in lower case')
354 if withXml:
355 gInOut.add_argument('--xml', default=None, type=str,
356 help='Output file for xml')
357 gInOut.add_argument('--dryRun', default=False, action='store_true',
358 help='Dry run without writing the FORTRAN file (the xml ' +
359 'is still written')
360
361
363 """
364 Updates an argparse parser with fxtran arguments
365 """
366 gParser = parser.add_argument_group('fxtran parser relative options')
367 gParser.add_argument('--parserOption', nargs='*', action='append',
368 help='Option to pass to fxtran, defaults ' +
369 f'to {PYFT.DEFAULT_FXTRAN_OPTIONS}')
370 gParser.add_argument('--wrapH', default=False, action='store_true',
371 help='Wrap .h file content into a MODULE to enable the reading')
372
373
375 """
376 Updates an argparse parser with variables arguments
377 """
378 gVariables = parser.add_argument_group('Options to deal with variables')
379 gVariables.add_argument('--showVariables', default=False, action='store_true',
380 help='Show the declared variables')
381 gVariables.add_argument('--removeVariable', nargs=2, action='append',
382 metavar=('SCOPEPATH', 'VARNAME'),
383 help="Variable to remove from declaration. The first argument " +
384 "is the SUBROUTINE/FUNCTION/MODULE/TYPE where the variable " +
385 "is declared. It is '/'-separated path with each element having " +
386 "the form 'module:<name of the module>', " +
387 "'sub:<name of the subroutine>', " +
388 "'func:<name of the function>' or 'type:<name of the type>'. " +
389 "The second argument is the variable name")
390 gVariables.add_argument('--attachArraySpecToEntity', default=False, action='store_true',
391 help='Find all T-decl-stmt elements that have a child element ' +
392 'attribute with attribute-N=DIMENSION and move the attribute ' +
393 'into EN-N elements')
394 gVariables.add_argument('--addVariable', nargs=4, action='append',
395 metavar=('SCOPEPATH', 'VARNAME', 'DECLARATION', 'POSITION'),
396 help='Add a variable. First argument is the scope path (as for ' +
397 'the --removeVariable option. The second is the variable ' +
398 'name, the third is the declarative statement to insert, ' +
399 'the fourth is the position (python indexing) the new ' +
400 'variable will have in the calling statment of the ' +
401 'routine (non-integer value for a local variable).')
402 gVariables.add_argument('--addModuleVariable', nargs=3, action='append',
403 metavar=('SCOPEPATH', 'MODULENAME', 'VARNAME'),
404 help='Add a USE statement. The first argument is the scope path ' +
405 '(as for the --removeVariable option). The second is the module ' +
406 'name; the third is the variable name.')
407 gVariables.add_argument('--showUnusedVariables', default=False, action='store_true',
408 help='Show a list of unused variables.')
409 gVariables.add_argument('--removeUnusedLocalVariables',
410 help='Remove unused local variables, excluding some variables (comma-' +
411 'separated list or NONE to exclude nothing).')
412 gVariables.add_argument('--removePHYEXUnusedLocalVariables',
413 help='Remove unused local variables, excluding some variables (comma-' +
414 'separated list or NONE to exclude nothing). This option takes ' +
415 'into account the mnh_expand directives to prevent from ' +
416 'removing useful variables.')
417 gVariables.add_argument('--addExplicitArrayBounds', action='store_true',
418 help='Adds explicit bounds to arrays that already have parentheses.')
419 gVariables.add_argument('--addArrayParentheses', action='store_true',
420 help='Adds parentheses to arrays (A => A(:))')
421 gVariables.add_argument('--modifyAutomaticArrays', metavar="DECL#START#END",
422 help='Transform all automatic arrays declaration using the templates.' +
423 ' The DECL part of the template will replace the declaration ' +
424 'statement, the START part will be inserted as the first ' +
425 'executable statement while the END part will be inserted as ' +
426 'the last executable statement. Each part ' +
427 'of the template can use the following place holders: ' +
428 '"{doubledotshape}", "{shape}", "{lowUpList}", "{name}" and ' +
429 '"{type}" which are, respectively modified into ' +
430 '":, :, :", "I, I:J, 0:I", "1, I, I, J, 0, I", "A", "REAL" ' +
431 'if the original declaration statement ' +
432 'was "A(I, I:J, 0:I)". For example, the template ' +
433 '"{type}, DIMENSION({doubledotshape}), ALLOCATABLE :: ' +
434 '{name}#ALLOCATE({name}({shape}))#DEALLOCATE({name})"' +
435 'will replace automatic arrays by allocatables.')
436 gVariables.add_argument('--replaceAutomaticWithAllocatable', action='store_true',
437 help='Replace all automatic arrays with allocatable arrays.')
438 gVariables.add_argument('--addArgInTree', default=None, action='append', nargs=3,
439 metavar=('VARNAME', 'DECLARATION', 'POSITION'),
440 help='Add an argument variable. The first argument is the variable ' +
441 'name, the second one is the declarative statement to insert, ' +
442 'the third one is the position (python indexing) the new ' +
443 'variable will have in the calling statement of the ' +
444 'routine. Needs the --stopScopes argument')
445
446
448 """
449 Updates an argparse parser with cosmetics arguments
450 """
451 gCosmetics = parser.add_argument_group('Cosmetics options')
452 gCosmetics.add_argument('--upperCase', default=False, action='store_true',
453 help='Put FORTRAN code in upper case letters')
454 gCosmetics.add_argument('--lowerCase', default=False, action='store_true',
455 help='Put FORTRAN code in lower case letters')
456 gCosmetics.add_argument('--changeIfStatementsInIfConstructs', default=False,
457 action='store_true',
458 help='Find all if-statement and convert it to if-then-statement')
459 gCosmetics.add_argument('--indent', default=False, action='store_true',
460 help='Correct indentation')
461 gCosmetics.add_argument('--removeIndent', default=False, action='store_true',
462 help='Remove indentation')
463 gCosmetics.add_argument('--removeEmptyLines', default=False, action='store_true',
464 help='Remove empty lines')
465 gCosmetics.add_argument('--removeComments', default=False, action='store_true',
466 help='Remove comments')
467 gCosmetics.add_argument('--updateSpaces', default=False, action='store_true',
468 help='Updates spaces around operators, commas, parenthesis and ' +
469 'at the end of line')
470 gCosmetics.add_argument('--alignContinuation', default=False, action='store_true',
471 help='Align the beginings of continued lines')
472 gCosmetics.add_argument('--addBeginContinuation', default=False, action='store_true',
473 help='Add missing continuation characters (\'&\') at the ' +
474 'begining of lines')
475 gCosmetics.add_argument('--removeBeginContinuation', default=False, action='store_true',
476 help='Remove continuation characters (\'&\') at the begining of lines')
477 gCosmetics.add_argument('--removeALLContinuation', default=False, action='store_true',
478 help='Remove all continuation characters(\'&\')')
479 gCosmetics.add_argument('--prettify', default=False, action='store_true',
480 help='Prettify the source code (indentation, spaces...)')
481 gCosmetics.add_argument('--minify', default=False, action='store_true',
482 help='Simplify the source code (indentation, spaces...)')
483 gCosmetics.add_argument('--removeEmptyCONTAINS', default=False, action='store_true',
484 help='Remove useless CONTAINS statements')
485
486
488 """
489 Updates an argparse parser with applications arguments
490 """
491 gApplications = parser.add_argument_group('Options to apply upper level transformation')
492 gApplications.add_argument('--deleteDrHook', default=False, action='store_true',
493 help='Delete DR HOOK use')
494 gApplications.add_argument('--addDrHook', default=False, action='store_true',
495 help='Add DR HOOK')
496 gApplications.add_argument('--deleteBudgetDDH', default=False, action='store_true',
497 help='Delete Budget/DDH use')
498 gApplications.add_argument('--deleteRoutineCallsMesoNHGPU', default=False, action='store_true',
499 help='Delete parts of the code not compatible with MesoNH-OpenACC' +
500 'such as OCND2 blocks')
501 gApplications.add_argument('--splitModuleRoutineFile', default=False, action='store_true',
502 help='Split a file')
503 gApplications.add_argument('--deleteNonColumnCallsPHYEX', default=False, action='store_true',
504 help='Delete call to PHYEX routines that needs information on ' +
505 'horizontal points (multiple column dependency')
506 gApplications.add_argument('--removeIJDim', default=False, action='store_true',
507 help='Remove I and J dimensions (1, KLON). ' +
508 'Needs the --stopScopes argument.')
509 gApplications.add_argument('--expandAllArraysPHYEX', default=False, action='store_true',
510 help='Expand all array syntax (computing and where block) ' +
511 'using PHYEX conventions')
512 gApplications.add_argument('--expandAllArraysPHYEXConcurrent', default=False,
513 action='store_true',
514 help='Expand all array syntax with DO CONCURRENT loops ' +
515 '(computing and where block) using PHYEX conventions')
516 gApplications.add_argument('--expandAllArrays', default=False, action='store_true',
517 help='Expand all array syntax (computing and where block) ' +
518 'using mnh directives if present')
519 gApplications.add_argument('--expandAllArraysConcurrent', default=False, action='store_true',
520 help='Expand all array syntax with DO CONCURRENT loops ' +
521 '(computing and where block) using mnh directives if present')
522 gApplications.add_argument('--inlineContainedSubroutinesPHYEX', default=False,
523 action='store_true',
524 help='Inline containted subroutines in main routine, using ' +
525 'PHYEX conventions')
526 gApplications.add_argument('--addStack', metavar='MODEL', type=str,
527 help='Add local arrays to the stack. The argument is the ' +
528 'the model name in which stack must be added ("AROME" ' +
529 'or "MESONH"). Needs the --stopScopes argument for AROME.')
530 gApplications.add_argument('--addIncludes', default=False, action='store_true',
531 help='Add .h includes in the file and remove the INCLUDE statement')
532 gApplications.add_argument('--addSubmodulePHYEX', default=False, action='store_true',
533 help='Add SUBMODULE and INTERFACE of subroutines in PHYEX')
534 gApplications.add_argument('--mnhExpand', default=False, action='store_true',
535 help='Apply the mnh_expand directives with DO loops')
536 gApplications.add_argument('--mnhExpandConcurrent', default=False, action='store_true',
537 help='Apply the mnh_expand directives with DO CONCURRENT loops')
538 gApplications.add_argument('--addMPPDB_CHECKS', default=False, action='store_true',
539 help='Add MPPDB_CHEKS bit-repro checking routines of MesoNH for ' +
540 'all in and inout arrays in subroutines')
541 gApplications.add_argument('--addPrints', default=False, action='store_true',
542 help='Add Prints of min/maxval and shape of all in, out, inout ' +
543 'arguments of all scopes')
544 gApplications.add_argument('--shumanFUNCtoCALL', default=False, action='store_true',
545 help='Transform shuman functions to call statements')
546 gApplications.add_argument('--mathFunctoBRFunc', default=False, action='store_true',
547 help='Convert intrinsic math functions **, LOG, ATAN, **2, **3, ' +
548 '**4, EXP, COS, SIN, ATAN2 into a self defined function BR_ ' +
549 'for MesoNH bit-repro.')
550 gApplications.add_argument('--convertTypesInCompute', default=False, action='store_true',
551 help='Use single variable instead of variable contained in ' +
552 'structure in compute statement for optimization issue ')
553 gApplications.add_argument('--buildModi', default=False, action='store_true',
554 help='Builds the corresponding modi_ file')
555 gApplications.add_argument('--removeExtraDOinMnhDoConcurrent', default=False,
556 action='store_true',
557 help='Remove DO and ENDDO instructions inside !$mnh_do_concurrent')
558
559
561 """
562 Updates an argparse parser with openACC arguments
563 """
564 gOpenACC = parser.add_argument_group('OpenACC')
565 gOpenACC.add_argument('--addACCData', default=False, action='store_true',
566 help='Add !$acc data present and !$acc end data directives')
567 gOpenACC.add_argument('--addACCRoutineSeq', default=False, action='store_true',
568 help='Add "!$acc routine seq" to routines under stopScopes')
569 gOpenACC.add_argument('--craybyPassDOCONCURRENT', default=False, action='store_true',
570 help='remove acc loop independant collapse for BR_ fonctions and ' +
571 'mnh_undef(OPENACC) macro' +
572 ' use DO CONCURRENT with mnh_undef(LOOP)')
573 gOpenACC.add_argument('--removeACC', default=False, action='store_true',
574 help='remove all ACC directives')
575 gOpenACC.add_argument('--removebyPassDOCONCURRENT', default=False, action='store_true',
576 help='remove macro !$mnh_(un)def(OPENACC) and !$mnh_(un)def(LOOP) ' +
577 'directives')
578 gOpenACC.add_argument('--buildACCTypeHelpers', default=False, action='store_true',
579 help='build module files containing helpers to copy user ' +
580 'type structures')
581 gOpenACC.add_argument('--allocatetoHIP', default=False, action='store_true',
582 help='convert (DE)ALLOCATE to (DE)ALLOCATE_HIP on variables only sent ' +
583 'to the GPU via acc enter data copyin/create (for GPU AMD MI250X)')
584
585
587 """
588 Updates an argparse parser with checks arguments
589 """
590
591 gChecks = parser.add_argument_group('Check options')
592 gChecks.add_argument('--checkIMPLICIT', choices={'Warn', 'Err'}, default=None,
593 help='Send a warning or raise an error if the "IMPLICIT NONE" ' +
594 'is missing')
595 gChecks.add_argument('--checkINTENT', choices={'Warn', 'Err'}, default=None,
596 help='Send a warning or raise an error if the "INTENT" ' +
597 'attribute is missing for a dummy argument')
598 gChecks.add_argument('--checkOpInCall', choices={'Warn', 'Err'}, default=None,
599 help='Send a warning or raise an error if a call argument is an '
600 'operation.')
601 gChecks.add_argument('--checkUnusedLocalVar', choices={'Warn', 'Err'}, default=None,
602 help='Send a warning or raise an error if some local '
603 'variables are unused.')
604 gChecks.add_argument('--checkPHYEXUnusedLocalVar', choices={'Warn', 'Err'}, default=None,
605 help='Send a warning or raise an error if some local '
606 'variables are unused (excluding variables needed '
607 'for mnh_expand directives).')
608 gChecks.add_argument('--checkEmptyParensInCall', choices={'Warn', 'Err'}, default=None,
609 help='Send a warning or raise an error if a call argument is an '
610 'array with empty parens.')
611
612
614 """
615 Updates an argparse parser with statements arguments
616 """
617
618 gStatement = parser.add_argument_group('Statements options')
619 gStatement.add_argument('--removeCall', action='append',
620 help="Call to remove from the source code. The argument " +
621 "is the subprogram name")
622 gStatement.add_argument('--removePrints', default=False, action='store_true',
623 help="Remove print statements from the source code.")
624 gStatement.add_argument('--inlineContainedSubroutines', default=False, action='store_true',
625 help='Inline containted subroutines in main routine')
626 gStatement.add_argument('--setFalseIfStmt', default=None,
627 help='Replace this value by .FALSE. in if statements')
628
629
631 """
632 Updates an argparse parser with misc arguments
633 """
634 gMisc = parser.add_argument_group('Miscellaneous')
635 gMisc.add_argument('--showScopes', default=False, action='store_true',
636 help='Show the different scopes found in the source code')
637 gMisc.add_argument('--empty', default=False, action='store_true',
638 help='Empty the different scopes')
639
640
641def updateParserTree(parser, withPlotCentralFile, treeIsOptional):
642 """
643 Updates an argparse parser with statements arguments
644 :param withPlotCentralFile: to add the --plotCentralFile argumen
645 :param treeIsOptional: is the --tree argument optional?
646 """
647 gTree = parser.add_argument_group('Tree')
648 gTree.add_argument('--tree', default=None, action='append', required=not treeIsOptional,
649 help='Directories where source code must be searched for')
650 gTree.add_argument('--descTree', default=None, required=not treeIsOptional,
651 help='File to write and/or read the description of the tree.')
652 if withPlotCentralFile:
653 gTree.add_argument('--plotCentralFile', default=None, type=str,
654 help='Central file of the plot')
655 gTree.add_argument('--plotCompilTree', default=None,
656 help='File name for compilation dependency graph (.dot or image extension)')
657 gTree.add_argument('--plotExecTree', default=None,
658 help='File name for execution dependency graph (.dot or image extension)')
659 gTree.add_argument('--plotMaxUpper', default=None, type=int,
660 help='Maximum number of upper elements in the plot tree')
661 gTree.add_argument('--plotMaxLower', default=None, type=int,
662 help='Maximum number of lower elements in the plot tree')
663 gTree.add_argument('--stopScopes', default=None, type=str,
664 help='#-separated list of scopes ' +
665 'where the recursive inclusion of an argument variable ' +
666 'must stop (needed for some transformations).')
667
668
670 """
671 Updates an argparse parser with statements arguments
672 """
673 gCpp = parser.add_argument_group('Preprocessor')
674 gCpp.add_argument('--applyCPPifdef', nargs='*', action='append',
675 help="This option is followed by the list of defined or undefined " +
676 "CPP keys. " +
677 "All #ifdef and #ifndef concerning these keys are evaluated. " +
678 "Undefined keys are preceded by a percentage sign.")
679
680
681def applyTransfo(pft, arg, args, plotCentralFile):
682 """
683 Apply transformation on a PYFT instance
684 :param pft: PYFT instance
685 :param arg: argument to deal with
686 :param args: parsed argparsed arguments
687 :param plotCentralFile: central file for plots
688 """
689 simplify = {'simplify': args.simplify}
690 parserOptions = getParserOptions(args)
691 stopScopes = args.stopScopes.split('#') if args.stopScopes is not None else None
692
693 # File name manipulations
694 applyTransfoFileName(pft, arg)
695
696 # Variables
697 applyTransfoVariables(pft, arg, args, simplify, parserOptions, stopScopes)
698
699 # Applications
700 applyTransfoApplications(pft, arg, args, simplify, parserOptions, stopScopes)
701
702 # OpenACC
703 applyTransfoOpenACC(pft, arg, args, stopScopes)
704
705 # Cosmetics
706 applyTransfoCosmetics(pft, arg, args)
707
708 # Checks
709 applyTransfoChecks(pft, arg, args)
710
711 # Statements
712 applyTransfoStatements(pft, arg, args, simplify)
713
714 # Misc
715 applyTransfoMisc(pft, arg, args, simplify)
716
717 # Tree
718 applyTransfoTree(pft, arg, args, plotCentralFile)
719
720 # Preprocessor
721 applyTransfoPreprocessor(pft, arg, args)
722
723
725 """
726 Apply file name transformations on a PYFT instance
727 :param pft: PYFT instance
728 :param arg: argument to deal with
729 :param args: parsed argparsed arguments
730 """
731
732 # File name manipulations
733 if arg == '--renamefF':
734 pft.renameUpper()
735 elif arg == '--renameFf':
736 pft.renameLower()
737
738
739def applyTransfoVariables(pft, arg, args, simplify, parserOptions, stopScopes):
740 """
741 Apply variables transformations on a PYFT instance
742 :param pft: PYFT instance
743 :param arg: argument to deal with
744 :param args: parsed argparsed arguments
745 :param simplify: kwargs to simplify
746 :param parserOptions: fxtran parser options
747 :param stopScopes: upper limit in call tree for some transformations
748 """
749 if arg == '--showVariables':
750 pft.varList.showVarList()
751 elif arg == '--attachArraySpecToEntity':
752 pft.attachArraySpecToEntity()
753 elif arg == '--removeVariable':
754 pft.removeVar(args.removeVariable, **simplify)
755 elif arg == '--addVariable':
756 pft.addVar([[v[0], v[1], v[2], (int(v[3]) if isint(v[3]) else None)]
757 for v in args.addVariable])
758 elif arg == '--addModuleVariable':
759 pft.addModuleVar([[v[0], v[1], v[2]] for v in args.addModuleVariable])
760 elif arg == '--showUnusedVariables':
761 pft.showUnusedVar()
762 elif arg == '--removeUnusedLocalVariables':
763 pft.removeUnusedLocalVar(
764 [item.strip() for item in args.removeUnusedLocalVariables.split(',')]
765 if args.removeUnusedLocalVariables != 'NONE' else None, **simplify)
766 elif arg == '--removePHYEXUnusedLocalVariables':
767 pft.removePHYEXUnusedLocalVar(
768 [item.strip() for item in args.removePHYEXUnusedLocalVariables.split(',')]
769 if args.removePHYEXUnusedLocalVariables != 'NONE' else None, **simplify)
770 elif arg == '--addExplicitArrayBounds':
771 pft.addExplicitArrayBounds()
772 elif arg == '--addArrayParentheses':
773 pft.addArrayParentheses()
774 elif arg == '--modifyAutomaticArrays':
775 pft.modifyAutomaticArrays(*(args.modifyAutomaticArrays.split('#')))
776 elif arg == '--replaceAutomaticWithAllocatable':
777 pft.modifyAutomaticArrays(
778 "{type}, DIMENSION({doubledotshape}), ALLOCATABLE :: {name}",
779 "ALLOCATE({name}({shape}))", "DEALLOCATE({name})")
780 elif arg == '--addArgInTree':
781 for varName, declStmt, pos in args.addArgInTree:
782 pft.addArgInTree(varName, declStmt, int(pos), stopScopes,
783 parserOptions=parserOptions,
784 wrapH=args.wrapH)
785
786
787def applyTransfoApplications(pft, arg, args, simplify, parserOptions, stopScopes):
788 """
789 Apply applications transformations on a PYFT instance
790 :param pft: PYFT instance
791 :param arg: argument to deal with
792 :param args: parsed argparsed arguments
793 :param simplify: kwargs to simplify
794 :param parserOptions: fxtran parser options
795 :param stopScopes: upper limit in call tree for some transformations
796 """
797 if arg == '--addStack':
798 pft.addStack(args.addStack, stopScopes,
799 parserOptions=parserOptions,
800 wrapH=args.wrapH)
801 elif arg == '--deleteDrHook':
802 pft.deleteDrHook(**simplify)
803 elif arg == '--addDrHook':
804 pft.addDrHook()
805 elif arg == '--deleteBudgetDDH':
806 pft.deleteBudgetDDH(**simplify)
807 elif arg == '--deleteRoutineCallsMesoNHGPU':
808 pft.deleteRoutineCallsMesoNHGPU(**simplify)
809 elif arg == '--deleteNonColumnCallsPHYEX':
810 pft.deleteNonColumnCallsPHYEX(**simplify)
811 elif arg == '--addMPPDB_CHECKS':
812 pft.addMPPDB_CHECKS()
813 elif arg == '--addPrints':
814 pft.addMPPDB_CHECKS(printsMode=True)
815 elif arg == '--addSubmodulePHYEX':
816 pft.addSubmodulePHYEX()
817 # mnhExpand must be before inlineContainedSubroutines as inlineContainedSubroutines
818 # can change variable names used by mnh_expand directives
819 assert not (args.mnhExpand and args.mnhExpandConcurrent), \
820 "Only one of --mnhExpand and --mnhExpandConcurrent"
821 if arg == '--mnhExpand':
822 pft.removeArraySyntax(everywhere=False, addAccIndependentCollapse=False)
823 elif arg == '--mnhExpandConcurrent':
824 pft.removeArraySyntax(concurrent=True, everywhere=False)
825 elif arg == '--inlineContainedSubroutines':
826 pft.inlineContainedSubroutines(**simplify)
827 elif arg == '--inlineContainedSubroutinesPHYEX':
828 pft.inlineContainedSubroutinesPHYEX(**simplify)
829 elif arg == '--expandAllArrays':
830 pft.removeArraySyntax()
831 elif arg == '--expandAllArraysConcurrent':
832 pft.removeArraySyntax(concurrent=True)
833 elif arg == '--expandAllArraysPHYEX':
834 pft.expandAllArraysPHYEX()
835 elif arg == '--expandAllArraysPHYEXConcurrent':
836 pft.expandAllArraysPHYEX(concurrent=True)
837 elif arg == '--removeIJDim':
838 pft.removeIJDim(stopScopes,
839 parserOptions=parserOptions,
840 wrapH=args.wrapH, **simplify)
841 elif arg == '--shumanFUNCtoCALL':
842 pft.shumanFUNCtoCALL()
843 elif arg == '--buildACCTypeHelpers':
844 pft.buildACCTypeHelpers()
845 elif arg == '--mathFunctoBRFunc':
846 pft.mathFunctoBRFunc()
847 elif arg == '--convertTypesInCompute':
848 pft.convertTypesInCompute()
849 elif arg == '--buildModi':
850 pft.buildModi()
851 elif arg == '--splitModuleRoutineFile':
852 pft.splitModuleRoutineFile()
853 elif arg == '--removeExtraDOinMnhDoConcurrent':
854 pft.removeExtraDOinMnhDoConcurrent()
855
856
857def applyTransfoOpenACC(pft, arg, args, stopScopes): # pylint: disable=unused-argument
858 """
859 Apply openACC transformations on a PYFT instance
860 :param pft: PYFT instance
861 :param arg: argument to deal with
862 :param args: parsed argparsed arguments
863 :param stopScopes: upper limit in call tree for some transformations
864 """
865 if arg == '--addACCData':
866 pft.addACCData()
867 elif arg == '--craybyPassDOCONCURRENT':
868 pft.craybyPassDOCONCURRENT()
869 elif arg == '--removebyPassDOCONCURRENT':
870 pft.removebyPassDOCONCURRENT()
871 elif arg == '--addACCRoutineSeq':
872 pft.addACCRoutineSeq(stopScopes)
873 elif arg == '--removeACC':
874 pft.removeACC()
875 elif arg == '--allocatetoHIP':
876 pft.allocatetoHIP()
877
878
879def applyTransfoCosmetics(pft, arg, args):
880 """
881 Apply cosmetics transformations on a PYFT instance
882 :param pft: PYFT instance
883 :param arg: argument to deal with
884 :param args: parsed argparsed arguments
885 """
886 if arg == '--upperCase':
887 pft.upperCase()
888 elif arg == '--lowerCase':
889 pft.lowerCase()
890 elif arg == '--changeIfStatementsInIfConstructs':
891 pft.changeIfStatementsInIfConstructs()
892 elif arg == '--indent':
893 pft.indent()
894 elif arg == '--removeIndent':
895 pft.indent(indentProgramunit=0, indentBranch=0)
896 elif arg == '--removeEmptyLines':
897 pft.removeEmptyLines()
898 elif arg == '--removeComments':
899 pft.removeComments()
900 elif arg == '--updateSpaces':
901 pft.updateSpaces()
902 elif arg in ARG_UPDATE_CNT:
903 pft.updateContinuation(align=args.alignContinuation,
904 addBegin=args.addBeginContinuation,
905 removeBegin=args.removeBeginContinuation,
906 removeALL=args.removeALLContinuation)
907 elif arg == '--prettify':
908 pft.indent()
909 pft.upperCase()
910 pft.removeEmptyLines()
911 pft.updateSpaces()
912 pft.updateContinuation()
913 elif arg == '--minify':
914 pft.indent(indentProgramunit=0, indentBranch=0)
915 pft.upperCase()
916 pft.removeComments()
917 pft.removeEmptyLines()
918 pft.updateSpaces()
919 pft.updateContinuation(align=False, removeALL=True, addBegin=False)
920 elif arg == '--removeEmptyCONTAINS':
921 pft.removeEmptyCONTAINS()
922
923
924def applyTransfoChecks(pft, arg, args):
925 """
926 Apply checks transformations on a PYFT instance
927 :param pft: PYFT instance
928 :param arg: argument to deal with
929 :param args: parsed argparsed arguments
930 """
931 if arg == '--checkIMPLICIT':
932 pft.checkImplicitNone(args.checkIMPLICIT == 'Err')
933 elif arg == '--checkINTENT':
934 pft.checkIntent(args.checkINTENT == 'Err')
935 elif arg == '--checkOpInCall':
936 pft.checkOpInCall(args.checkOpInCall == 'Err')
937 elif arg == '--checkUnusedLocalVar':
938 pft.checkUnusedLocalVar(args.checkUnusedLocalVar == 'Err')
939 elif arg == '--checkPHYEXUnusedLocalVar':
940 pft.checkPHYEXUnusedLocalVar(args.checkPHYEXUnusedLocalVar == 'Err')
941 elif arg == '--checkEmptyParensInCall':
942 pft.checkEmptyParensInCall(args.checkEmptyParensInCall == 'Err')
943
944
945def applyTransfoStatements(pft, arg, args, simplify):
946 """
947 Apply statements transformations on a PYFT instance
948 :param pft: PYFT instance
949 :param arg: argument to deal with
950 :param args: parsed argparsed arguments
951 :param simplify: kwargs to simplify
952 """
953 if arg == '--removeCall':
954 for rc in args.removeCall:
955 pft.removeCall(rc, **simplify)
956 elif arg == '--removePrints':
957 pft.removePrints(**simplify)
958 elif arg == '--setFalseIfStmt':
959 pft.setFalseIfStmt(args.setFalseIfStmt, **simplify)
960
961
962def applyTransfoMisc(pft, arg, args, simplify): # pylint: disable=unused-argument
963 """
964 Apply misc transformations on a PYFT instance
965 :param pft: PYFT instance
966 :param arg: argument to deal with
967 :param args: parsed argparsed arguments
968 :param simplify: kwargs to simplify
969 """
970 if arg == '--showScopes':
971 pft.showScopesList()
972 elif arg == '--empty':
973 pft.empty(**simplify)
974
975
976def applyTransfoTree(pft, arg, args, plotCentralFile):
977 """
978 Apply tree transformations on a PYFT instance
979 :param pft: PYFT instance
980 :param arg: argument to deal with
981 :param args: parsed argparsed arguments
982 :param plotCentralFile: central file for plots
983 """
984 if arg == '--plotCompilTree' and plotCentralFile is not None:
985 pft.tree.plotCompilTreeFromFile(plotCentralFile, args.plotCompilTree,
986 args.plotMaxUpper, args.plotMaxLower)
987 elif arg == '--plotExecTree' and plotCentralFile is not None:
988 pft.tree.plotExecTreeFromFile(plotCentralFile, args.plotExecTree,
989 args.plotMaxUpper, args.plotMaxLower)
990
991
992def applyTransfoPreprocessor(pft, arg, args):
993 """
994 Apply preprocessor transformations on a PYFT instance
995 :param pft: PYFT instance
996 :param arg: argument to deal with
997 :param args: parsed argparsed arguments
998 """
999 if arg == '--applyCPPifdef':
1000 pft.applyCPPifdef([k for aList in args.applyCPPifdef for k in aList])
applyTransfoApplications(pft, arg, args, simplify, parserOptions, stopScopes)
Definition scripting.py:787
updateParserVariables(parser)
Definition scripting.py:374
applyTransfoStatements(pft, arg, args, simplify)
Definition scripting.py:945
applyTransfoTree(pft, arg, args, plotCentralFile)
Definition scripting.py:976
applyTransfoPreprocessor(pft, arg, args)
Definition scripting.py:992
updateParserCosmetics(parser)
Definition scripting.py:447
applyTransfoVariables(pft, arg, args, simplify, parserOptions, stopScopes)
Definition scripting.py:739
updateParserInputsOutputs(parser, withInput, withOutput, withXml)
Definition scripting.py:337
updateParserApplications(parser)
Definition scripting.py:487
updateParserFxtran(parser)
Definition scripting.py:362
updateParserChecks(parser)
Definition scripting.py:586
updateParserOpenACC(parser)
Definition scripting.py:560
updateParserPreprocessor(parser)
Definition scripting.py:669
applyTransfoOpenACC(pft, arg, args, stopScopes)
Definition scripting.py:857
updateParserStatements(parser)
Definition scripting.py:613
applyTransfoChecks(pft, arg, args)
Definition scripting.py:924
applyTransfo(pft, arg, args, plotCentralFile)
Definition scripting.py:681
getDescTree(args, cls=Tree)
Definition scripting.py:229
applyTransfoMisc(pft, arg, args, simplify)
Definition scripting.py:962
updateParser(parser, withInput, withOutput, withXml, withPlotCentralFile, treeIsOptional, nbPar, restrictScope)
Definition scripting.py:247
applyTransfoCosmetics(pft, arg, args)
Definition scripting.py:879
applyTransfoFileName(pft, arg)
Definition scripting.py:724
updateParserTree(parser, withPlotCentralFile, treeIsOptional)
Definition scripting.py:641
updateParserMisc(parser)
Definition scripting.py:630