Debian Codegraph @

contrib/fypp-3.2-b8dd58b-20230822/bin/fypp

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 ################################################################################
4 #
5 # fypp -- Python powered Fortran preprocessor
6 #
7 # Copyright (c) 2016-2023 Bálint Aradi, Universität Bremen
8 #
9 # All rights reserved.
10 #
11 # Redistribution and use in source and binary forms, with or without
12 # modification, are permitted provided that the following conditions are met:
13 #
14 # 1. Redistributions of source code must retain the above copyright notice, this
15 # list of conditions and the following disclaimer.
16 #
17 # 2. Redistributions in binary form must reproduce the above copyright notice,
18 # this list of conditions and the following disclaimer in the documentation
19 # and/or other materials provided with the distribution.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
22 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #
32 ################################################################################
33
34 '''For using the functionality of the Fypp preprocessor from within
35 Python, one usually interacts with the following two classes:
36
37 * `Fypp`_: The actual Fypp preprocessor. It returns for a given input
38 the preprocessed output.
39
40 * `FyppOptions`_: Contains customizable settings controlling the behaviour of
41 `Fypp`_. Alternatively, the function `get_option_parser()`_ can be used to
42 obtain an option parser, which can create settings based on command line
43 arguments.
44
45 If processing stops prematurely, an instance of one of the following
46 subclasses of `FyppError`_ is raised:
47
48 * FyppFatalError: Unexpected error (e.g. bad input, missing files, etc.)
49
50 * FyppStopRequest: Stop was triggered by an explicit request in the input
51 (by a stop- or an assert-directive).
52 '''
53 import pathlib
54 import sys
55 import types
56 import inspect
57 import re
58 import os
59 import errno
60 import time
61 import optparse
62 import io
63 import platform
64 import builtins
65
66 # Prevent cluttering user directory with Python bytecode
67 sys.dont_write_bytecode = True
68
69 VERSION = '3.2'
70
71 STDIN = '<stdin>'
72
73 FILEOBJ = '<fileobj>'
74
75 STRING = '<string>'
76
77 ERROR_EXIT_CODE = 1
78
79 USER_ERROR_EXIT_CODE = 2
80
81 _ALL_DIRECTIVES_PATTERN = r'''
82 # comment block
83 (?:^[ \t]*\#!.*\n)+
84 |
85 # line directive (with optional continuation lines)
86 ^[ \t]*(?P<ldirtype>[\#\$@]):[ \t]*
87 (?P<ldir>.+?(?:&[ \t]*\n(?:[ \t]*&)?.*?)*)?[ \t]*\n
88 |
89 # inline eval directive
90 (?P<idirtype>[$\#@])\{[ \t]*(?P<idir>.+?)?[ \t]*\}(?P=idirtype)
91 '''
92
93 _ALL_DIRECTIVES_REGEXP = re.compile(
94 _ALL_DIRECTIVES_PATTERN, re.VERBOSE | re.MULTILINE)
95
96 _CONTROL_DIR_REGEXP = re.compile(
97 r'(?P<dir>[a-zA-Z_]\w*)[ \t]*(?:[ \t]+(?P<param>[^ \t].*))?$')
98
99 _DIRECT_CALL_REGEXP = re.compile(
100 r'(?P<callname>[a-zA-Z_][\w.]*)[ \t]*\((?P<callparams>.+?)?\)$')
101
102 _DIRECT_CALL_KWARG_REGEXP = re.compile(
103 r'(?:(?P<kwname>[a-zA-Z_]\w*)\s*=(?=[^=]|$))?')
104
105 _DEF_PARAM_REGEXP = re.compile(
106 r'^(?P<name>[a-zA-Z_]\w*)[ \t]*\(\s*(?P<args>.+)?\s*\)$')
107
108 _SIMPLE_CALLABLE_REGEXP = re.compile(
109 r'^(?P<name>[a-zA-Z_][\w.]*)[ \t]*(?:\([ \t]*(?P<args>.*)[ \t]*\))?$')
110
111 _IDENTIFIER_NAME_REGEXP = re.compile(r'^(?P<name>[a-zA-Z_]\w*)$')
112
113 _PREFIXED_IDENTIFIER_NAME_REGEXP = re.compile(r'^(?P<name>[a-zA-Z_][\w.]*)$')
114
115 _SET_PARAM_REGEXP = re.compile(
116 r'^(?P<name>(?:[(]\s*)?[a-zA-Z_]\w*(?:\s*,\s*[a-zA-Z_]\w*)*(?:\s*[)])?)\s*'\
117 r'(?:=\s*(?P<expr>.*))?$')
118
119 _DEL_PARAM_REGEXP = re.compile(
120 r'^(?:[(]\s*)?[a-zA-Z_]\w*(?:\s*,\s*[a-zA-Z_]\w*)*(?:\s*[)])?$')
121
122 _FOR_PARAM_REGEXP = re.compile(
123 r'^(?P<loopexpr>[a-zA-Z_]\w*(\s*,\s*[a-zA-Z_]\w*)*)\s+in\s+(?P<iter>.+)$')
124
125 _INCLUDE_PARAM_REGEXP = re.compile(r'^(\'|")(?P<fname>.*?)\1$')
126
127 _COMMENTLINE_REGEXP = re.compile(r'^[ \t]*!.*$')
128
129 _CONTLINE_REGEXP = re.compile(r'&[ \t]*\n(?:[ \t]*&)?')
130
131 _UNESCAPE_TEXT_REGEXP1 = re.compile(r'([$#@])\\(\\*)([{:])')
132
133 _UNESCAPE_TEXT_REGEXP2 = re.compile(r'#\\(\\*)([!])')
134
135 _UNESCAPE_TEXT_REGEXP3 = re.compile(r'(\})\\(\\*)([$#@])')
136
137 _INLINE_EVAL_REGION_REGEXP = re.compile(r'\${.*?}\$')
138
139 _RESERVED_PREFIX = '__'
140
141 _RESERVED_NAMES = set(['defined', 'setvar', 'getvar', 'delvar', 'globalvar',
142 '_LINE_', '_FILE_', '_THIS_FILE_', '_THIS_LINE_',
143 '_TIME_', '_DATE_', '_SYSTEM_', '_MACHINE_'])
144
145 _LINENUM_NEW_FILE = 1
146
147 _LINENUM_RETURN_TO_FILE = 2
148
149 _QUOTES_FORTRAN = '\'"'
150
151 _OPENING_BRACKETS_FORTRAN = '{(['
152
153 _CLOSING_BRACKETS_FORTRAN = '})]'
154
155 _ARGUMENT_SPLIT_CHAR_FORTRAN = ','
156
157
158 class FyppError(Exception):
159 '''Signalizes error occurring during preprocessing.
160
161 Args:
162 msg (str): Error message.
163 fname (str): File name. None (default) if file name is not available.
164 span (tuple of int): Beginning and end line of the region where error
165 occurred or None if not available. If fname was not None, span must
166 not be None.
167
168 Attributes:
169 msg (str): Error message.
170 fname (str or None): File name or None if not available.
171 span (tuple of int or None): Beginning and end line of the region
172 where error occurred or None if not available. Line numbers start
173 from zero. For directives, which do not consume end of the line,
174 start and end lines are identical.
175 '''
176
177 def __init__(self, msg, fname=None, span=None):
178 super().__init__()
179 self.msg = msg
180 self.fname = fname
181 self.span = span
182
183
184 def __str__(self):
185 msg = [self.__class__.__name__, ': ']
186 if self.fname is not None:
187 msg.append("file '" + self.fname + "'")
188 if self.span[1] > self.span[0] + 1:
189 msg.append(', lines {0}-{1}'.format(
190 self.span[0] + 1, self.span[1]))
191 else:
192 msg.append(', line {0}'.format(self.span[0] + 1))
193 msg.append('\n')
194 if self.msg:
195 msg.append(self.msg)
196 if self.__cause__ is not None:
197 msg.append('\n' + str(self.__cause__))
198 return ''.join(msg)
199
200
201 class FyppFatalError(FyppError):
202 '''Signalizes an unexpected error during processing.'''
203
204
205 class FyppStopRequest(FyppError):
206 '''Signalizes an explicitely triggered stop (e.g. via stop directive)'''
207
208
209 class Parser:
210 '''Parses a text and generates events when encountering Fypp constructs.
211
212 Args:
213 includedirs (list): List of directories, in which include files should
214 be searched for, when they are not found at the default location.
215
216 encoding (str): Encoding to use when reading the file (default: utf-8)
217 '''
218
219 def __init__(self, includedirs=None, encoding='utf-8'):
220
221 # Directories to search for include files
222 if includedirs is None:
223 self._includedirs = []
224 else:
225 self._includedirs = includedirs
226
227 # Encoding
228 self._encoding = encoding
229
230 # Name of current file
231 self._curfile = None
232
233 # Directory of current file
234 self._curdir = None
235
236
237 def parsefile(self, fobj):
238 '''Parses file or a file like object.
239
240 Args:
241 fobj (str or file): Name of a file or a file like object.
242 '''
243 if isinstance(fobj, str):
244 if fobj == STDIN:
245 self._includefile(None, sys.stdin, STDIN, os.getcwd())
246 else:
247 inpfp = _open_input_file(fobj, self._encoding)
248 self._includefile(None, inpfp, fobj, os.path.dirname(fobj))
249 inpfp.close()
250 else:
251 self._includefile(None, fobj, FILEOBJ, os.getcwd())
252
253
254 def _includefile(self, span, fobj, fname, curdir):
255 oldfile = self._curfile
256 olddir = self._curdir
257 self._curfile = fname
258 self._curdir = curdir
259 self._parse_txt(span, fname, fobj.read())
260 self._curfile = oldfile
261 self._curdir = olddir
262
263
264 def parse(self, txt):
265 '''Parses string.
266
267 Args:
268 txt (str): Text to parse.
269 '''
270 self._curfile = STRING
271 self._curdir = ''
272 self._parse_txt(None, self._curfile, txt)
273
274
275 def handle_include(self, span, fname):
276 '''Called when parser starts to process a new file.
277
278 It is a dummy methond and should be overridden for actual use.
279
280 Args:
281 span (tuple of int): Start and end line of the include directive
282 or None if called the first time for the main input.
283 fname (str): Name of the file.
284 '''
285 self._log_event('include', span, filename=fname)
286
287
288 def handle_endinclude(self, span, fname):
289 '''Called when parser finished processing a file.
290
291 It is a dummy method and should be overridden for actual use.
292
293 Args:
294 span (tuple of int): Start and end line of the include directive
295 or None if called the first time for the main input.
296 fname (str): Name of the file.
297 '''
298 self._log_event('endinclude', span, filename=fname)
299
300
301 def handle_set(self, span, name, expr):
302 '''Called when parser encounters a set directive.
303
304 It is a dummy method and should be overridden for actual use.
305
306 Args:
307 span (tuple of int): Start and end line of the directive.
308 name (str): Name of the variable.
309 expr (str): String representation of the expression to be assigned
310 to the variable.
311 '''
312 self._log_event('set', span, name=name, expression=expr)
313
314
315 def handle_def(self, span, name, args):
316 '''Called when parser encounters a def directive.
317
318 It is a dummy method and should be overridden for actual use.
319
320 Args:
321 span (tuple of int): Start and end line of the directive.
322 name (str): Name of the macro to be defined.
323 argexpr (str): String with argument definition (or None)
324 '''
325 self._log_event('def', span, name=name, arguments=args)
326
327
328 def handle_enddef(self, span, name):
329 '''Called when parser encounters an enddef directive.
330
331 It is a dummy method and should be overridden for actual use.
332
333 Args:
334 span (tuple of int): Start and end line of the directive.
335 name (str): Name found after the enddef directive.
336 '''
337 self._log_event('enddef', span, name=name)
338
339
340 def handle_del(self, span, name):
341 '''Called when parser encounters a del directive.
342
343 It is a dummy method and should be overridden for actual use.
344
345 Args:
346 span (tuple of int): Start and end line of the directive.
347 name (str): Name of the variable to delete.
348 '''
349 self._log_event('del', span, name=name)
350
351
352 def handle_if(self, span, cond):
353 '''Called when parser encounters an if directive.
354
355 It is a dummy method and should be overridden for actual use.
356
357 Args:
358 span (tuple of int): Start and end line of the directive.
359 cond (str): String representation of the branching condition.
360 '''
361 self._log_event('if', span, condition=cond)
362
363
364 def handle_elif(self, span, cond):
365 '''Called when parser encounters an elif directive.
366
367 It is a dummy method and should be overridden for actual use.
368
369 Args:
370 span (tuple of int): Start and end line of the directive.
371 cond (str): String representation of the branching condition.
372 '''
373 self._log_event('elif', span, condition=cond)
374
375
376 def handle_else(self, span):
377 '''Called when parser encounters an else directive.
378
379 It is a dummy method and should be overridden for actual use.
380
381 Args:
382 span (tuple of int): Start and end line of the directive.
383 '''
384 self._log_event('else', span)
385
386
387 def handle_endif(self, span):
388 '''Called when parser encounters an endif directive.
389
390 It is a dummy method and should be overridden for actual use.
391
392 Args:
393 span (tuple of int): Start and end line of the directive.
394 '''
395 self._log_event('endif', span)
396
397
398 def handle_for(self, span, varexpr, iterator):
399 '''Called when parser encounters a for directive.
400
401 It is a dummy method and should be overridden for actual use.
402
403 Args:
404 span (tuple of int): Start and end line of the directive.
405 varexpr (str): String representation of the loop variable
406 expression.
407 iterator (str): String representation of the iterable.
408 '''
409 self._log_event('for', span, variable=varexpr, iterable=iterator)
410
411
412 def handle_endfor(self, span):
413 '''Called when parser encounters an endfor directive.
414
415 It is a dummy method and should be overridden for actual use.
416
417 Args:
418 span (tuple of int): Start and end line of the directive.
419 '''
420 self._log_event('endfor', span)
421
422
423 def handle_call(self, span, name, argexpr, blockcall):
424 '''Called when parser encounters a call directive.
425
426 It is a dummy method and should be overridden for actual use.
427
428 Args:
429 span (tuple of int): Start and end line of the directive.
430 name (str): Name of the callable to call
431 argexpr (str or None): Argument expression containing additional
432 arguments for the call.
433 blockcall (bool): Whether the alternative "block / contains /
434 endblock" calling directive has been used.
435 '''
436 self._log_event('call', span, name=name, argexpr=argexpr,
437 blockcall=blockcall)
438
439
440 def handle_nextarg(self, span, name, blockcall):
441 '''Called when parser encounters a nextarg directive.
442
443 It is a dummy method and should be overridden for actual use.
444
445 Args:
446 span (tuple of int): Start and end line of the directive.
447 name (str or None): Name of the argument following next or
448 None if it should be the next positional argument.
449 blockcall (bool): Whether the alternative "block / contains /
450 endblock" calling directive has been used.
451 '''
452 self._log_event('nextarg', span, name=name, blockcall=blockcall)
453
454
455 def handle_endcall(self, span, name, blockcall):
456 '''Called when parser encounters an endcall directive.
457
458 It is a dummy method and should be overridden for actual use.
459
460 Args:
461 span (tuple of int): Start and end line of the directive.
462 name (str): Name found after the endcall directive.
463 blockcall (bool): Whether the alternative "block / contains /
464 endblock" calling directive has been used.
465 '''
466 self._log_event('endcall', span, name=name, blockcall=blockcall)
467
468
469 def handle_eval(self, span, expr):
470 '''Called when parser encounters an eval directive.
471
472 It is a dummy method and should be overridden for actual use.
473
474 Args:
475 span (tuple of int): Start and end line of the directive.
476 expr (str): String representation of the Python expression to
477 be evaluated.
478 '''
479 self._log_event('eval', span, expression=expr)
480
481
482 def handle_global(self, span, name):
483 '''Called when parser encounters a global directive.
484
485 It is a dummy method and should be overridden for actual use.
486
487 Args:
488 span (tuple of int): Start and end line of the directive.
489 name (str): Name of the variable which should be made global.
490 '''
491 self._log_event('global', span, name=name)
492
493
494 def handle_text(self, span, txt):
495 '''Called when parser finds text which must left unaltered.
496
497 It is a dummy method and should be overridden for actual use.
498
499 Args:
500 span (tuple of int): Start and end line of the directive.
501 txt (str): Text.
502 '''
503 self._log_event('text', span, content=txt)
504
505
506 def handle_comment(self, span):
507 '''Called when parser finds a preprocessor comment.
508
509 It is a dummy method and should be overridden for actual use.
510
511 Args:
512 span (tuple of int): Start and end line of the directive.
513 '''
514 self._log_event('comment', span)
515
516
517 def handle_mute(self, span):
518 '''Called when parser finds a mute directive.
519
520 It is a dummy method and should be overridden for actual use.
521
522 Args:
523 span (tuple of int): Start and end line of the directive.
524 '''
525 self._log_event('mute', span)
526
527
528 def handle_endmute(self, span):
529 '''Called when parser finds an endmute directive.
530
531 It is a dummy method and should be overridden for actual use.
532
533 Args:
534 span (tuple of int): Start and end line of the directive.
535 '''
536 self._log_event('endmute', span)
537
538
539 def handle_stop(self, span, msg):
540 '''Called when parser finds an stop directive.
541
542 It is a dummy method and should be overridden for actual use.
543
544 Args:
545 span (tuple of int): Start and end line of the directive.
546 msg (str): Stop message.
547 '''
548 self._log_event('stop', span, msg=msg)
549
550
551 def handle_assert(self, span):
552 '''Called when parser finds an assert directive.
553
554 It is a dummy method and should be overridden for actual use.
555
556 Args:
557 span (tuple of int): Start and end line of the directive.
558 '''
559 self._log_event('assert', span)
560
561
562 @staticmethod
563 def _log_event(event, span=(-1, -1), **params):
564 print('{0}: {1} --> {2}'.format(event, span[0], span[1]))
565 for parname, parvalue in params.items():
566 print(' {0}: ->|{1}|<-'.format(parname, parvalue))
567 print()
568
569
570 def _parse_txt(self, includespan, fname, txt):
571 self.handle_include(includespan, fname)
572 self._parse(txt)
573 self.handle_endinclude(includespan, fname)
574
575
576 def _parse(self, txt, linenr=0, directcall=False):
577 pos = 0
578 for match in _ALL_DIRECTIVES_REGEXP.finditer(txt):
579 start, end = match.span()
580 if start > pos:
581 endlinenr = linenr + txt.count('\n', pos, start)
582 self._process_text(txt[pos:start], (linenr, endlinenr))
583 linenr = endlinenr
584 endlinenr = linenr + txt.count('\n', start, end)
585 span = (linenr, endlinenr)
586 ldirtype, ldir, idirtype, idir = match.groups()
587 if directcall and (idirtype is None or idirtype != '$'):
588 msg = 'only inline eval directives allowed in direct calls'
589 raise FyppFatalError(msg, self._curfile, span)
590 elif idirtype is not None:
591 if idir is None:
592 msg = 'missing inline directive content'
593 raise FyppFatalError(msg, self._curfile, span)
594 dirtype = idirtype
595 content = idir
596 elif ldirtype is not None:
597 if ldir is None:
598 msg = 'missing line directive content'
599 raise FyppFatalError(msg, self._curfile, span)
600 dirtype = ldirtype
601 content = _CONTLINE_REGEXP.sub('', ldir)
602 else:
603 # Comment directive
604 dirtype = None
605 if dirtype == '$':
606 self.handle_eval(span, content)
607 elif dirtype == '#':
608 self._process_control_dir(content, span)
609 elif dirtype == '@':
610 self._process_direct_call(content, span)
611 else:
612 self.handle_comment(span)
613 pos = end
614 linenr = endlinenr
615 if pos < len(txt):
616 endlinenr = linenr + txt.count('\n', pos)
617 self._process_text(txt[pos:], (linenr, endlinenr))
618
619
620 def _process_text(self, txt, span):
621 escaped_txt = self._unescape(txt)
622 self.handle_text(span, escaped_txt)
623
624
625 def _process_control_dir(self, content, span):
626 match = _CONTROL_DIR_REGEXP.match(content)
627 if not match:
628 msg = "invalid control directive content '{0}'".format(content)
629 raise FyppFatalError(msg, self._curfile, span)
630 directive, param = match.groups()
631 if directive == 'if':
632 self._check_param_presence(True, 'if', param, span)
633 self.handle_if(span, param)
634 elif directive == 'else':
635 self._check_param_presence(False, 'else', param, span)
636 self.handle_else(span)
637 elif directive == 'elif':
638 self._check_param_presence(True, 'elif', param, span)
639 self.handle_elif(span, param)
640 elif directive == 'endif':
641 self._check_param_presence(False, 'endif', param, span)
642 self.handle_endif(span)
643 elif directive == 'def':
644 self._check_param_presence(True, 'def', param, span)
645 self._check_not_inline_directive('def', span)
646 self._process_def(param, span)
647 elif directive == 'enddef':
648 self._process_enddef(param, span)
649 elif directive == 'set':
650 self._check_param_presence(True, 'set', param, span)
651 self._process_set(param, span)
652 elif directive == 'del':
653 self._check_param_presence(True, 'del', param, span)
654 self._process_del(param, span)
655 elif directive == 'for':
656 self._check_param_presence(True, 'for', param, span)
657 self._process_for(param, span)
658 elif directive == 'endfor':
659 self._check_param_presence(False, 'endfor', param, span)
660 self.handle_endfor(span)
661 elif directive == 'call' or directive == 'block':
662 self._check_param_presence(True, directive, param, span)
663 self._process_call(param, span, directive == 'block')
664 elif directive == 'nextarg' or directive == 'contains':
665 self._process_nextarg(param, span, directive == 'contains')
666 elif directive == 'endcall' or directive == 'endblock':
667 self._process_endcall(param, span, directive == 'endblock')
668 elif directive == 'include':
669 self._check_param_presence(True, 'include', param, span)
670 self._check_not_inline_directive('include', span)
671 self._process_include(param, span)
672 elif directive == 'mute':
673 self._check_param_presence(False, 'mute', param, span)
674 self._check_not_inline_directive('mute', span)
675 self.handle_mute(span)
676 elif directive == 'endmute':
677 self._check_param_presence(False, 'endmute', param, span)
678 self._check_not_inline_directive('endmute', span)
679 self.handle_endmute(span)
680 elif directive == 'stop':
681 self._check_param_presence(True, 'stop', param, span)
682 self._check_not_inline_directive('stop', span)
683 self.handle_stop(span, param)
684 elif directive == 'assert':
685 self._check_param_presence(True, 'assert', param, span)
686 self._check_not_inline_directive('assert', span)
687 self.handle_assert(span, param)
688 elif directive == 'global':
689 self._check_param_presence(True, 'global', param, span)
690 self._process_global(param, span)
691 else:
692 msg = "unknown directive '{0}'".format(directive)
693 raise FyppFatalError(msg, self._curfile, span)
694
695
696 def _process_direct_call(self, callexpr, span):
697 match = _DIRECT_CALL_REGEXP.match(callexpr)
698 if not match:
699 msg = "invalid direct call expression"
700 raise FyppFatalError(msg, self._curfile, span)
701 callname = match.group('callname')
702 self.handle_call(span, callname, None, False)
703 callparams = match.group('callparams')
704 if callparams is None or not callparams.strip():
705 args = []
706 else:
707 try:
708 args = [arg.strip() for arg in _argsplit_fortran(callparams)]
709 except Exception as exc:
710 msg = 'unable to parse direct call argument'
711 raise FyppFatalError(msg, self._curfile, span) from exc
712 for arg in args:
713 match = _DIRECT_CALL_KWARG_REGEXP.match(arg)
714 argval = arg[match.end():].strip()
715 # Remove enclosing braces if present
716 if argval.startswith('{'):
717 argval = argval[1:-1]
718 keyword = match.group('kwname')
719 self.handle_nextarg(span, keyword, False)
720 self._parse(argval, linenr=span[0], directcall=True)
721 self.handle_endcall(span, callname, False)
722
723
724 def _process_def(self, param, span):
725 match = _DEF_PARAM_REGEXP.match(param)
726 if not match:
727 msg = "invalid macro definition '{0}'".format(param)
728 raise FyppFatalError(msg, self._curfile, span)
729 name = match.group('name')
730 argexpr = match.group('args')
731 self.handle_def(span, name, argexpr)
732
733
734 def _process_enddef(self, param, span):
735 if param is not None:
736 match = _IDENTIFIER_NAME_REGEXP.match(param)
737 if not match:
738 msg = "invalid enddef parameter '{0}'".format(param)
739 raise FyppFatalError(msg, self._curfile, span)
740 param = match.group('name')
741 self.handle_enddef(span, param)
742
743
744 def _process_set(self, param, span):
745 match = _SET_PARAM_REGEXP.match(param)
746 if not match:
747 msg = "invalid variable assignment '{0}'".format(param)
748 raise FyppFatalError(msg, self._curfile, span)
749 self.handle_set(span, match.group('name'), match.group('expr'))
750
751
752 def _process_global(self, param, span):
753 match = _DEL_PARAM_REGEXP.match(param)
754 if not match:
755 msg = "invalid variable specification '{0}'".format(param)
756 raise FyppFatalError(msg, self._curfile, span)
757 self.handle_global(span, param)
758
759
760 def _process_del(self, param, span):
761 match = _DEL_PARAM_REGEXP.match(param)
762 if not match:
763 msg = "invalid variable specification '{0}'".format(param)
764 raise FyppFatalError(msg, self._curfile, span)
765 self.handle_del(span, param)
766
767
768 def _process_for(self, param, span):
769 match = _FOR_PARAM_REGEXP.match(param)
770 if not match:
771 msg = "invalid for loop declaration '{0}'".format(param)
772 raise FyppFatalError(msg, self._curfile, span)
773 loopexpr = match.group('loopexpr')
774 loopvars = [s.strip() for s in loopexpr.split(',')]
775 self.handle_for(span, loopvars, match.group('iter'))
776
777
778 def _process_call(self, param, span, blockcall):
779 match = _SIMPLE_CALLABLE_REGEXP.match(param)
780 if not match:
781 msg = "invalid callable expression '{}'".format(param)
782 raise FyppFatalError(msg, self._curfile, span)
783 name, args = match.groups()
784 self.handle_call(span, name, args, blockcall)
785
786
787 def _process_nextarg(self, param, span, blockcall):
788 if param is not None:
789 match = _IDENTIFIER_NAME_REGEXP.match(param)
790 if not match:
791 msg = "invalid nextarg parameter '{0}'".format(param)
792 raise FyppFatalError(msg, self._curfile, span)
793 param = match.group('name')
794 self.handle_nextarg(span, param, blockcall)
795
796
797 def _process_endcall(self, param, span, blockcall):
798 if param is not None:
799 match = _PREFIXED_IDENTIFIER_NAME_REGEXP.match(param)
800 if not match:
801 msg = "invalid endcall parameter '{0}'".format(param)
802 raise FyppFatalError(msg, self._curfile, span)
803 param = match.group('name')
804 self.handle_endcall(span, param, blockcall)
805
806
807 def _process_include(self, param, span):
808 match = _INCLUDE_PARAM_REGEXP.match(param)
809 if not match:
810 msg = "invalid include file declaration '{0}'".format(param)
811 raise FyppFatalError(msg, self._curfile, span)
812 fname = match.group('fname')
813 for incdir in [self._curdir] + self._includedirs:
814 fpath = os.path.join(incdir, fname)
815 if os.path.exists(fpath):
816 break
817 else:
818 msg = "include file '{0}' not found".format(fname)
819 raise FyppFatalError(msg, self._curfile, span)
820 inpfp = _open_input_file(fpath, self._encoding)
821 self._includefile(span, inpfp, fpath, os.path.dirname(fpath))
822 inpfp.close()
823
824
825 def _process_mute(self, span):
826 if span[0] == span[1]:
827 msg = 'Inline form of mute directive not allowed'
828 raise FyppFatalError(msg, self._curfile, span)
829 self.handle_mute(span)
830
831
832 def _process_endmute(self, span):
833 if span[0] == span[1]:
834 msg = 'Inline form of endmute directive not allowed'
835 raise FyppFatalError(msg, self._curfile, span)
836 self.handle_endmute(span)
837
838
839 def _check_param_presence(self, presence, directive, param, span):
840 if (param is not None) != presence:
841 if presence:
842 msg = 'missing data in {0} directive'.format(directive)
843 else:
844 msg = 'forbidden data in {0} directive'.format(directive)
845 raise FyppFatalError(msg, self._curfile, span)
846
847
848 def _check_not_inline_directive(self, directive, span):
849 if span[0] == span[1]:
850 msg = 'Inline form of {0} directive not allowed'.format(directive)
851 raise FyppFatalError(msg, self._curfile, span)
852
853
854 @staticmethod
855 def _unescape(txt):
856 txt = _UNESCAPE_TEXT_REGEXP1.sub(r'\1\2\3', txt)
857 txt = _UNESCAPE_TEXT_REGEXP2.sub(r'#\1\2', txt)
858 txt = _UNESCAPE_TEXT_REGEXP3.sub(r'\1\2\3', txt)
859 return txt
860
861
862 class Builder:
863 '''Builds a tree representing a text with preprocessor directives.
864 '''
865
866 def __init__(self):
867 # The tree, which should be built.
868 self._tree = []
869
870 # List of all open constructs
871 self._open_blocks = []
872
873 # Nodes to which the open blocks have to be appended when closed
874 self._path = []
875
876 # Nr. of open blocks when file was opened. Used for checking whether all
877 # blocks have been closed, when file processing finishes.
878 self._nr_prev_blocks = []
879
880 # Current node, to which content should be added
881 self._curnode = self._tree
882
883 # Current file
884 self._curfile = None
885
886
887 def reset(self):
888 '''Resets the builder so that it starts to build a new tree.'''
889 self._tree = []
890 self._open_blocks = []
891 self._path = []
892 self._nr_prev_blocks = []
893 self._curnode = self._tree
894 self._curfile = None
895
896
897 def handle_include(self, span, fname):
898 '''Should be called to signalize change to new file.
899
900 Args:
901 span (tuple of int): Start and end line of the include directive
902 or None if called the first time for the main input.
903 fname (str): Name of the file to be included.
904 '''
905 self._path.append(self._curnode)
906 self._curnode = []
907 self._open_blocks.append(
908 ('include', self._curfile, [span], fname, None))
909 self._curfile = fname
910 self._nr_prev_blocks.append(len(self._open_blocks))
911
912
913 def handle_endinclude(self, span, fname):
914 '''Should be called when processing of a file finished.
915
916 Args:
917 span (tuple of int): Start and end line of the include directive
918 or None if called the first time for the main input.
919 fname (str): Name of the file which has been included.
920 '''
921 nprev_blocks = self._nr_prev_blocks.pop(-1)
922 if len(self._open_blocks) > nprev_blocks:
923 directive, fname, spans = self._open_blocks[-1][0:3]
924 msg = '{0} directive still unclosed when reaching end of file'\
925 .format(directive)
926 raise FyppFatalError(msg, self._curfile, spans[0])
927 block = self._open_blocks.pop(-1)
928 directive, blockfname, spans = block[0:3]
929 if directive != 'include':
930 msg = 'internal error: last open block is not \'include\' when '\
931 'closing file \'{0}\''.format(fname)
932 raise FyppFatalError(msg)
933 if span != spans[0]:
934 msg = 'internal error: span for include and endinclude differ ('\
935 '{0} vs {1}'.format(span, spans[0])
936 raise FyppFatalError(msg)
937 oldfname, _ = block[3:5]
938 if fname != oldfname:
939 msg = 'internal error: mismatching file name in close_file event'\
940 " (expected: '{0}', got: '{1}')".format(oldfname, fname)
941 raise FyppFatalError(msg, fname)
942 block = directive, blockfname, spans, fname, self._curnode
943 self._curnode = self._path.pop(-1)
944 self._curnode.append(block)
945 self._curfile = blockfname
946
947
948 def handle_if(self, span, cond):
949 '''Should be called to signalize an if directive.
950
951 Args:
952 span (tuple of int): Start and end line of the directive.
953 param (str): String representation of the branching condition.
954 '''
955 self._path.append(self._curnode)
956 self._curnode = []
957 self._open_blocks.append(('if', self._curfile, [span], [cond], []))
958
959
960 def handle_elif(self, span, cond):
961 '''Should be called to signalize an elif directive.
962
963 Args:
964 span (tuple of int): Start and end line of the directive.
965 cond (str): String representation of the branching condition.
966 '''
967 self._check_for_open_block(span, 'elif')
968 block = self._open_blocks[-1]
969 directive, _, spans = block[0:3]
970 self._check_if_matches_last(directive, 'if', spans[-1], span, 'elif')
971 conds, contents = block[3:5]
972 conds.append(cond)
973 contents.append(self._curnode)
974 spans.append(span)
975 self._curnode = []
976
977
978 def handle_else(self, span):
979 '''Should be called to signalize an else directive.
980
981 Args:
982 span (tuple of int): Start and end line of the directive.
983 '''
984 self._check_for_open_block(span, 'else')
985 block = self._open_blocks[-1]
986 directive, _, spans = block[0:3]
987 self._check_if_matches_last(directive, 'if', spans[-1], span, 'else')
988 conds, contents = block[3:5]
989 conds.append('True')
990 contents.append(self._curnode)
991 spans.append(span)
992 self._curnode = []
993
994
995 def handle_endif(self, span):
996 '''Should be called to signalize an endif directive.
997
998 Args:
999 span (tuple of int): Start and end line of the directive.
1000 '''
1001 self._check_for_open_block(span, 'endif')
1002 block = self._open_blocks.pop(-1)
1003 directive, _, spans = block[0:3]
1004 self._check_if_matches_last(directive, 'if', spans[-1], span, 'endif')
1005 _, contents = block[3:5]
1006 contents.append(self._curnode)
1007 spans.append(span)
1008 self._curnode = self._path.pop(-1)
1009 self._curnode.append(block)
1010
1011
1012 def handle_for(self, span, loopvar, iterator):
1013 '''Should be called to signalize a for directive.
1014
1015 Args:
1016 span (tuple of int): Start and end line of the directive.
1017 varexpr (str): String representation of the loop variable
1018 expression.
1019 iterator (str): String representation of the iterable.
1020 '''
1021 self._path.append(self._curnode)
1022 self._curnode = []
1023 self._open_blocks.append(('for', self._curfile, [span], loopvar,
1024 iterator, None))
1025
1026
1027 def handle_endfor(self, span):
1028 '''Should be called to signalize an endfor directive.
1029
1030 Args:
1031 span (tuple of int): Start and end line of the directive.
1032 '''
1033 self._check_for_open_block(span, 'endfor')
1034 block = self._open_blocks.pop(-1)
1035 directive, fname, spans = block[0:3]
1036 self._check_if_matches_last(directive, 'for', spans[-1], span, 'endfor')
1037 loopvar, iterator, dummy = block[3:6]
1038 spans.append(span)
1039 block = (directive, fname, spans, loopvar, iterator, self._curnode)
1040 self._curnode = self._path.pop(-1)
1041 self._curnode.append(block)
1042
1043
1044 def handle_def(self, span, name, argexpr):
1045 '''Should be called to signalize a def directive.
1046
1047 Args:
1048 span (tuple of int): Start and end line of the directive.
1049 name (str): Name of the macro to be defined.
1050 argexpr (str): Macro argument definition or None
1051 '''
1052 self._path.append(self._curnode)
1053 self._curnode = []
1054 defblock = ('def', self._curfile, [span], name, argexpr, None)
1055 self._open_blocks.append(defblock)
1056
1057
1058 def handle_enddef(self, span, name):
1059 '''Should be called to signalize an enddef directive.
1060
1061 Args:
1062 span (tuple of int): Start and end line of the directive.
1063 name (str): Name of the enddef statement. Could be None, if enddef
1064 was specified without name.
1065 '''
1066 self._check_for_open_block(span, 'enddef')
1067 block = self._open_blocks.pop(-1)
1068 directive, fname, spans = block[0:3]
1069 self._check_if_matches_last(directive, 'def', spans[-1], span, 'enddef')
1070 defname, argexpr, dummy = block[3:6]
1071 if name is not None and name != defname:
1072 msg = "wrong name in enddef directive "\
1073 "(expected '{0}', got '{1}')".format(defname, name)
1074 raise FyppFatalError(msg, fname, span)
1075 spans.append(span)
1076 block = (directive, fname, spans, defname, argexpr, self._curnode)
1077 self._curnode = self._path.pop(-1)
1078 self._curnode.append(block)
1079
1080
1081 def handle_call(self, span, name, argexpr, blockcall):
1082 '''Should be called to signalize a call directive.
1083
1084 Args:
1085 span (tuple of int): Start and end line of the directive.
1086 name (str): Name of the callable to call
1087 argexpr (str or None): Argument expression containing additional
1088 arguments for the call.
1089 blockcall (bool): Whether the alternative "block / contains /
1090 endblock" calling directive has been used.
1091 '''
1092 self._path.append(self._curnode)
1093 self._curnode = []
1094 directive = 'block' if blockcall else 'call'
1095 self._open_blocks.append(
1096 (directive, self._curfile, [span, span], name, argexpr, [], []))
1097
1098
1099 def handle_nextarg(self, span, name, blockcall):
1100 '''Should be called to signalize a nextarg directive.
1101
1102 Args:
1103 span (tuple of int): Start and end line of the directive.
1104 name (str or None): Name of the argument following next or
1105 None if it should be the next positional argument.
1106 blockcall (bool): Whether the alternative "block / contains /
1107 endblock" calling directive has been used.
1108 '''
1109 self._check_for_open_block(span, 'nextarg')
1110 block = self._open_blocks[-1]
1111 directive, fname, spans = block[0:3]
1112 if blockcall:
1113 opened, current = 'block', 'contains'
1114 else:
1115 opened, current = 'call', 'nextarg'
1116 self._check_if_matches_last(directive, opened, spans[-1], span, current)
1117 args, argnames = block[5:7]
1118 args.append(self._curnode)
1119 spans.append(span)
1120 if name is not None:
1121 argnames.append(name)
1122 elif argnames:
1123 msg = 'non-keyword argument following keyword argument'
1124 raise FyppFatalError(msg, fname, span)
1125 self._curnode = []
1126
1127
1128 def handle_endcall(self, span, name, blockcall):
1129 '''Should be called to signalize an endcall directive.
1130
1131 Args:
1132 span (tuple of int): Start and end line of the directive.
1133 name (str): Name of the endcall statement. Could be None, if endcall
1134 was specified without name.
1135 blockcall (bool): Whether the alternative "block / contains /
1136 endblock" calling directive has been used.
1137 '''
1138 self._check_for_open_block(span, 'endcall')
1139 block = self._open_blocks.pop(-1)
1140 directive, fname, spans = block[0:3]
1141 callname, callargexpr, args, argnames = block[3:7]
1142 if blockcall:
1143 opened, current = 'block', 'endblock'
1144 else:
1145 opened, current = 'call', 'endcall'
1146 self._check_if_matches_last(directive, opened, spans[0], span, current)
1147
1148 if name is not None and name != callname:
1149 msg = "wrong name in {0} directive "\
1150 "(expected '{1}', got '{2}')".format(current, callname, name)
1151 raise FyppFatalError(msg, fname, span)
1152 args.append(self._curnode)
1153 # If nextarg or endcall immediately followed call, then first argument
1154 # is empty and should be removed (to allow for calls without arguments
1155 # and named first argument in calls)
1156 if args and not args[0]:
1157 if len(argnames) == len(args):
1158 del argnames[0]
1159 del args[0]
1160 del spans[1]
1161 spans.append(span)
1162 block = (directive, fname, spans, callname, callargexpr, args, argnames)
1163 self._curnode = self._path.pop(-1)
1164 self._curnode.append(block)
1165
1166
1167 def handle_set(self, span, name, expr):
1168 '''Should be called to signalize a set directive.
1169
1170 Args:
1171 span (tuple of int): Start and end line of the directive.
1172 name (str): Name of the variable.
1173 expr (str): String representation of the expression to be assigned
1174 to the variable.
1175 '''
1176 self._curnode.append(('set', self._curfile, span, name, expr))
1177
1178
1179 def handle_global(self, span, name):
1180 '''Should be called to signalize a global directive.
1181
1182 Args:
1183 span (tuple of int): Start and end line of the directive.
1184 name (str): Name of the variable(s) to make global.
1185 '''
1186 self._curnode.append(('global', self._curfile, span, name))
1187
1188
1189 def handle_del(self, span, name):
1190 '''Should be called to signalize a del directive.
1191
1192 Args:
1193 span (tuple of int): Start and end line of the directive.
1194 name (str): Name of the variable(s) to delete.
1195 '''
1196 self._curnode.append(('del', self._curfile, span, name))
1197
1198
1199 def handle_eval(self, span, expr):
1200 '''Should be called to signalize an eval directive.
1201
1202 Args:
1203 span (tuple of int): Start and end line of the directive.
1204 expr (str): String representation of the Python expression to
1205 be evaluated.
1206 '''
1207 self._curnode.append(('eval', self._curfile, span, expr))
1208
1209
1210 def handle_comment(self, span):
1211 '''Should be called to signalize a comment directive.
1212
1213 The content of the comment is not needed by the builder, but it needs
1214 the span of the comment to generate proper line numbers if needed.
1215
1216 Args:
1217 span (tuple of int): Start and end line of the directive.
1218 '''
1219 self._curnode.append(('comment', self._curfile, span))
1220
1221
1222 def handle_text(self, span, txt):
1223 '''Should be called to pass text which goes to output unaltered.
1224
1225 Args:
1226 span (tuple of int): Start and end line of the text.
1227 txt (str): Text.
1228 '''
1229 self._curnode.append(('txt', self._curfile, span, txt))
1230
1231
1232 def handle_mute(self, span):
1233 '''Should be called to signalize a mute directive.
1234
1235 Args:
1236 span (tuple of int): Start and end line of the directive.
1237 '''
1238 self._path.append(self._curnode)
1239 self._curnode = []
1240 self._open_blocks.append(('mute', self._curfile, [span], None))
1241
1242
1243 def handle_endmute(self, span):
1244 '''Should be called to signalize an endmute directive.
1245
1246 Args:
1247 span (tuple of int): Start and end line of the directive.
1248 '''
1249 self._check_for_open_block(span, 'endmute')
1250 block = self._open_blocks.pop(-1)
1251 directive, fname, spans = block[0:3]
1252 self._check_if_matches_last(directive, 'mute', spans[-1], span,
1253 'endmute')
1254 spans.append(span)
1255 block = (directive, fname, spans, self._curnode)
1256 self._curnode = self._path.pop(-1)
1257 self._curnode.append(block)
1258
1259
1260 def handle_stop(self, span, msg):
1261 '''Should be called to signalize a stop directive.
1262
1263 Args:
1264 span (tuple of int): Start and end line of the directive.
1265 '''
1266 self._curnode.append(('stop', self._curfile, span, msg))
1267
1268
1269 def handle_assert(self, span, cond):
1270 '''Should be called to signalize an assert directive.
1271
1272 Args:
1273 span (tuple of int): Start and end line of the directive.
1274 '''
1275 self._curnode.append(('assert', self._curfile, span, cond))
1276
1277
1278 @property
1279 def tree(self):
1280 '''Returns the tree built by the Builder.'''
1281 return self._tree
1282
1283
1284 def _check_for_open_block(self, span, directive):
1285 if len(self._open_blocks) <= self._nr_prev_blocks[-1]:
1286 msg = 'unexpected {0} directive'.format(directive)
1287 raise FyppFatalError(msg, self._curfile, span)
1288
1289
1290 def _check_if_matches_last(self, lastdir, curdir, lastspan, curspan,
1291 directive):
1292 if curdir != lastdir:
1293 msg = "mismatching '{0}' directive (last block opened was '{1}')"\
1294 .format(directive, lastdir)
1295 raise FyppFatalError(msg, self._curfile, curspan)
1296 inline_last = lastspan[0] == lastspan[1]
1297 inline_cur = curspan[0] == curspan[1]
1298 if inline_last != inline_cur:
1299 if inline_cur:
1300 msg = 'expecting line form of directive {0}'.format(directive)
1301 else:
1302 msg = 'expecting inline form of directive {0}'.format(directive)
1303 raise FyppFatalError(msg, self._curfile, curspan)
1304 elif inline_cur and curspan[0] != lastspan[0]:
1305 msg = 'inline directives of the same construct must be in the '\
1306 'same row'
1307 raise FyppFatalError(msg, self._curfile, curspan)
1308
1309
1310 class Renderer:
1311
1312 ''''Renders a tree.
1313
1314 Args:
1315 evaluator (Evaluator, optional): Evaluator to use when rendering eval
1316 directives. If None (default), Evaluator() is used.
1317 linenums (bool, optional): Whether linenums should be generated,
1318 defaults to False.
1319 contlinenums (bool, optional): Whether linenums for continuation
1320 should be generated, defaults to False.
1321 linenumformat (str, optional): 'std', 'cpp' or 'gfortran5' depending
1322 what kind of line directives should be created. Default: 'cpp'.
1323 Format 'std' emits #line pragmas, 'cpp' resembles GNU cpps special
1324 format, and 'gfortran5' adds to cpp a workaround for a bug introduced in GFortran 5.
1325 linefolder (callable): Callable to use when folding a line.
1326 filevarroot (str, optional): render _FILE_ and _THIS_FILE_ as paths relative to this
1327 root directory (default: paths are not converted explicitely to relative paths)
1328 '''
1329
1330 def __init__(self, evaluator=None, linenums=False, contlinenums=False,
1331 linenumformat=None, linefolder=None, filevarroot=None):
1332 # Evaluator to use for Python expressions
1333 self._evaluator = Evaluator() if evaluator is None else evaluator
1334 self._evaluator.updateglobals(_SYSTEM_=platform.system(),
1335 _MACHINE_=platform.machine())
1336
1337 # Whether rendered output is diverted and will be processed
1338 # further before output (if True: no line numbering and post processing)
1339 self._diverted = False
1340
1341 # Whether file name and line numbers should be kept fixed and
1342 # not updated (typically when rendering macro content)
1343 self._fixedposition = False
1344
1345 # Whether line numbering directives should be emitted
1346 self._linenums = linenums
1347
1348 # Whether line numbering directives in continuation lines are needed.
1349 self._contlinenums = contlinenums
1350
1351 # Line number formatter function and whether gfortran5 fix is needed
1352 if linenumformat is None or linenumformat in ('cpp', 'gfortran5'):
1353 self._linenumdir = linenumdir_cpp
1354 self._linenum_gfortran5 = linenumformat == 'gfortran5'
1355 else:
1356 self._linenumdir = linenumdir_std
1357 self._linenum_gfortran5 = False
1358
1359 # Callable to be used for folding lines
1360 if linefolder is None:
1361 self._linefolder = lambda line: [line]
1362 else:
1363 self._linefolder = linefolder
1364
1365 if filevarroot is None:
1366 self._convert_file_path = lambda path: path
1367 else:
1368 self._convert_file_path = (
1369 lambda path: pathlib.Path(path).relative_to(filevarroot)
1370 )
1371
1372
1373 def render(self, tree, divert=False, fixposition=False):
1374 '''Renders a tree.
1375
1376 Args:
1377 tree (fypp-tree): Tree to render.
1378 divert (bool): Whether output will be diverted and sent for further
1379 processing, so that no line numbering directives and
1380 postprocessing are needed at this stage. (Default: False)
1381 fixposition (bool): Whether file name and line position (variables
1382 _FILE_ and _LINE_) should be kept at their current values or
1383 should be updated continuously. (Default: False).
1384
1385 Returns: str: Rendered string.
1386 '''
1387 diverted = self._diverted
1388 self._diverted = divert
1389 fixedposition_old = self._fixedposition
1390 self._fixedposition = self._fixedposition or fixposition
1391 output, eval_inds, eval_pos = self._render(tree)
1392 if not self._diverted and eval_inds:
1393 self._postprocess_eval_lines(output, eval_inds, eval_pos)
1394 self._diverted = diverted
1395 self._fixedposition = fixedposition_old
1396 txt = ''.join(output)
1397
1398 return txt
1399
1400
1401 def _render(self, tree):
1402 output = []
1403 eval_inds = []
1404 eval_pos = []
1405 for node in tree:
1406 cmd = node[0]
1407 if cmd == 'txt':
1408 output.append(node[3])
1409 elif cmd == 'if':
1410 out, ieval, peval = self._get_conditional_content(*node[1:5])
1411 eval_inds += _shiftinds(ieval, len(output))
1412 eval_pos += peval
1413 output += out
1414 elif cmd == 'eval':
1415 out, ieval, peval = self._get_eval(*node[1:4])
1416 eval_inds += _shiftinds(ieval, len(output))
1417 eval_pos += peval
1418 output += out
1419 elif cmd == 'def':
1420 result = self._define_macro(*node[1:6])
1421 output.append(result)
1422 elif cmd == 'set':
1423 result = self._define_variable(*node[1:5])
1424 output.append(result)
1425 elif cmd == 'del':
1426 self._delete_variable(*node[1:4])
1427 elif cmd == 'for':
1428 out, ieval, peval = self._get_iterated_content(*node[1:6])
1429 eval_inds += _shiftinds(ieval, len(output))
1430 eval_pos += peval
1431 output += out
1432 elif cmd == 'call' or cmd == 'block':
1433 out, ieval, peval = self._get_called_content(*node[1:7])
1434 eval_inds += _shiftinds(ieval, len(output))
1435 eval_pos += peval
1436 output += out
1437 elif cmd == 'include':
1438 out, ieval, peval = self._get_included_content(*node[1:5])
1439 eval_inds += _shiftinds(ieval, len(output))
1440 eval_pos += peval
1441 output += out
1442 elif cmd == 'comment':
1443 output.append(self._get_comment(*node[1:3]))
1444 elif cmd == 'mute':
1445 output.append(self._get_muted_content(*node[1:4]))
1446 elif cmd == 'stop':
1447 self._handle_stop(*node[1:4])
1448 elif cmd == 'assert':
1449 result = self._handle_assert(*node[1:4])
1450 output.append(result)
1451 elif cmd == 'global':
1452 self._add_global(*node[1:4])
1453 else:
1454 msg = "internal error: unknown command '{0}'".format(cmd)
1455 raise FyppFatalError(msg)
1456 return output, eval_inds, eval_pos
1457
1458
1459 def _get_eval(self, fname, span, expr):
1460 try:
1461 result = self._evaluate(expr, fname, span[0])
1462 except Exception as exc:
1463 msg = "exception occurred when evaluating '{0}'".format(expr)
1464 raise FyppFatalError(msg, fname, span) from exc
1465 out = []
1466 ieval = []
1467 peval = []
1468 if result is not None:
1469 out.append(str(result))
1470 if not self._diverted:
1471 ieval.append(0)
1472 peval.append((span, fname))
1473 if span[0] != span[1]:
1474 out.append('\n')
1475 return out, ieval, peval
1476
1477
1478 def _get_conditional_content(self, fname, spans, conditions, contents):
1479 out = []
1480 ieval = []
1481 peval = []
1482 multiline = (spans[0][0] != spans[-1][1])
1483 for condition, content, span in zip(conditions, contents, spans):
1484 try:
1485 cond = bool(self._evaluate(condition, fname, span[0]))
1486 except Exception as exc:
1487 msg = "exception occurred when evaluating '{0}'"\
1488 .format(condition)
1489 raise FyppFatalError(msg, fname, span) from exc
1490 if cond:
1491 if self._linenums and not self._diverted and multiline:
1492 out.append(self._linenumdir(span[1], fname))
1493 outcont, ievalcont, pevalcont = self._render(content)
1494 ieval += _shiftinds(ievalcont, len(out))
1495 peval += pevalcont
1496 out += outcont
1497 break
1498 if self._linenums and not self._diverted and multiline:
1499 out.append(self._linenumdir(spans[-1][1], fname))
1500 return out, ieval, peval
1501
1502
1503 def _get_iterated_content(self, fname, spans, loopvars, loopiter, content):
1504 out = []
1505 ieval = []
1506 peval = []
1507 try:
1508 iterobj = iter(self._evaluate(loopiter, fname, spans[0][0]))
1509 except Exception as exc:
1510 msg = "exception occurred when evaluating '{0}'"\
1511 .format(loopiter)
1512 raise FyppFatalError(msg, fname, spans[0]) from exc
1513 multiline = (spans[0][0] != spans[-1][1])
1514 for var in iterobj:
1515 if len(loopvars) == 1:
1516 self._define(loopvars[0], var)
1517 else:
1518 for varname, value in zip(loopvars, var):
1519 self._define(varname, value)
1520 if self._linenums and not self._diverted and multiline:
1521 out.append(self._linenumdir(spans[0][1], fname))
1522 outcont, ievalcont, pevalcont = self._render(content)
1523 ieval += _shiftinds(ievalcont, len(out))
1524 peval += pevalcont
1525 out += outcont
1526 if self._linenums and not self._diverted and multiline:
1527 out.append(self._linenumdir(spans[1][1], fname))
1528 return out, ieval, peval
1529
1530
1531 def _get_called_content(self, fname, spans, name, argexpr, contents,
1532 argnames):
1533 posargs, kwargs = self._get_call_arguments(fname, spans, argexpr,
1534 contents, argnames)
1535 try:
1536 callobj = self._evaluate(name, fname, spans[0][0])
1537 result = callobj(*posargs, **kwargs)
1538 except Exception as exc:
1539 msg = "exception occurred when calling '{0}'".format(name)
1540 raise FyppFatalError(msg, fname, spans[0]) from exc
1541 self._update_predef_globals(fname, spans[0][0])
1542 span = (spans[0][0], spans[-1][1])
1543 out = []
1544 ieval = []
1545 peval = []
1546 if result is not None:
1547 out = [str(result)]
1548 if not self._diverted:
1549 ieval = [0]
1550 peval = [(span, fname)]
1551 if span[0] != span[1]:
1552 out.append('\n')
1553 return out, ieval, peval
1554
1555
1556 def _get_call_arguments(self, fname, spans, argexpr, contents, argnames):
1557 if argexpr is None:
1558 posargs = []
1559 kwargs = {}
1560 else:
1561 # Parse and evaluate arguments passed in call header
1562 self._evaluator.openscope()
1563 try:
1564 posargs, kwargs = self._evaluate(
1565 '__getargvalues(' + argexpr + ')', fname, spans[0][0])
1566 except Exception as exc:
1567 msg = "unable to parse argument expression '{0}'"\
1568 .format(argexpr)
1569 raise FyppFatalError(msg, fname, spans[0]) from exc
1570 self._evaluator.closescope()
1571
1572 # Render arguments passed in call body
1573 args = []
1574 for content in contents:
1575 self._evaluator.openscope()
1576 rendered = self.render(content, divert=True)
1577 self._evaluator.closescope()
1578 if rendered.endswith('\n'):
1579 rendered = rendered[:-1]
1580 args.append(rendered)
1581
1582 # Separate arguments in call body into positional and keyword ones:
1583 if argnames:
1584 posargs += args[:len(args) - len(argnames)]
1585 offset = len(args) - len(argnames)
1586 for iargname, argname in enumerate(argnames):
1587 ind = offset + iargname
1588 if argname in kwargs:
1589 msg = "keyword argument '{0}' already defined"\
1590 .format(argname)
1591 raise FyppFatalError(msg, fname, spans[ind + 1])
1592 kwargs[argname] = args[ind]
1593 else:
1594 posargs += args
1595
1596 return posargs, kwargs
1597
1598
1599 def _get_included_content(self, fname, spans, includefname, content):
1600 includefile = spans[0] is not None
1601 out = []
1602 if self._linenums and not self._diverted:
1603 if includefile or self._linenum_gfortran5:
1604 out += self._linenumdir(0, includefname, _LINENUM_NEW_FILE)
1605 else:
1606 out += self._linenumdir(0, includefname)
1607 outcont, ieval, peval = self._render(content)
1608 ieval = _shiftinds(ieval, len(out))
1609 out += outcont
1610 if self._linenums and not self._diverted and includefile:
1611 out += self._linenumdir(spans[0][1], fname, _LINENUM_RETURN_TO_FILE)
1612 return out, ieval, peval
1613
1614
1615 def _define_macro(self, fname, spans, name, argexpr, content):
1616 if argexpr is None:
1617 args = []
1618 defaults = {}
1619 varpos = None
1620 varkw = None
1621 else:
1622 # Try to create a lambda function with the argument expression
1623 self._evaluator.openscope()
1624 lambdaexpr = 'lambda ' + argexpr + ': None'
1625 try:
1626 func = self._evaluate(lambdaexpr, fname, spans[0][0])
1627 except Exception as exc:
1628 msg = "exception occurred when evaluating argument expression "\
1629 "'{0}'".format(argexpr)
1630 raise FyppFatalError(msg, fname, spans[0]) from exc
1631 self._evaluator.closescope()
1632 try:
1633 args, defaults, varpos, varkw = _get_callable_argspec(func)
1634 except Exception as exc:
1635 msg = "invalid argument expression '{0}'".format(argexpr)
1636 raise FyppFatalError(msg, fname, spans[0]) from exc
1637 named_args = args if varpos is None else args + [varpos]
1638 named_args = named_args if varkw is None else named_args + [varkw]
1639 for arg in named_args:
1640 if arg in _RESERVED_NAMES or arg.startswith(_RESERVED_PREFIX):
1641 msg = "invalid argument name '{0}'".format(arg)
1642 raise FyppFatalError(msg, fname, spans[0])
1643 result = ''
1644 try:
1645 macro = _Macro(
1646 name, fname, spans, args, defaults, varpos, varkw, content,
1647 self, self._evaluator, self._evaluator.localscope)
1648 self._define(name, macro)
1649 except Exception as exc:
1650 msg = "exception occurred when defining macro '{0}'"\
1651 .format(name)
1652 raise FyppFatalError(msg, fname, spans[0]) from exc
1653 if self._linenums and not self._diverted:
1654 result = self._linenumdir(spans[1][1], fname)
1655 return result
1656
1657
1658 def _define_variable(self, fname, span, name, valstr):
1659 result = ''
1660 try:
1661 if valstr is None:
1662 expr = None
1663 else:
1664 expr = self._evaluate(valstr, fname, span[0])
1665 self._define(name, expr)
1666 except Exception as exc:
1667 msg = "exception occurred when setting variable(s) '{0}' to '{1}'"\
1668 .format(name, valstr)
1669 raise FyppFatalError(msg, fname, span) from exc
1670 multiline = (span[0] != span[1])
1671 if self._linenums and not self._diverted and multiline:
1672 result = self._linenumdir(span[1], fname)
1673 return result
1674
1675
1676 def _delete_variable(self, fname, span, name):
1677 result = ''
1678 try:
1679 self._evaluator.undefine(name)
1680 except Exception as exc:
1681 msg = "exception occurred when deleting variable(s) '{0}'"\
1682 .format(name)
1683 raise FyppFatalError(msg, fname, span) from exc
1684 multiline = (span[0] != span[1])
1685 if self._linenums and not self._diverted and multiline:
1686 result = self._linenumdir(span[1], fname)
1687 return result
1688
1689
1690 def _add_global(self, fname, span, name):
1691 result = ''
1692 try:
1693 self._evaluator.addglobal(name)
1694 except Exception as exc:
1695 msg = "exception occurred when making variable(s) '{0}' global"\
1696 .format(name)
1697 raise FyppFatalError(msg, fname, span) from exc
1698 multiline = (span[0] != span[1])
1699 if self._linenums and not self._diverted and multiline:
1700 result = self._linenumdir(span[1], fname)
1701 return result
1702
1703
1704 def _get_comment(self, fname, span):
1705 if self._linenums and not self._diverted:
1706 return self._linenumdir(span[1], fname)
1707 return ''
1708
1709
1710 def _get_muted_content(self, fname, spans, content):
1711 self._render(content)
1712 if self._linenums and not self._diverted:
1713 return self._linenumdir(spans[-1][1], fname)
1714 return ''
1715
1716
1717 def _handle_stop(self, fname, span, msgstr):
1718 try:
1719 msg = str(self._evaluate(msgstr, fname, span[0]))
1720 except Exception as exc:
1721 msg = "exception occurred when evaluating stop message '{0}'"\
1722 .format(msgstr)
1723 raise FyppFatalError(msg, fname, span) from exc
1724 raise FyppStopRequest(msg, fname, span)
1725
1726
1727 def _handle_assert(self, fname, span, expr):
1728 result = ''
1729 try:
1730 cond = bool(self._evaluate(expr, fname, span[0]))
1731 except Exception as exc:
1732 msg = "exception occurred when evaluating assert condition '{0}'"\
1733 .format(expr)
1734 raise FyppFatalError(msg, fname, span) from exc
1735 if not cond:
1736 msg = "Assertion failed ('{0}')".format(expr)
1737 raise FyppStopRequest(msg, fname, span)
1738 if self._linenums and not self._diverted:
1739 result = self._linenumdir(span[1], fname)
1740 return result
1741
1742
1743 def _evaluate(self, expr, fname, linenr):
1744 self._update_predef_globals(fname, linenr)
1745 result = self._evaluator.evaluate(expr)
1746 self._update_predef_globals(fname, linenr)
1747 return result
1748
1749
1750 def _update_predef_globals(self, fname, linenr):
1751 fname = self._convert_file_path(fname)
1752 self._evaluator.updatelocals(
1753 _DATE_=time.strftime('%Y-%m-%d'), _TIME_=time.strftime('%H:%M:%S'),
1754 _THIS_FILE_=fname, _THIS_LINE_=linenr + 1)
1755 if not self._fixedposition:
1756 self._evaluator.updateglobals(_FILE_=fname, _LINE_=linenr + 1)
1757
1758
1759 def _define(self, var, value):
1760 self._evaluator.define(var, value)
1761
1762
1763 def _postprocess_eval_lines(self, output, eval_inds, eval_pos):
1764 ilastproc = -1
1765 for ieval, ind in enumerate(eval_inds):
1766 span, fname = eval_pos[ieval]
1767 if ind <= ilastproc:
1768 continue
1769 iprev, eolprev = self._find_last_eol(output, ind)
1770 inext, eolnext = self._find_next_eol(output, ind)
1771 curline = self._glue_line(output, ind, iprev, eolprev, inext,
1772 eolnext)
1773 output[iprev + 1:inext] = [''] * (inext - iprev - 1)
1774 output[ind] = self._postprocess_eval_line(curline, fname, span)
1775 ilastproc = inext
1776
1777
1778 @staticmethod
1779 def _find_last_eol(output, ind):
1780 'Find last newline before current position.'
1781 iprev = ind - 1
1782 while iprev >= 0:
1783 eolprev = output[iprev].rfind('\n')
1784 if eolprev != -1:
1785 break
1786 iprev -= 1
1787 else:
1788 iprev = 0
1789 eolprev = -1
1790 return iprev, eolprev
1791
1792
1793 @staticmethod
1794 def _find_next_eol(output, ind):
1795 'Find last newline before current position.'
1796 # find first eol after expr. evaluation
1797 inext = ind + 1
1798 while inext < len(output):
1799 eolnext = output[inext].find('\n')
1800 if eolnext != -1:
1801 break
1802 inext += 1
1803 else:
1804 inext = len(output) - 1
1805 eolnext = len(output[-1]) - 1
1806 return inext, eolnext
1807
1808
1809 @staticmethod
1810 def _glue_line(output, ind, iprev, eolprev, inext, eolnext):
1811 'Create line from parts between specified boundaries.'
1812 curline_parts = []
1813 if iprev != ind:
1814 curline_parts = [output[iprev][eolprev + 1:]]
1815 output[iprev] = output[iprev][:eolprev + 1]
1816 curline_parts.extend(output[iprev + 1:ind])
1817 curline_parts.extend(output[ind])
1818 curline_parts.extend(output[ind + 1:inext])
1819 if inext != ind:
1820 curline_parts.append(output[inext][:eolnext + 1])
1821 output[inext] = output[inext][eolnext + 1:]
1822 return ''.join(curline_parts)
1823
1824
1825 def _postprocess_eval_line(self, evalline, fname, span):
1826 lines = evalline.split('\n')
1827 # If line ended on '\n', last element is ''. We remove it and
1828 # add the trailing newline later manually.
1829 trailing_newline = (lines[-1] == '')
1830 if trailing_newline:
1831 del lines[-1]
1832 lnum = self._linenumdir(span[0], fname) if self._linenums else ''
1833 clnum = lnum if self._contlinenums else ''
1834 linenumsep = '\n' + lnum
1835 clinenumsep = '\n' + clnum
1836 foldedlines = [self._foldline(line) for line in lines]
1837 outlines = [clinenumsep.join(lines) for lines in foldedlines]
1838 result = linenumsep.join(outlines)
1839 # Add missing trailing newline
1840 if trailing_newline:
1841 trailing = '\n'
1842 if self._linenums:
1843 # Last line was folded, but no linenums were generated for
1844 # the continuation lines -> current line position is not
1845 # in sync with the one calculated from the last line number
1846 unsync = (
1847 len(foldedlines) and len(foldedlines[-1]) > 1
1848 and not self._contlinenums)
1849 # Eval directive in source consists of more than one line
1850 multiline = span[1] - span[0] > 1
1851 if unsync or multiline:
1852 # For inline eval directives span[0] == span[1]
1853 # -> next line is span[0] + 1 and not span[1] as for
1854 # line eval directives
1855 nextline = max(span[1], span[0] + 1)
1856 trailing += self._linenumdir(nextline, fname)
1857 else:
1858 trailing = ''
1859 return result + trailing
1860
1861
1862 def _foldline(self, line):
1863 if _COMMENTLINE_REGEXP.match(line) is None:
1864 return self._linefolder(line)
1865 return [line]
1866
1867
1868 class Evaluator:
1869
1870 '''Provides an isolated environment for evaluating Python expressions.
1871
1872 It restricts the builtins which can be used within this environment to a
1873 (hopefully safe) subset. Additionally it defines the functions which are
1874 provided by the preprocessor for the eval directives.
1875
1876 Args:
1877 env (dict, optional): Initial definitions for the environment, defaults
1878 to None.
1879 '''
1880
1881 # Restricted builtins working in all supported Python verions. Version
1882 # specific ones are added dynamically in _get_restricted_builtins().
1883 _RESTRICTED_BUILTINS = {
1884 'abs': builtins.abs,
1885 'all': builtins.all,
1886 'any': builtins.any,
1887 'bin': builtins.bin,
1888 'bool': builtins.bool,
1889 'bytearray': builtins.bytearray,
1890 'bytes': builtins.bytes,
1891 'chr': builtins.chr,
1892 'classmethod': builtins.classmethod,
1893 'complex': builtins.complex,
1894 'delattr': builtins.delattr,
1895 'dict': builtins.dict,
1896 'dir': builtins.dir,
1897 'divmod': builtins.divmod,
1898 'enumerate': builtins.enumerate,
1899 'filter': builtins.filter,
1900 'float': builtins.float,
1901 'format': builtins.format,
1902 'frozenset': builtins.frozenset,
1903 'getattr': builtins.getattr,
1904 'globals': builtins.globals,
1905 'hasattr': builtins.hasattr,
1906 'hash': builtins.hash,
1907 'hex': builtins.hex,
1908 'id': builtins.id,
1909 'int': builtins.int,
1910 'isinstance': builtins.isinstance,
1911 'issubclass': builtins.issubclass,
1912 'iter': builtins.iter,
1913 'len': builtins.len,
1914 'list': builtins.list,
1915 'locals': builtins.locals,
1916 'map': builtins.map,
1917 'max': builtins.max,
1918 'min': builtins.min,
1919 'next': builtins.next,
1920 'object': builtins.object,
1921 'oct': builtins.oct,
1922 'ord': builtins.ord,
1923 'pow': builtins.pow,
1924 'property': builtins.property,
1925 'range': builtins.range,
1926 'repr': builtins.repr,
1927 'reversed': builtins.reversed,
1928 'round': builtins.round,
1929 'set': builtins.set,
1930 'setattr': builtins.setattr,
1931 'slice': builtins.slice,
1932 'sorted': builtins.sorted,
1933 'staticmethod': builtins.staticmethod,
1934 'str': builtins.str,
1935 'sum': builtins.sum,
1936 'super': builtins.super,
1937 'tuple': builtins.tuple,
1938 'type': builtins.type,
1939 'vars': builtins.vars,
1940 'zip': builtins.zip,
1941 }
1942
1943
1944 def __init__(self, env=None):
1945
1946 # Global scope
1947 self._globals = env if env is not None else {}
1948
1949 # Local scope(s)
1950 self._locals = None
1951 self._locals_stack = []
1952
1953 # Variables which are references to entries in global scope
1954 self._globalrefs = None
1955 self._globalrefs_stack = []
1956
1957 # Current scope (globals + locals in all embedding and in current scope)
1958 self._scope = self._globals
1959
1960 # Turn on restricted mode
1961 self._restrict_builtins()
1962
1963
1964 def evaluate(self, expr):
1965 '''Evaluate a Python expression using the `eval()` builtin.
1966
1967 Args:
1968 expr (str): String represantion of the expression.
1969
1970 Return:
1971 Python object: Result of the expression evaluation.
1972 '''
1973 result = eval(expr, self._scope)
1974 return result
1975
1976
1977 def import_module(self, module):
1978 '''Import a module into the evaluator.
1979
1980 Note: Import only trustworthy modules! Module imports are global,
1981 therefore, importing a malicious module which manipulates other global
1982 modules could affect code behaviour outside of the Evaluator as well.
1983
1984 Args:
1985 module (str): Python module to import.
1986
1987 Raises:
1988 FyppFatalError: If module could not be imported.
1989
1990 '''
1991 rootmod = module.split('.', 1)[0]
1992 try:
1993 imported = __import__(module, self._scope)
1994 self.define(rootmod, imported)
1995 except Exception as exc:
1996 msg = "failed to import module '{0}'".format(module)
1997 raise FyppFatalError(msg) from exc
1998
1999
2000 def define(self, name, value):
2001 '''Define a Python entity.
2002
2003 Args:
2004 name (str): Name of the entity.
2005 value (Python object): Value of the entity.
2006
2007 Raises:
2008 FyppFatalError: If name starts with the reserved prefix or if it is
2009 a reserved name.
2010 '''
2011 varnames = self._get_variable_names(name)
2012 if len(varnames) == 1:
2013 value = (value,)
2014 elif len(varnames) != len(value):
2015 msg = 'value for tuple assignment has incompatible length'
2016 raise FyppFatalError(msg)
2017 for varname, varvalue in zip(varnames, value):
2018 self._check_variable_name(varname)
2019 if self._locals is None:
2020 self._globals[varname] = varvalue
2021 else:
2022 if varname in self._globalrefs:
2023 self._globals[varname] = varvalue
2024 else:
2025 self._locals[varname] = varvalue
2026 self._scope[varname] = varvalue
2027
2028
2029 def undefine(self, name):
2030 '''Undefine a Python entity.
2031
2032 Args:
2033 name (str): Name of the entity to undefine.
2034
2035 Raises:
2036 FyppFatalError: If name starts with the reserved prefix or if it is
2037 a reserved name.
2038 '''
2039 varnames = self._get_variable_names(name)
2040 for varname in varnames:
2041 self._check_variable_name(varname)
2042 deleted = False
2043 if self._locals is None:
2044 if varname in self._globals:
2045 del self._globals[varname]
2046 deleted = True
2047 else:
2048 if varname in self._locals:
2049 del self._locals[varname]
2050 del self._scope[varname]
2051 deleted = True
2052 elif varname in self._globalrefs and varname in self._globals:
2053 del self._globals[varname]
2054 del self._scope[varname]
2055 deleted = True
2056 if not deleted:
2057 msg = "lookup for an erasable instance of '{0}' failed"\
2058 .format(varname)
2059 raise FyppFatalError(msg)
2060
2061
2062 def addglobal(self, name):
2063 '''Define a given entity as global.
2064
2065 Args:
2066 name (str): Name of the entity to make global.
2067
2068 Raises:
2069 FyppFatalError: If entity name is invalid or if the current scope is
2070 a local scope and entity is already defined in it.
2071 '''
2072 varnames = self._get_variable_names(name)
2073 for varname in varnames:
2074 self._check_variable_name(varname)
2075 if self._locals is not None:
2076 if varname in self._locals:
2077 msg = "variable '{0}' already defined in local scope"\
2078 .format(varname)
2079 raise FyppFatalError(msg)
2080 self._globalrefs.add(varname)
2081
2082
2083 def updateglobals(self, **vardict):
2084 '''Update variables in the global scope.
2085
2086 This is a shortcut function to inject protected variables in the global
2087 scope without extensive checks (as in define()). Vardict must not
2088 contain any global entries which can be shadowed in local scopes
2089 (e.g. should only contain variables with forbidden prefix).
2090
2091 Args:
2092 **vardict: variable definitions.
2093
2094 '''
2095 self._scope.update(vardict)
2096 if self._locals is not None:
2097 self._globals.update(vardict)
2098
2099
2100 def updatelocals(self, **vardict):
2101 '''Update variables in the local scope.
2102
2103 This is a shortcut function to inject variables in the local scope
2104 without extensive checks (as in define()). Vardict must not contain any
2105 entries which have been made global via addglobal() before. In order to
2106 ensure this, updatelocals() should be called immediately after
2107 openscope(), or with variable names, which are warrantedly not globals
2108 (e.g variables starting with forbidden prefix)
2109
2110 Args:
2111 **vardict: variable definitions.
2112 '''
2113 self._scope.update(vardict)
2114 if self._locals is not None:
2115 self._locals.update(vardict)
2116
2117
2118 def openscope(self, customlocals=None):
2119 '''Opens a new (embedded) scope.
2120
2121 Args:
2122 customlocals (dict): By default, the locals of the embedding scope
2123 are visible in the new one. When this is not the desired
2124 behaviour a dictionary of customized locals can be passed,
2125 and those locals will become the only visible ones.
2126 '''
2127 self._locals_stack.append(self._locals)
2128 self._globalrefs_stack.append(self._globalrefs)
2129 if customlocals is not None:
2130 self._locals = customlocals.copy()
2131 elif self._locals is not None:
2132 self._locals = self._locals.copy()
2133 else:
2134 self._locals = {}
2135 self._globalrefs = set()
2136 self._scope = self._globals.copy()
2137 self._scope.update(self._locals)
2138
2139
2140 def closescope(self):
2141 '''Close scope and restore embedding scope.'''
2142 self._locals = self._locals_stack.pop(-1)
2143 self._globalrefs = self._globalrefs_stack.pop(-1)
2144 if self._locals is not None:
2145 self._scope = self._globals.copy()
2146 self._scope.update(self._locals)
2147 else:
2148 self._scope = self._globals
2149
2150
2151 @property
2152 def globalscope(self):
2153 'Dictionary of the global scope.'
2154 return self._globals
2155
2156
2157 @property
2158 def localscope(self):
2159 'Dictionary of the current local scope.'
2160 return self._locals
2161
2162
2163 def _restrict_builtins(self):
2164 builtindict = self._get_restricted_builtins()
2165 builtindict['__import__'] = self._func_import
2166 builtindict['defined'] = self._func_defined
2167 builtindict['setvar'] = self._func_setvar
2168 builtindict['getvar'] = self._func_getvar
2169 builtindict['delvar'] = self._func_delvar
2170 builtindict['globalvar'] = self._func_globalvar
2171 builtindict['__getargvalues'] = self._func_getargvalues
2172 self._globals['__builtins__'] = builtindict
2173
2174
2175 @classmethod
2176 def _get_restricted_builtins(cls):
2177 bidict = dict(cls._RESTRICTED_BUILTINS)
2178 return bidict
2179
2180
2181 @staticmethod
2182 def _get_variable_names(varexpr):
2183 lpar = varexpr.startswith('(')
2184 rpar = varexpr.endswith(')')
2185 if lpar != rpar:
2186 msg = "unbalanced parenthesis around variable varexpr(s) in '{0}'"\
2187 .format(varexpr)
2188 raise FyppFatalError(msg, None, None)
2189 if lpar:
2190 varexpr = varexpr[1:-1]
2191 varnames = [s.strip() for s in varexpr.split(',')]
2192 return varnames
2193
2194
2195 @staticmethod
2196 def _check_variable_name(varname):
2197 if varname.startswith(_RESERVED_PREFIX):
2198 msg = "Name '{0}' starts with reserved prefix '{1}'"\
2199 .format(varname, _RESERVED_PREFIX)
2200 raise FyppFatalError(msg, None, None)
2201 if varname in _RESERVED_NAMES:
2202 msg = "Name '{0}' is reserved and can not be redefined"\
2203 .format(varname)
2204 raise FyppFatalError(msg, None, None)
2205
2206
2207 def _func_defined(self, var):
2208 defined = var in self._scope
2209 return defined
2210
2211
2212 def _func_import(self, name, *_, **__):
2213 module = self._scope.get(name, None)
2214 if module is not None and isinstance(module, types.ModuleType):
2215 return module
2216 msg = "Import of module '{0}' via '__import__' not allowed".format(name)
2217 raise ImportError(msg)
2218
2219
2220 def _func_setvar(self, *namesvalues):
2221 if len(namesvalues) % 2:
2222 msg = 'setvar function needs an even number of arguments'
2223 raise FyppFatalError(msg)
2224 for ind in range(0, len(namesvalues), 2):
2225 self.define(namesvalues[ind], namesvalues[ind + 1])
2226
2227
2228 def _func_getvar(self, name, defvalue=None):
2229 if name in self._scope:
2230 return self._scope[name]
2231 return defvalue
2232
2233
2234 def _func_delvar(self, *names):
2235 for name in names:
2236 self.undefine(name)
2237
2238
2239 def _func_globalvar(self, *names):
2240 for name in names:
2241 self.addglobal(name)
2242
2243
2244 @staticmethod
2245 def _func_getargvalues(*args, **kwargs):
2246 return list(args), kwargs
2247
2248
2249
2250 class _Macro:
2251
2252 '''Represents a user defined macro.
2253
2254 This object should only be initiatied by a Renderer instance, as it
2255 needs access to Renderers internal variables and methods.
2256
2257 Args:
2258 name (str): Name of the macro.
2259 fname (str): The file where the macro was defined.
2260 spans (str): Line spans of macro definition.
2261 argnames (list of str): Macro dummy arguments.
2262 varpos (str): Name of variable positional argument or None.
2263 varkw (str): Name of variable keyword argument or None.
2264 content (list): Content of the macro as tree.
2265 renderer (Renderer): Renderer to use for evaluating macro content.
2266 localscope (dict): Dictionary with local variables, which should be used
2267 the local scope, when the macro is called. Default: None (empty
2268 local scope).
2269 '''
2270
2271 def __init__(self, name, fname, spans, argnames, defaults, varpos, varkw,
2272 content, renderer, evaluator, localscope=None):
2273 self._name = name
2274 self._fname = fname
2275 self._spans = spans
2276 self._argnames = argnames
2277 self._defaults = defaults
2278 self._varpos = varpos
2279 self._varkw = varkw
2280 self._content = content
2281 self._renderer = renderer
2282 self._evaluator = evaluator
2283 self._localscope = localscope if localscope is not None else {}
2284
2285
2286 def __call__(self, *args, **keywords):
2287 argdict = self._process_arguments(args, keywords)
2288 self._evaluator.openscope(customlocals=self._localscope)
2289 self._evaluator.updatelocals(**argdict)
2290 output = self._renderer.render(self._content, divert=True,
2291 fixposition=True)
2292 self._evaluator.closescope()
2293 if output.endswith('\n'):
2294 return output[:-1]
2295 return output
2296
2297
2298 def _process_arguments(self, args, keywords):
2299 kwdict = dict(keywords)
2300 argdict = {}
2301 nargs = min(len(args), len(self._argnames))
2302 for iarg in range(nargs):
2303 argdict[self._argnames[iarg]] = args[iarg]
2304 if nargs < len(args):
2305 if self._varpos is None:
2306 msg = "macro '{0}' called with too many positional arguments "\
2307 "(expected: {1}, received: {2})"\
2308 .format(self._name, len(self._argnames), len(args))
2309 raise FyppFatalError(msg, self._fname, self._spans[0])
2310 else:
2311 argdict[self._varpos] = list(args[nargs:])
2312 elif self._varpos is not None:
2313 argdict[self._varpos] = []
2314 for argname in self._argnames[:nargs]:
2315 if argname in kwdict:
2316 msg = "got multiple values for argument '{0}'".format(argname)
2317 raise FyppFatalError(msg, self._fname, self._spans[0])
2318 if nargs < len(self._argnames):
2319 for argname in self._argnames[nargs:]:
2320 if argname in kwdict:
2321 argdict[argname] = kwdict.pop(argname)
2322 elif argname in self._defaults:
2323 argdict[argname] = self._defaults[argname]
2324 else:
2325 msg = "macro '{0}' called without mandatory positional "\
2326 "argument '{1}'".format(self._name, argname)
2327 raise FyppFatalError(msg, self._fname, self._spans[0])
2328 if kwdict and self._varkw is None:
2329 kwstr = "', '".join(kwdict.keys())
2330 msg = "macro '{0}' called with unknown keyword argument(s) '{1}'"\
2331 .format(self._name, kwstr)
2332 raise FyppFatalError(msg, self._fname, self._spans[0])
2333 if self._varkw is not None:
2334 argdict[self._varkw] = kwdict
2335 return argdict
2336
2337
2338
2339 class Processor:
2340
2341 '''Connects various objects with each other to create a processor.
2342
2343 Args:
2344 parser (Parser, optional): Parser to use for parsing text. If None
2345 (default), `Parser()` is used.
2346 builder (Builder, optional): Builder to use for building the tree
2347 representation of the text. If None (default), `Builder()` is used.
2348 renderer (Renderer, optional): Renderer to use for rendering the
2349 output. If None (default), `Renderer()` is used with a default
2350 Evaluator().
2351 evaluator (Evaluator, optional): Evaluator to use for evaluating Python
2352 expressions. If None (default), `Evaluator()` is used.
2353 '''
2354
2355 def __init__(self, parser=None, builder=None, renderer=None,
2356 evaluator=None):
2357 self._parser = Parser() if parser is None else parser
2358 self._builder = Builder() if builder is None else builder
2359 if renderer is None:
2360 evaluator = Evaluator() if evaluator is None else evaluator
2361 self._renderer = Renderer(evaluator)
2362 else:
2363 self._renderer = renderer
2364
2365 self._parser.handle_include = self._builder.handle_include
2366 self._parser.handle_endinclude = self._builder.handle_endinclude
2367 self._parser.handle_if = self._builder.handle_if
2368 self._parser.handle_else = self._builder.handle_else
2369 self._parser.handle_elif = self._builder.handle_elif
2370 self._parser.handle_endif = self._builder.handle_endif
2371 self._parser.handle_eval = self._builder.handle_eval
2372 self._parser.handle_text = self._builder.handle_text
2373 self._parser.handle_def = self._builder.handle_def
2374 self._parser.handle_enddef = self._builder.handle_enddef
2375 self._parser.handle_set = self._builder.handle_set
2376 self._parser.handle_del = self._builder.handle_del
2377 self._parser.handle_global = self._builder.handle_global
2378 self._parser.handle_for = self._builder.handle_for
2379 self._parser.handle_endfor = self._builder.handle_endfor
2380 self._parser.handle_call = self._builder.handle_call
2381 self._parser.handle_nextarg = self._builder.handle_nextarg
2382 self._parser.handle_endcall = self._builder.handle_endcall
2383 self._parser.handle_comment = self._builder.handle_comment
2384 self._parser.handle_mute = self._builder.handle_mute
2385 self._parser.handle_endmute = self._builder.handle_endmute
2386 self._parser.handle_stop = self._builder.handle_stop
2387 self._parser.handle_assert = self._builder.handle_assert
2388
2389
2390 def process_file(self, fname):
2391 '''Processeses a file.
2392
2393 Args:
2394 fname (str): Name of the file to process.
2395
2396 Returns:
2397 str: Processed content.
2398 '''
2399 self._parser.parsefile(fname)
2400 return self._render()
2401
2402
2403 def process_text(self, txt):
2404 '''Processes a string.
2405
2406 Args:
2407 txt (str): Text to process.
2408
2409 Returns:
2410 str: Processed content.
2411 '''
2412 self._parser.parse(txt)
2413 return self._render()
2414
2415
2416 def _render(self):
2417 output = self._renderer.render(self._builder.tree)
2418 self._builder.reset()
2419 return ''.join(output)
2420
2421
2422 class Fypp:
2423
2424 '''Fypp preprocessor.
2425
2426 You can invoke it like ::
2427
2428 tool = fypp.Fypp()
2429 tool.process_file('file.in', 'file.out')
2430
2431 to initialize Fypp with default options, process `file.in` and write the
2432 result to `file.out`. If the input should be read from a string, the
2433 ``process_text()`` method can be used::
2434
2435 tool = fypp.Fypp()
2436 output = tool.process_text('#:if DEBUG > 0\\nprint *, "DEBUG"\\n#:endif\\n')
2437
2438 If you want to fine tune Fypps behaviour, pass a customized `FyppOptions`_
2439 instance at initialization::
2440
2441 options = fypp.FyppOptions()
2442 options.fixed_format = True
2443 tool = fypp.Fypp(options)
2444
2445 Alternatively, you can use the command line parser ``optparse.OptionParser``
2446 to set options for Fypp. The function ``get_option_parser()`` returns you a
2447 default option parser. You can then use its ``parse_args()`` method to
2448 obtain settings by reading the command line arguments::
2449
2450 optparser = fypp.get_option_parser()
2451 options, leftover = optparser.parse_args()
2452 tool = fypp.Fypp(options)
2453
2454 The command line options can also be passed directly as a list when
2455 calling ``parse_args()``::
2456
2457 args = ['-DDEBUG=0', 'input.fpp', 'output.f90']
2458 optparser = fypp.get_option_parser()
2459 options, leftover = optparser.parse_args(args=args)
2460 tool = fypp.Fypp(options)
2461
2462 For even more fine-grained control over how Fypp works, you can pass in
2463 custom factory methods that handle construction of the evaluator, parser,
2464 builder and renderer components. These factory methods must have the same
2465 signature as the corresponding component's constructor. As an example of
2466 using a builder that's customized by subclassing::
2467
2468 class MyBuilder(fypp.Builder):
2469
2470 def __init__(self):
2471 super().__init__()
2472 ...additional initialization...
2473
2474 tool = fypp.Fypp(options, builder_factory=MyBuilder)
2475
2476
2477 Args:
2478 options (object): Object containing the settings for Fypp. You typically
2479 would pass a customized `FyppOptions`_ instance or an
2480 ``optparse.Values`` object as returned by the option parser. If not
2481 present, the default settings in `FyppOptions`_ are used.
2482 evaluator_factory (function): Factory function that returns an Evaluator
2483 object. Its call signature must match that of the Evaluator
2484 constructor. If not present, ``Evaluator`` is used.
2485 parser_factory (function): Factory function that returns a Parser
2486 object. Its call signature must match that of the Parser
2487 constructor. If not present, ``Parser`` is used.
2488 builder_factory (function): Factory function that returns a Builder
2489 object. Its call signature must match that of the Builder
2490 constructor. If not present, ``Builder`` is used.
2491 renderer_factory (function): Factory function that returns a Renderer
2492 object. Its call signature must match that of the Renderer
2493 constructor. If not present, ``Renderer`` is used.
2494 '''
2495
2496 def __init__(self, options=None, evaluator_factory=Evaluator,
2497 parser_factory=Parser, builder_factory=Builder,
2498 renderer_factory=Renderer):
2499 syspath = self._get_syspath_without_scriptdir()
2500 self._adjust_syspath(syspath)
2501 if options is None:
2502 options = FyppOptions()
2503 if inspect.signature(evaluator_factory) == inspect.signature(Evaluator):
2504 evaluator = evaluator_factory()
2505 else:
2506 raise FyppFatalError('evaluator_factory has incorrect signature')
2507 self._encoding = options.encoding
2508 if options.modules:
2509 self._import_modules(options.modules, evaluator, syspath,
2510 options.moduledirs)
2511 if options.defines:
2512 self._apply_definitions(options.defines, evaluator)
2513 if inspect.signature(parser_factory) == inspect.signature(Parser):
2514 parser = parser_factory(includedirs=options.includes,
2515 encoding=self._encoding)
2516 else:
2517 raise FyppFatalError('parser_factory has incorrect signature')
2518 if inspect.signature(builder_factory) == inspect.signature(Builder):
2519 builder = builder_factory()
2520 else:
2521 raise FyppFatalError('builder_factory has incorrect signature')
2522
2523 fixed_format = options.fixed_format
2524 linefolding = not options.no_folding
2525 if linefolding:
2526 folding = 'brute' if fixed_format else options.folding_mode
2527 linelength = 72 if fixed_format else options.line_length
2528 indentation = 5 if fixed_format else options.indentation
2529 prefix = '&'
2530 suffix = '' if fixed_format else '&'
2531 linefolder = FortranLineFolder(linelength, indentation, folding,
2532 prefix, suffix)
2533 else:
2534 linefolder = DummyLineFolder()
2535 linenums = options.line_numbering
2536 contlinenums = (options.line_numbering_mode != 'nocontlines')
2537 self._create_parent_folder = options.create_parent_folder
2538 if inspect.signature(renderer_factory) == inspect.signature(Renderer):
2539 renderer = renderer_factory(
2540 evaluator, linenums=linenums, contlinenums=contlinenums,
2541 linenumformat=options.line_marker_format, linefolder=linefolder,
2542 filevarroot=options.file_var_root)
2543 else:
2544 raise FyppFatalError('renderer_factory has incorrect signature')
2545 self._preprocessor = Processor(parser, builder, renderer)
2546
2547
2548 def process_file(self, infile, outfile=None):
2549 '''Processes input file and writes result to output file.
2550
2551 Args:
2552 infile (str): Name of the file to read and process. If its value is
2553 '-', input is read from stdin.
2554 outfile (str, optional): Name of the file to write the result to.
2555 If its value is '-', result is written to stdout. If not
2556 present, result will be returned as string.
2557 env (dict, optional): Additional definitions for the evaluator.
2558
2559 Returns:
2560 str: Result of processed input, if no outfile was specified.
2561 '''
2562 infile = STDIN if infile == '-' else infile
2563 output = self._preprocessor.process_file(infile)
2564 if outfile is None:
2565 return output
2566 if outfile == '-':
2567 outfile = sys.stdout
2568 else:
2569 outfile = _open_output_file(outfile, self._encoding,
2570 self._create_parent_folder)
2571 outfile.write(output)
2572 if outfile != sys.stdout:
2573 outfile.close()
2574 return None
2575
2576
2577 def process_text(self, txt):
2578 '''Processes a string.
2579
2580 Args:
2581 txt (str): String to process.
2582 env (dict, optional): Additional definitions for the evaluator.
2583
2584 Returns:
2585 str: Processed content.
2586 '''
2587 return self._preprocessor.process_text(txt)
2588
2589
2590 @staticmethod
2591 def _apply_definitions(defines, evaluator):
2592 for define in defines:
2593 words = define.split('=', 1)
2594 name = words[0]
2595 value = None
2596 if len(words) > 1:
2597 try:
2598 value = evaluator.evaluate(words[1])
2599 except Exception as exc:
2600 msg = "exception at evaluating '{0}' in definition for " \
2601 "'{1}'".format(words[1], name)
2602 raise FyppFatalError(msg) from exc
2603 evaluator.define(name, value)
2604
2605
2606 def _import_modules(self, modules, evaluator, syspath, moduledirs):
2607 lookuppath = []
2608 if moduledirs is not None:
2609 lookuppath += [os.path.abspath(moddir) for moddir in moduledirs]
2610 lookuppath.append(os.path.abspath('.'))
2611 lookuppath += syspath
2612 self._adjust_syspath(lookuppath)
2613 for module in modules:
2614 evaluator.import_module(module)
2615 self._adjust_syspath(syspath)
2616
2617
2618 @staticmethod
2619 def _get_syspath_without_scriptdir():
2620 '''Remove the folder of the fypp binary from the search path'''
2621 syspath = list(sys.path)
2622 scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
2623 if os.path.abspath(syspath[0]) == scriptdir:
2624 del syspath[0]
2625 return syspath
2626
2627
2628 @staticmethod
2629 def _adjust_syspath(syspath):
2630 sys.path = syspath
2631
2632
2633 class FyppOptions(optparse.Values):
2634
2635 '''Container for Fypp options with default values.
2636
2637 Attributes:
2638 defines (list of str): List of variable definitions in the form of
2639 'VARNAME=VALUE'. Default: []
2640 includes (list of str): List of paths to search when looking for include
2641 files. Default: []
2642 line_numbering (bool): Whether line numbering directives should appear
2643 in the output. Default: False
2644 line_numbering_mode (str): Line numbering mode 'full' or 'nocontlines'.
2645 Default: 'full'.
2646 line_marker_format (str): Line marker format. Currently 'std',
2647 'cpp' and 'gfortran5' are supported, where 'std' emits ``#line``
2648 pragmas similar to standard tools, 'cpp' produces line directives as
2649 emitted by GNU cpp, and 'gfortran5' cpp line directives with a
2650 workaround for a bug introduced in GFortran 5. Default: 'cpp'.
2651 line_length (int): Length of output lines. Default: 132.
2652 folding_mode (str): Folding mode 'smart', 'simple' or 'brute'. Default:
2653 'smart'.
2654 no_folding (bool): Whether folding should be suppressed. Default: False.
2655 indentation (int): Indentation in continuation lines. Default: 4.
2656 modules (list of str): Modules to import at initialization. Default: [].
2657 moduledirs (list of str): Module lookup directories for importing user
2658 specified modules. The specified paths are looked up *before* the
2659 standard module locations in sys.path.
2660 fixed_format (bool): Whether input file is in fixed format.
2661 Default: False.
2662 encoding (str): Character encoding for reading/writing files. Allowed
2663 values are Pythons codec identifiers, e.g. 'ascii', 'utf-8', etc.
2664 Default: 'utf-8'. Reading from stdin and writing to stdout is always
2665 encoded according to the current locale and is not affected by this
2666 setting.
2667 create_parent_folder (bool): Whether the parent folder for the output
2668 file should be created if it does not exist. Default: False.
2669 '''
2670
2671 def __init__(self):
2672 optparse.Values.__init__(self)
2673 self.defines = []
2674 self.includes = []
2675 self.line_numbering = False
2676 self.line_numbering_mode = 'full'
2677 self.line_marker_format = 'cpp'
2678 self.line_length = 132
2679 self.folding_mode = 'smart'
2680 self.no_folding = False
2681 self.indentation = 4
2682 self.modules = []
2683 self.moduledirs = []
2684 self.fixed_format = False
2685 self.encoding = 'utf-8'
2686 self.create_parent_folder = False
2687 self.file_var_root = None
2688
2689
2690 class FortranLineFolder:
2691
2692 '''Implements line folding with Fortran continuation lines.
2693
2694 Args:
2695 maxlen (int, optional): Maximal line length (default: 132).
2696 indent (int, optional): Indentation for continuation lines (default: 4).
2697 method (str, optional): Folding method with following options:
2698
2699 * ``brute``: folding with maximal length of continuation lines,
2700 * ``simple``: indents with respect of indentation of first line,
2701 * ``smart``: like ``simple``, but tries to fold at whitespaces.
2702
2703 prefix (str, optional): String to use at the beginning of a continuation
2704 line (default: '&').
2705 suffix (str, optional): String to use at the end of the line preceding
2706 a continuation line (default: '&')
2707 '''
2708
2709 def __init__(self, maxlen=132, indent=4, method='smart', prefix='&',
2710 suffix='&'):
2711 # Line length should be long enough that contintuation lines can host at
2712 # east one character apart of indentation and two continuation signs
2713 minmaxlen = indent + len(prefix) + len(suffix) + 1
2714 if maxlen < minmaxlen:
2715 msg = 'Maximal line length less than {0} when using an indentation'\
2716 ' of {1}'.format(minmaxlen, indent)
2717 raise FyppFatalError(msg)
2718 self._maxlen = maxlen
2719 self._indent = indent
2720 self._prefix = ' ' * self._indent + prefix
2721 self._suffix = suffix
2722 if method not in ['brute', 'smart', 'simple']:
2723 raise FyppFatalError('invalid folding type')
2724 if method == 'brute':
2725 self._inherit_indent = False
2726 self._fold_position_finder = self._get_maximal_fold_pos
2727 elif method == 'simple':
2728 self._inherit_indent = True
2729 self._fold_position_finder = self._get_maximal_fold_pos
2730 elif method == 'smart':
2731 self._inherit_indent = True
2732 self._fold_position_finder = self._get_smart_fold_pos
2733
2734
2735 def __call__(self, line):
2736 '''Folds a line.
2737
2738 Can be directly called to return the list of folded lines::
2739
2740 linefolder = FortranLineFolder(maxlen=10)
2741 linefolder(' print *, "some Fortran line"')
2742
2743 Args:
2744 line (str): Line to fold.
2745
2746 Returns:
2747 list of str: Components of folded line. They should be
2748 assembled via ``\\n.join()`` to obtain the string
2749 representation.
2750 '''
2751 if self._maxlen < 0 or len(line) <= self._maxlen:
2752 return [line]
2753 if self._inherit_indent:
2754 indent = len(line) - len(line.lstrip())
2755 prefix = ' ' * indent + self._prefix
2756 else:
2757 indent = 0
2758 prefix = self._prefix
2759 suffix = self._suffix
2760 return self._split_line(line, self._maxlen, prefix, suffix,
2761 self._fold_position_finder)
2762
2763
2764 @staticmethod
2765 def _split_line(line, maxlen, prefix, suffix, fold_position_finder):
2766 # length of continuation lines with 1 or two continuation chars.
2767 maxlen1 = maxlen - len(prefix)
2768 maxlen2 = maxlen1 - len(suffix)
2769 start = 0
2770 end = fold_position_finder(line, start, maxlen - len(suffix))
2771 result = [line[start:end] + suffix]
2772 while end < len(line) - maxlen1:
2773 start = end
2774 end = fold_position_finder(line, start, start + maxlen2)
2775 result.append(prefix + line[start:end] + suffix)
2776 result.append(prefix + line[end:])
2777 return result
2778
2779
2780 @staticmethod
2781 def _get_maximal_fold_pos(_, __, end):
2782 return end
2783
2784
2785 @staticmethod
2786 def _get_smart_fold_pos(line, start, end):
2787 linelen = end - start
2788 ispace = line.rfind(' ', start, end)
2789 # The space we waste for smart folding should be max. 1/3rd of the line
2790 if ispace != -1 and ispace >= start + (2 * linelen) // 3:
2791 return ispace
2792 return end
2793
2794
2795 class DummyLineFolder:
2796
2797 '''Implements a dummy line folder returning the line unaltered.'''
2798
2799 def __call__(self, line):
2800 '''Returns the entire line without any folding.
2801
2802 Returns:
2803 list of str: Components of folded line. They should be
2804 assembled via ``\\n.join()`` to obtain the string
2805 representation.
2806 '''
2807 return [line]
2808
2809
2810 def get_option_parser():
2811 '''Returns an option parser for the Fypp command line tool.
2812
2813 Returns:
2814 OptionParser: Parser which can create an optparse.Values object with
2815 Fypp settings based on command line arguments.
2816 '''
2817 defs = FyppOptions()
2818 fypp_name = 'fypp'
2819 fypp_desc = 'Preprocesses source code with Fypp directives. The input is '\
2820 'read from INFILE (default: \'-\', stdin) and written to '\
2821 'OUTFILE (default: \'-\', stdout).'
2822 fypp_version = fypp_name + ' ' + VERSION
2823 usage = '%prog [options] [INFILE] [OUTFILE]'
2824 parser = optparse.OptionParser(prog=fypp_name, description=fypp_desc,
2825 version=fypp_version, usage=usage)
2826
2827 msg = 'define variable, value is interpreted as ' \
2828 'Python expression (e.g \'-DDEBUG=1\' sets DEBUG to the ' \
2829 'integer 1) or set to None if omitted'
2830 parser.add_option('-D', '--define', action='append', dest='defines',
2831 metavar='VAR[=VALUE]', default=defs.defines, help=msg)
2832
2833 msg = 'add directory to the search paths for include files'
2834 parser.add_option('-I', '--include', action='append', dest='includes',
2835 metavar='INCDIR', default=defs.includes, help=msg)
2836
2837 msg = 'import a python module at startup (import only trustworthy modules '\
2838 'as they have access to an **unrestricted** Python environment!)'
2839 parser.add_option('-m', '--module', action='append', dest='modules',
2840 metavar='MOD', default=defs.modules, help=msg)
2841
2842 msg = 'directory to be searched for user imported modules before '\
2843 'looking up standard locations in sys.path'
2844 parser.add_option('-M', '--module-dir', action='append',
2845 dest='moduledirs', metavar='MODDIR',
2846 default=defs.moduledirs, help=msg)
2847
2848 msg = 'emit line numbering markers'
2849 parser.add_option('-n', '--line-numbering', action='store_true',
2850 dest='line_numbering', default=defs.line_numbering,
2851 help=msg)
2852
2853 msg = 'line numbering mode, \'full\' (default): line numbering '\
2854 'markers generated whenever source and output lines are out '\
2855 'of sync, \'nocontlines\': line numbering markers omitted '\
2856 'for continuation lines'
2857 parser.add_option('-N', '--line-numbering-mode', metavar='MODE',
2858 choices=['full', 'nocontlines'],
2859 default=defs.line_numbering_mode,
2860 dest='line_numbering_mode', help=msg)
2861
2862 msg = 'line numbering marker format, currently \'std\', \'cpp\' and '\
2863 '\'gfortran5\' are supported, where \'std\' emits #line pragmas '\
2864 'similar to standard tools, \'cpp\' produces line directives as '\
2865 'emitted by GNU cpp, and \'gfortran5\' cpp line directives with a '\
2866 'workaround for a bug introduced in GFortran 5. Default: \'cpp\'.'
2867 parser.add_option('--line-marker-format', metavar='FMT',
2868 choices=['cpp', 'gfortran5', 'std'],
2869 dest='line_marker_format',
2870 default=defs.line_marker_format, help=msg)
2871
2872 msg = 'maximal line length (default: 132), lines modified by the '\
2873 'preprocessor are folded if becoming longer'
2874 parser.add_option('-l', '--line-length', type=int, metavar='LEN',
2875 dest='line_length', default=defs.line_length, help=msg)
2876
2877 msg = 'line folding mode, \'smart\' (default): indentation context '\
2878 'and whitespace aware, \'simple\': indentation context aware, '\
2879 '\'brute\': mechnical folding'
2880 parser.add_option('-f', '--folding-mode', metavar='MODE',
2881 choices=['smart', 'simple', 'brute'], dest='folding_mode',
2882 default=defs.folding_mode, help=msg)
2883
2884 msg = 'suppress line folding'
2885 parser.add_option('-F', '--no-folding', action='store_true',
2886 dest='no_folding', default=defs.no_folding, help=msg)
2887
2888 msg = 'indentation to use for continuation lines (default 4)'
2889 parser.add_option('--indentation', type=int, metavar='IND',
2890 dest='indentation', default=defs.indentation, help=msg)
2891
2892 msg = 'produce fixed format output (any settings for options '\
2893 '--line-length, --folding-method and --indentation are ignored)'
2894 parser.add_option('--fixed-format', action='store_true',
2895 dest='fixed_format', default=defs.fixed_format, help=msg)
2896
2897 msg = 'character encoding for reading/writing files. Default: \'utf-8\'. '\
2898 'Note: reading from stdin and writing to stdout is encoded '\
2899 'according to the current locale and is not affected by this setting.'
2900 parser.add_option('--encoding', metavar='ENC', default=defs.encoding,
2901 help=msg)
2902
2903 msg = 'create parent folders of the output file if they do not exist'
2904 parser.add_option('-p', '--create-parents', action='store_true',
2905 dest='create_parent_folder',
2906 default=defs.create_parent_folder, help=msg)
2907
2908 msg = 'in variables _FILE_ and _THIS_FILE_, use relative paths with DIR '\
2909 'as root directory. Note: the input file and all included files '\
2910 'must be in DIR or in a directory below.'
2911 parser.add_option('--file-var-root', metavar='DIR', dest='file_var_root',
2912 default=defs.file_var_root, help=msg)
2913
2914 return parser
2915
2916
2917 def run_fypp():
2918 '''Run the Fypp command line tool.'''
2919 options = FyppOptions()
2920 optparser = get_option_parser()
2921 opts, leftover = optparser.parse_args(values=options)
2922 infile = leftover[0] if len(leftover) > 0 else '-'
2923 outfile = leftover[1] if len(leftover) > 1 else '-'
2924 try:
2925 tool = Fypp(opts)
2926 tool.process_file(infile, outfile)
2927 except FyppStopRequest as exc:
2928 sys.stderr.write(_formatted_exception(exc))
2929 sys.exit(USER_ERROR_EXIT_CODE)
2930 except FyppFatalError as exc:
2931 sys.stderr.write(_formatted_exception(exc))
2932 sys.exit(ERROR_EXIT_CODE)
2933
2934
2935 def linenumdir_cpp(linenr, fname, flag=None):
2936 """Returns a GNU cpp style line directive.
2937
2938 Args:
2939 linenr (int): Line nr (starting with zero).
2940 fname (str): File name.
2941 flag (str): Optional flag to print after the directive
2942
2943 Returns:
2944 Line number directive as string.
2945 """
2946 if flag is None:
2947 return '# {0} "{1}"\n'.format(linenr + 1, fname)
2948 return '# {0} "{1}" {2}\n'.format(linenr + 1, fname, flag)
2949
2950
2951 def linenumdir_std(linenr, fname, flag=None):
2952 """Returns standard #line pragma styled line directive.
2953
2954 Args:
2955 linenr (int): Line nr (starting with zero).
2956 fname (str): File name.
2957 flag (str): Optional flag to print after the directive. Note, this
2958 option is only there to be API compatible with linenumdir_cpp(),
2959 but is ignored otherwise, since #line pragmas do not allow for
2960 extra file opening/closing flags.
2961
2962 Returns:
2963 Line number directive as string.
2964 """
2965 return "#line {0} \"{1}\"\n".format(linenr + 1, fname)
2966
2967
2968 def _shiftinds(inds, shift):
2969 return [ind + shift for ind in inds]
2970
2971
2972 def _open_input_file(inpfile, encoding=None):
2973 try:
2974 inpfp = io.open(inpfile, 'r', encoding=encoding)
2975 except IOError as exc:
2976 msg = "Failed to open file '{0}' for read".format(inpfile)
2977 raise FyppFatalError(msg) from exc
2978 return inpfp
2979
2980
2981 def _open_output_file(outfile, encoding=None, create_parents=False):
2982 if create_parents:
2983 parentdir = os.path.abspath(os.path.dirname(outfile))
2984 if not os.path.exists(parentdir):
2985 try:
2986 os.makedirs(parentdir)
2987 except OSError as exc:
2988 if exc.errno != errno.EEXIST:
2989 msg = "Folder '{0}' can not be created"\
2990 .format(parentdir)
2991 raise FyppFatalError(msg) from exc
2992 try:
2993 outfp = io.open(outfile, 'w', encoding=encoding)
2994 except IOError as exc:
2995 msg = "Failed to open file '{0}' for write".format(outfile)
2996 raise FyppFatalError(msg) from exc
2997 return outfp
2998
2999
3000 # Signature objects are available from Python 3.3 (and deprecated from 3.5)
3001 def _get_callable_argspec(func):
3002 sig = inspect.signature(func)
3003 args = []
3004 defaults = {}
3005 varpos = None
3006 varkw = None
3007 for param in sig.parameters.values():
3008 if param.kind == param.POSITIONAL_OR_KEYWORD:
3009 args.append(param.name)
3010 if param.default != param.empty:
3011 defaults[param.name] = param.default
3012 elif param.kind == param.VAR_POSITIONAL:
3013 varpos = param.name
3014 elif param.kind == param.VAR_KEYWORD:
3015 varkw = param.name
3016 else:
3017 msg = "argument '{0}' has invalid argument type".format(param.name)
3018 raise FyppFatalError(msg)
3019 return args, defaults, varpos, varkw
3020
3021
3022
3023 def _blank_match(match):
3024 size = match.end() - match.start()
3025 return " " * size
3026
3027
3028 def _argsplit_fortran(argtxt):
3029 txt = _INLINE_EVAL_REGION_REGEXP.sub(_blank_match, argtxt)
3030 splitpos = [-1]
3031 quote = None
3032 closing_brace_stack = []
3033 closing_brace = None
3034 for ind, char in enumerate(txt):
3035 if quote:
3036 if char == quote:
3037 quote = None
3038 continue
3039 if char in _QUOTES_FORTRAN:
3040 quote = char
3041 continue
3042 if char in _OPENING_BRACKETS_FORTRAN:
3043 closing_brace_stack.append(closing_brace)
3044 ind = _OPENING_BRACKETS_FORTRAN.index(char)
3045 closing_brace = _CLOSING_BRACKETS_FORTRAN[ind]
3046 continue
3047 if char in _CLOSING_BRACKETS_FORTRAN:
3048 if char == closing_brace:
3049 closing_brace = closing_brace_stack.pop(-1)
3050 continue
3051 else:
3052 msg = "unexpected closing delimiter '{0}' in expression '{1}' "\
3053 "at position {2}".format(char, argtxt, ind + 1)
3054 raise FyppFatalError(msg)
3055 if not closing_brace and char == _ARGUMENT_SPLIT_CHAR_FORTRAN:
3056 splitpos.append(ind)
3057 if quote or closing_brace:
3058 msg = "open quotes or brackets in expression '{0}'".format(argtxt)
3059 raise FyppFatalError(msg)
3060 splitpos.append(len(txt))
3061 fragments = [argtxt[start + 1 : end]
3062 for start, end in zip(splitpos, splitpos[1:])]
3063 return fragments
3064
3065
3066 def _formatted_exception(exc):
3067 error_header_formstr = '{file}:{line}: '
3068 error_body_formstr = 'error: {errormsg} [{errorclass}]'
3069 if not isinstance(exc, FyppError):
3070 return error_body_formstr.format(
3071 errormsg=str(exc), errorclass=exc.__class__.__name__)
3072 out = []
3073 if exc.fname is not None:
3074 if exc.span[1] > exc.span[0] + 1:
3075 line = '{0}-{1}'.format(exc.span[0] + 1, exc.span[1])
3076 else:
3077 line = '{0}'.format(exc.span[0] + 1)
3078 out.append(error_header_formstr.format(file=exc.fname, line=line))
3079 out.append(error_body_formstr.format(errormsg=exc.msg,
3080 errorclass=exc.__class__.__name__))
3081 if exc.__cause__ is not None:
3082 out.append('\n' + _formatted_exception(exc.__cause__))
3083 out.append('\n')
3084 return ''.join(out)
3085
3086
3087 if __name__ == '__main__':
3088 run_fypp()