-
Notifications
You must be signed in to change notification settings - Fork 51
/
fypp.py
executable file
·2956 lines (2417 loc) · 106 KB
/
fypp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# fypp -- Python powered Fortran preprocessor
#
# Copyright (c) 2016-2017 Bálint Aradi, Universität Bremen
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################
'''For using the functionality of the Fypp preprocessor from within
Python, one usually interacts with the following two classes:
* `Fypp`_: The actual Fypp preprocessor. It returns for a given input
the preprocessed output.
* `FyppOptions`_: Contains customizable settings controling the behaviour of
`Fypp`_. Alternatively, the function `get_option_parser()`_ can be used to
obtain an option parser, which can create settings based on command line
arguments.
If processing stops prematurely, an instance of one of the following
subclasses of `FyppError`_ is raised:
* FyppFatalError: Unexpected error (e.g. bad input, missing files, etc.)
* FyppStopRequest: Stop was triggered by an explicit request in the input
(by a stop- or an assert-directive).
'''
from __future__ import print_function
import sys
import types
import inspect
import re
import os
import errno
import time
import optparse
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin__ as builtins
# Prevent cluttering user directory with Python bytecode
sys.dont_write_bytecode = True
VERSION = '2.0.1'
STDIN = '<stdin>'
FILEOBJ = '<fileobj>'
STRING = '<string>'
ERROR_EXIT_CODE = 1
USER_ERROR_EXIT_CODE = 2
_ALL_DIRECTIVES_PATTERN = r'''
# comment block
(?:^[ \t]*\#!.*\n)+
|
# line directive (with optional continuation lines)
^[ \t]*(?P<ldirtype>[\#\$@]):[ \t]*
(?P<ldir>.+?(?:&[ \t]*\n(?:[ \t]*&)?.*?)*)?[ \t]*\n
|
# inline eval directive
(?P<idirtype>[$\#@])\{[ \t]*(?P<idir>.+?)?[ \t]*\}(?P=idirtype)
'''
_ALL_DIRECTIVES_REGEXP = re.compile(
_ALL_DIRECTIVES_PATTERN, re.VERBOSE | re.MULTILINE)
_CONTROL_DIR_REGEXP = re.compile(
r'(?P<dir>[a-zA-Z_]\w*)[ \t]*(?:[ \t]+(?P<param>[^ \t].*))?$')
_DIRECT_CALL_REGEXP = re.compile(
r'(?P<callname>[a-zA-Z_][\w.]*)[ \t]*\((?P<callparams>.+?)?\)$')
_DIRECT_CALL_KWARG_REGEXP = re.compile(
r'(?:(?P<kwname>[a-zA-Z_]\w*)\s*=(?=[^=]|$))?')
_DEF_PARAM_REGEXP = re.compile(
r'^(?P<name>[a-zA-Z_]\w*)[ \t]*\(\s*(?P<args>.+)?\s*\)$')
_SIMPLE_CALLABLE_REGEXP = re.compile(
r'^(?P<name>[a-zA-Z_][\w.]*)[ \t]*(?:\([ \t]*(?P<args>.*)[ \t]*\))?$')
_IDENTIFIER_NAME_REGEXP = re.compile(r'^(?P<name>[a-zA-Z_]\w*)$')
_PREFIXED_IDENTIFIER_NAME_REGEXP = re.compile(r'^(?P<name>[a-zA-Z_][\w.]*)$')
_SET_PARAM_REGEXP = re.compile(
r'^(?P<name>(?:[(]\s*)?[a-zA-Z_]\w*(?:\s*,\s*[a-zA-Z_]\w*)*(?:\s*[)])?)\s*'\
r'(?:=\s*(?P<expr>.*))?$')
_DEL_PARAM_REGEXP = re.compile(
r'^(?:[(]\s*)?[a-zA-Z_]\w*(?:\s*,\s*[a-zA-Z_]\w*)*(?:\s*[)])?$')
_FOR_PARAM_REGEXP = re.compile(
r'^(?P<loopexpr>[a-zA-Z_]\w*(\s*,\s*[a-zA-Z_]\w*)*)\s+in\s+(?P<iter>.+)$')
_INCLUDE_PARAM_REGEXP = re.compile(r'^(\'|")(?P<fname>.*?)\1$')
_COMMENTLINE_REGEXP = re.compile(r'^[ \t]*!.*$')
_CONTLINE_REGEXP = re.compile(r'&[ \t]*\n(?:[ \t]*&)?')
_UNESCAPE_TEXT_REGEXP1 = re.compile(r'([$#@])\\(\\*)([{:])')
_UNESCAPE_TEXT_REGEXP2 = re.compile(r'(\})\\(\\*)([$#@])')
_INLINE_EVAL_REGION_REGEXP = re.compile(r'\${.*?}\$')
_RESERVED_PREFIX = '__'
_RESERVED_NAMES = set(['defined', 'setvar', 'getvar', 'delvar', 'globalvar',
'_LINE_', '_FILE_', '_THIS_FILE_', '_THIS_LINE_',
'_TIME_', '_DATE_'])
_LINENUM_NEW_FILE = 1
_LINENUM_RETURN_TO_FILE = 2
_QUOTES_FORTRAN = '\'"'
_OPENING_BRACKETS_FORTRAN = '{(['
_CLOSING_BRACKETS_FORTRAN = '})]'
_ARGUMENT_SPLIT_CHAR_FORTRAN = ','
class FyppError(Exception):
'''Signalizes error occuring during preprocessing.
Args:
msg (str): Error message.
fname (str): File name. None (default) if file name is not available.
span (tuple of int): Beginning and end line of the region where error
occured or None if not available. If fname was not None, span must
not be None.
cause (Exception): Contains the exception, which triggered this
exception or None, if this exception is not masking any underlying
one. (Emulates Python 3 exception chaining in a Python 2 compatible
way.)
Attributes:
msg (str): Error message.
fname (str or None): File name or None if not available.
span (tuple of int or None): Beginning and end line of the region
where error occured or None if not available. Line numbers start
from zero. For directives, which do not consume end of the line,
start and end lines are identical.
cause (Exception): In case this exception is raised in an except block,
the original exception should be passed here. (Emulates Python 3
exception chaining in a Python 2 compatible way.)
'''
def __init__(self, msg, fname=None, span=None, cause=None):
super(FyppError, self).__init__()
self.msg = msg
self.fname = fname
self.span = span
self.cause = cause
def __str__(self):
msg = [self.__class__.__name__, ': ']
if self.fname is not None:
msg.append("file '" + self.fname + "'")
if self.span[1] > self.span[0] + 1:
msg.append(', lines {0}-{1}'.format(
self.span[0] + 1, self.span[1]))
else:
msg.append(', line {0}'.format(self.span[0] + 1))
msg.append('\n')
if self.msg:
msg.append(self.msg)
if self.cause is not None:
msg.append('\n' + str(self.cause))
return ''.join(msg)
class FyppFatalError(FyppError):
'''Signalizes an unexpected error during processing.'''
pass
class FyppStopRequest(FyppError):
'''Signalizes an explicitely triggered stop (e.g. via stop directive)'''
pass
class Parser:
'''Parses a text and generates events when encountering Fypp constructs.
Args:
includedirs (list): List of directories, in which include files should
be searched for, when they are not found at the default location.
'''
def __init__(self, includedirs=None):
# Directories to search for include files
if includedirs is None:
self._includedirs = []
else:
self._includedirs = includedirs
# Name of current file
self._curfile = None
# Directory of current file
self._curdir = None
def parsefile(self, fobj):
'''Parses file or a file like object.
Args:
fobj (str or file): Name of a file or a file like object.
'''
if isinstance(fobj, str):
if fobj == STDIN:
self._includefile(None, sys.stdin, STDIN, os.getcwd())
else:
inpfp = _open_input_file(fobj)
self._includefile(None, inpfp, fobj, os.path.dirname(fobj))
inpfp.close()
else:
self._includefile(None, fobj, FILEOBJ, os.getcwd())
def _includefile(self, span, fobj, fname, curdir):
oldfile = self._curfile
olddir = self._curdir
self._curfile = fname
self._curdir = curdir
self.handle_include(span, fname)
self._parse(fobj.read())
self.handle_endinclude(span, fname)
self._curfile = oldfile
self._curdir = olddir
def parse(self, txt):
'''Parses string.
Args:
txt (str): Text to parse.
'''
self._curfile = STRING
self._curdir = ''
self.handle_include(None, self._curfile)
self._parse(txt)
self.handle_endinclude(None, self._curfile)
def handle_include(self, span, fname):
'''Called when parser starts to process a new file.
It is a dummy methond and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file.
'''
self._log_event('include', span, filename=fname)
def handle_endinclude(self, span, fname):
'''Called when parser finished processing a file.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file.
'''
self._log_event('endinclude', span, filename=fname)
def handle_set(self, span, name, expr):
'''Called when parser encounters a set directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the variable.
expr (str): String representation of the expression to be assigned
to the variable.
'''
self._log_event('set', span, name=name, expression=expr)
def handle_def(self, span, name, args):
'''Called when parser encounters a def directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the macro to be defined.
argexpr (str): String with argument definition (or None)
'''
self._log_event('def', span, name=name, arguments=args)
def handle_enddef(self, span, name):
'''Called when parser encounters an enddef directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name found after the enddef directive.
'''
self._log_event('enddef', span, name=name)
def handle_del(self, span, name):
'''Called when parser encounters a del directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the variable to delete.
'''
self._log_event('del', span, name=name)
def handle_if(self, span, cond):
'''Called when parser encounters an if directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
cond (str): String representation of the branching condition.
'''
self._log_event('if', span, condition=cond)
def handle_elif(self, span, cond):
'''Called when parser encounters an elif directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
cond (str): String representation of the branching condition.
'''
self._log_event('elif', span, condition=cond)
def handle_else(self, span):
'''Called when parser encounters an else directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('else', span)
def handle_endif(self, span):
'''Called when parser encounters an endif directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('endif', span)
def handle_for(self, span, varexpr, iterator):
'''Called when parser encounters a for directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
varexpr (str): String representation of the loop variable
expression.
iterator (str): String representation of the iterable.
'''
self._log_event('for', span, variable=varexpr, iterable=iterator)
def handle_endfor(self, span):
'''Called when parser encounters an endfor directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('endfor', span)
def handle_call(self, span, name, argexpr):
'''Called when parser encounters a call directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the callable to call
argexpr (str or None): Argument expression containing additional
arguments for the call.
'''
self._log_event('call', span, name=name, argexpr=argexpr)
def handle_nextarg(self, span, name):
'''Called when parser encounters a nextarg directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str or None): Name of the argument following next or
None if it should be the next positional argument.
'''
self._log_event('nextarg', span, name=name)
def handle_endcall(self, span, name):
'''Called when parser encounters an endcall directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name found after the endcall directive.
'''
self._log_event('endcall', span, name=name)
def handle_eval(self, span, expr):
'''Called when parser encounters an eval directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
expr (str): String representation of the Python expression to
be evaluated.
'''
self._log_event('eval', span, expression=expr)
def handle_global(self, span, name):
'''Called when parser encounters a global directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the variable which should be made global.
'''
self._log_event('global', span, name=name)
def handle_text(self, span, txt):
'''Called when parser finds text which must left unaltered.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
txt (str): Text.
'''
self._log_event('text', span, content=txt)
def handle_comment(self, span):
'''Called when parser finds a preprocessor comment.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('comment', span)
def handle_mute(self, span):
'''Called when parser finds a mute directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('mute', span)
def handle_endmute(self, span):
'''Called when parser finds an endmute directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('endmute', span)
def handle_stop(self, span, msg):
'''Called when parser finds an stop directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
msg (str): Stop message.
'''
self._log_event('stop', span, msg=msg)
def handle_assert(self, span):
'''Called when parser finds an assert directive.
It is a dummy method and should be overriden for actual use.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._log_event('assert', span)
@staticmethod
def _log_event(event, span=(-1, -1), **params):
print('{0}: {1} --> {2}'.format(event, span[0], span[1]))
for parname, parvalue in params.items():
print(' {0}: ->|{1}|<-'.format(parname, parvalue))
print()
def _parse(self, txt, linenr=0, directcall=False):
pos = 0
for match in _ALL_DIRECTIVES_REGEXP.finditer(txt):
start, end = match.span()
if start > pos:
endlinenr = linenr + txt.count('\n', pos, start)
self._process_text(txt[pos:start], (linenr, endlinenr))
linenr = endlinenr
endlinenr = linenr + txt.count('\n', start, end)
span = (linenr, endlinenr)
ldirtype, ldir, idirtype, idir = match.groups()
if directcall and (idirtype is None or idirtype != '$'):
msg = 'only inline eval directives allowed in direct calls'
raise FyppFatalError(msg, self._curfile, span)
elif idirtype is not None:
if idir is None:
msg = 'missing inline directive content'
raise FyppFatalError(msg, self._curfile, span)
dirtype = idirtype
content = idir
elif ldirtype is not None:
if ldir is None:
msg = 'missing line directive content'
raise FyppFatalError(msg, self._curfile, span)
dirtype = ldirtype
content = _CONTLINE_REGEXP.sub('', ldir)
else:
# Comment directive
dirtype = None
if dirtype == '$':
self.handle_eval(span, content)
elif dirtype == '#':
self._process_control_dir(content, span)
elif dirtype == '@':
self._process_direct_call(content, span)
else:
self.handle_comment(span)
pos = end
linenr = endlinenr
if pos < len(txt):
endlinenr = linenr + txt.count('\n', pos)
self._process_text(txt[pos:], (linenr, endlinenr))
def _process_text(self, txt, span):
escaped_txt = self._unescape(txt)
self.handle_text(span, escaped_txt)
def _process_control_dir(self, content, span):
match = _CONTROL_DIR_REGEXP.match(content)
if not match:
msg = "invalid control directive content '{0}'".format(content)
raise FyppFatalError(msg, self._curfile, span)
directive, param = match.groups()
if directive == 'if':
self._check_param_presence(True, 'if', param, span)
self.handle_if(span, param)
elif directive == 'else':
self._check_param_presence(False, 'else', param, span)
self.handle_else(span)
elif directive == 'elif':
self._check_param_presence(True, 'elif', param, span)
self.handle_elif(span, param)
elif directive == 'endif':
self._check_param_presence(False, 'endif', param, span)
self.handle_endif(span)
elif directive == 'def':
self._check_param_presence(True, 'def', param, span)
self._check_not_inline_directive('def', span)
self._process_def(param, span)
elif directive == 'enddef':
self._process_enddef(param, span)
elif directive == 'set':
self._check_param_presence(True, 'set', param, span)
self._process_set(param, span)
elif directive == 'del':
self._check_param_presence(True, 'del', param, span)
self._process_del(param, span)
elif directive == 'for':
self._check_param_presence(True, 'for', param, span)
self._process_for(param, span)
elif directive == 'endfor':
self._check_param_presence(False, 'endfor', param, span)
self.handle_endfor(span)
elif directive == 'call':
self._check_param_presence(True, 'call', param, span)
self._process_call(param, span)
elif directive == 'nextarg':
self._process_nextarg(param, span)
elif directive == 'endcall':
self._process_endcall(param, span)
elif directive == 'include':
self._check_param_presence(True, 'include', param, span)
self._check_not_inline_directive('include', span)
self._process_include(param, span)
elif directive == 'mute':
self._check_param_presence(False, 'mute', param, span)
self._check_not_inline_directive('mute', span)
self.handle_mute(span)
elif directive == 'endmute':
self._check_param_presence(False, 'endmute', param, span)
self._check_not_inline_directive('endmute', span)
self.handle_endmute(span)
elif directive == 'stop':
self._check_param_presence(True, 'stop', param, span)
self._check_not_inline_directive('stop', span)
self.handle_stop(span, param)
elif directive == 'assert':
self._check_param_presence(True, 'assert', param, span)
self._check_not_inline_directive('assert', span)
self.handle_assert(span, param)
elif directive == 'global':
self._check_param_presence(True, 'global', param, span)
self._process_global(param, span)
else:
msg = "unknown directive '{0}'".format(directive)
raise FyppFatalError(msg, self._curfile, span)
def _process_direct_call(self, callexpr, span):
match = _DIRECT_CALL_REGEXP.match(callexpr)
if not match:
msg = "invalid direct call expression"
raise FyppFatalError(msg, self._curfile, span)
callname = match.group('callname')
self.handle_call(span, callname, None)
callparams = match.group('callparams')
if callparams is None or not callparams.strip():
args = []
else:
try:
args = [arg.strip() for arg in _argsplit_fortran(callparams)]
except Exception as exc:
msg = 'unable to parse direct call argument'
raise FyppFatalError(msg, self._curfile, span, exc)
for arg in args:
match = _DIRECT_CALL_KWARG_REGEXP.match(arg)
argval = arg[match.end():].strip()
# Remove enclosing braces if present
if argval.startswith('{'):
argval = argval[1:-1]
keyword = match.group('kwname')
self.handle_nextarg(span, keyword)
self._parse(argval, linenr=span[0], directcall=True)
self.handle_endcall(span, callname)
def _process_def(self, param, span):
match = _DEF_PARAM_REGEXP.match(param)
if not match:
msg = "invalid macro definition '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
name = match.group('name')
argexpr = match.group('args')
self.handle_def(span, name, argexpr)
def _process_enddef(self, param, span):
if param is not None:
match = _IDENTIFIER_NAME_REGEXP.match(param)
if not match:
msg = "invalid enddef parameter '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
param = match.group('name')
self.handle_enddef(span, param)
def _process_set(self, param, span):
match = _SET_PARAM_REGEXP.match(param)
if not match:
msg = "invalid variable assignment '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
self.handle_set(span, match.group('name'), match.group('expr'))
def _process_global(self, param, span):
match = _DEL_PARAM_REGEXP.match(param)
if not match:
msg = "invalid variable specification '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
self.handle_global(span, param)
def _process_del(self, param, span):
match = _DEL_PARAM_REGEXP.match(param)
if not match:
msg = "invalid variable specification '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
self.handle_del(span, param)
def _process_for(self, param, span):
match = _FOR_PARAM_REGEXP.match(param)
if not match:
msg = "invalid for loop declaration '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
loopexpr = match.group('loopexpr')
loopvars = [s.strip() for s in loopexpr.split(',')]
self.handle_for(span, loopvars, match.group('iter'))
def _process_call(self, param, span):
match = _SIMPLE_CALLABLE_REGEXP.match(param)
if not match:
msg = "invalid callable expression '{}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
name, args = match.groups()
self.handle_call(span, name, args)
def _process_nextarg(self, param, span):
if param is not None:
match = _IDENTIFIER_NAME_REGEXP.match(param)
if not match:
msg = "invalid nextarg parameter '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
param = match.group('name')
self.handle_nextarg(span, param)
def _process_endcall(self, param, span):
if param is not None:
match = _PREFIXED_IDENTIFIER_NAME_REGEXP.match(param)
if not match:
msg = "invalid endcall parameter '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
param = match.group('name')
self.handle_endcall(span, param)
def _process_include(self, param, span):
match = _INCLUDE_PARAM_REGEXP.match(param)
if not match:
msg = "invalid include file declaration '{0}'".format(param)
raise FyppFatalError(msg, self._curfile, span)
fname = match.group('fname')
for incdir in [self._curdir] + self._includedirs:
fpath = os.path.join(incdir, fname)
if os.path.exists(fpath):
break
else:
msg = "include file '{0}' not found".format(fname)
raise FyppFatalError(msg, self._curfile, span)
inpfp = _open_input_file(fpath)
self._includefile(span, inpfp, fpath, os.path.dirname(fpath))
inpfp.close()
def _process_mute(self, span):
if span[0] == span[1]:
msg = 'Inline form of mute directive not allowed'
raise FyppFatalError(msg, self._curfile, span)
self.handle_mute(span)
def _process_endmute(self, span):
if span[0] == span[1]:
msg = 'Inline form of endmute directive not allowed'
raise FyppFatalError(msg, self._curfile, span)
self.handle_endmute(span)
def _check_param_presence(self, presence, directive, param, span):
if (param is not None) != presence:
if presence:
msg = 'missing data in {0} directive'.format(directive)
else:
msg = 'forbidden data in {0} directive'.format(directive)
raise FyppFatalError(msg, self._curfile, span)
def _check_not_inline_directive(self, directive, span):
if span[0] == span[1]:
msg = 'Inline form of {0} directive not allowed'.format(directive)
raise FyppFatalError(msg, self._curfile, span)
@staticmethod
def _unescape(txt):
txt = _UNESCAPE_TEXT_REGEXP1.sub(r'\1\2\3', txt)
txt = _UNESCAPE_TEXT_REGEXP2.sub(r'\1\2\3', txt)
return txt
class Builder:
'''Builds a tree representing a text with preprocessor directives.
'''
def __init__(self):
# The tree, which should be built.
self._tree = []
# List of all open constructs
self._open_blocks = []
# Nodes to which the open blocks have to be appended when closed
self._path = []
# Nr. of open blocks when file was opened. Used for checking whether all
# blocks have been closed, when file processing finishes.
self._nr_prev_blocks = []
# Current node, to which content should be added
self._curnode = self._tree
# Current file
self._curfile = None
def reset(self):
'''Resets the builder so that it starts to build a new tree.'''
self._tree = []
self._open_blocks = []
self._path = []
self._nr_prev_blocks = []
self._curnode = self._tree
self._curfile = None
def handle_include(self, span, fname):
'''Should be called to signalize change to new file.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file to be included.
'''
self._path.append(self._curnode)
self._curnode = []
self._open_blocks.append(
('include', self._curfile, [span], fname, None))
self._curfile = fname
self._nr_prev_blocks.append(len(self._open_blocks))
def handle_endinclude(self, span, fname):
'''Should be called when processing of a file finished.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file which has been included.
'''
nprev_blocks = self._nr_prev_blocks.pop(-1)
if len(self._open_blocks) > nprev_blocks:
directive, fname, spans = self._open_blocks[-1][0:3]
msg = '{0} directive still unclosed when reaching end of file'\
.format(directive)
raise FyppFatalError(msg, self._curfile, spans[0])
block = self._open_blocks.pop(-1)
directive, blockfname, spans = block[0:3]
if directive != 'include':
msg = 'internal error: last open block is not \'include\' when '\
'closing file \'{0}\''.format(fname)
raise FyppFatalError(msg)
if span != spans[0]:
msg = 'internal error: span for include and endinclude differ ('\
'{0} vs {1}'.format(span, spans[0])
raise FyppFatalError(msg)
oldfname, _ = block[3:5]
if fname != oldfname:
msg = 'internal error: mismatching file name in close_file event'\
" (expected: '{0}', got: '{1}')".format(oldfname, fname)
raise FyppFatalError(msg, fname)
block = directive, blockfname, spans, fname, self._curnode
self._curnode = self._path.pop(-1)
self._curnode.append(block)
self._curfile = blockfname
def handle_if(self, span, cond):
'''Should be called to signalize an if directive.
Args:
span (tuple of int): Start and end line of the directive.
param (str): String representation of the branching condition.
'''
self._path.append(self._curnode)
self._curnode = []
self._open_blocks.append(('if', self._curfile, [span], [cond], []))
def handle_elif(self, span, cond):
'''Should be called to signalize an elif directive.
Args:
span (tuple of int): Start and end line of the directive.
cond (str): String representation of the branching condition.
'''
self._check_for_open_block(span, 'elif')
block = self._open_blocks[-1]
directive, _, spans = block[0:3]
self._check_if_matches_last(directive, 'if', spans[-1], span, 'elif')
conds, contents = block[3:5]
conds.append(cond)
contents.append(self._curnode)
spans.append(span)
self._curnode = []
def handle_else(self, span):
'''Should be called to signalize an else directive.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._check_for_open_block(span, 'else')
block = self._open_blocks[-1]
directive, _, spans = block[0:3]
self._check_if_matches_last(directive, 'if', spans[-1], span, 'else')
conds, contents = block[3:5]
conds.append('True')
contents.append(self._curnode)
spans.append(span)
self._curnode = []
def handle_endif(self, span):
'''Should be called to signalize an endif directive.
Args:
span (tuple of int): Start and end line of the directive.
'''
self._check_for_open_block(span, 'endif')
block = self._open_blocks.pop(-1)
directive, _, spans = block[0:3]
self._check_if_matches_last(directive, 'if', spans[-1], span, 'endif')
_, contents = block[3:5]