1 | from jinja2 import Environment, FileSystemLoader |
---|
2 | from sys import argv |
---|
3 | from textwrap import dedent |
---|
4 | import re |
---|
5 | from re import search # regular expressions |
---|
6 | |
---|
7 | def pretty(line,indent): |
---|
8 | line = dedent(line) |
---|
9 | if search('^#', line): # check if line is a preprocessor directive |
---|
10 | print line |
---|
11 | else: |
---|
12 | print (3*indent)*' ' + line |
---|
13 | |
---|
14 | # Jinja2 custom tests |
---|
15 | # https://jinja.palletsprojects.com/en/2.10.x/templates/ |
---|
16 | |
---|
17 | def is_keyword(word, txt): |
---|
18 | pattern=r'\b%s\b'%word |
---|
19 | match = search(pattern, txt) |
---|
20 | return True if match else False |
---|
21 | |
---|
22 | env=Environment(loader=FileSystemLoader('.')) |
---|
23 | env.tests['in'] = is_keyword |
---|
24 | |
---|
25 | tpl=env.get_template(argv[1]) |
---|
26 | source = tpl.render() |
---|
27 | source = [line for line in source.split('\n') if line.strip() != ''] |
---|
28 | |
---|
29 | # regular expressions matching Fortran keywords |
---|
30 | # \b detects word boundaries |
---|
31 | # $ and ( must be escaped : \$, \( |
---|
32 | # THIS|THAT means THIS or THAT |
---|
33 | # raw Python strings r'blabla' avoid doubling '\' |
---|
34 | noop = r'!\$OMP' |
---|
35 | increase = r'\bTHEN\b|\bDO\b|\bSELECT CASE\b' |
---|
36 | inter = r'\bELSE\b|\bCASE\(|\bCASE DEFAULT\b' |
---|
37 | decrease = r'\bEND IF\b|\bENDIF\b|\bEND DO\b|\bENDDO\b|\bEND SELECT\b' |
---|
38 | |
---|
39 | indent=1 |
---|
40 | |
---|
41 | for line in source : |
---|
42 | if search(noop, line) : |
---|
43 | pretty(line,indent) |
---|
44 | elif search(decrease, line) : |
---|
45 | indent = indent-1 |
---|
46 | pretty(line,indent) |
---|
47 | elif search(increase,line): |
---|
48 | pretty(line,indent) |
---|
49 | indent = indent+1 |
---|
50 | elif search(inter,line): |
---|
51 | pretty(line,indent-1) |
---|
52 | else: |
---|
53 | pretty(line,indent) |
---|
54 | |
---|
55 | # print is_keyword('LE','LE_DE') |
---|