PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
gen_modi.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2
3import sys
4import re
5from pathlib import Path
6
7# Start of a procedure, with its optional prefixes (PURE, ELEMENTAL, RECURSIVE...
8# and, for a function, its type: REAL, REAL(KIND=JPRB), TYPE(T), CHARACTER*8...)
9reg_type_spec = (r"(?:INTEGER|REAL|DOUBLE\s*PRECISION|COMPLEX|CHARACTER|LOGICAL|TYPE|CLASS)"
10 r"\s*(?:\‍((?:[^()]|\‍([^()]*\‍))*\‍)|\*\s*\w+)?")
11reg_proc_prefix = (r"(?:(?:IMPURE|PURE|ELEMENTAL|RECURSIVE|NON_RECURSIVE)\s+|"
12 + reg_type_spec + r"\s*)*")
13reg_proc_name = re.compile(r"^\s*" + reg_proc_prefix + r"(SUBROUTINE|FUNCTION)\s+(\w+)",
14 re.IGNORECASE)
15# End of a procedure (a bare END can only end a program unit)
16reg_proc_end = re.compile(r"^\s*END\s*((SUBROUTINE|FUNCTION)\b|$)", re.IGNORECASE)
17reg_proc_args = re.compile(r"\‍(([\w\s,]+)\‍)", re.IGNORECASE)
18reg_func_result = re.compile(r"RESULT\s*\‍(([\w\s]+)\‍)", re.IGNORECASE)
19reg_use_module_only = re.compile(r"(?:^\s*use\s+\w+\s*,\s*only\s*:)(.*)", re.IGNORECASE)
20reg_use_module_name = re.compile(r"^\s*use\s+(\w+)", re.IGNORECASE)
21reg_variable_name_simple = re.compile(r"::\s*(\w+)", re.IGNORECASE)
22reg_string = re.compile(r"'[^']*'|\"[^\"]*\"")
23reg_component = re.compile(r"%\s*\w+") # derived type components (D%NIJT)
24reg_identifier = re.compile(r"[A-Z_][A-Z0-9_]*")
25# ACDC directives (!$ACDC singlecolumn...) must be kept, as they are, in the interface
26reg_acdc = re.compile(r"!\$ACDC\b", re.IGNORECASE)
27
28# Macro directives and Fortran include statements are case-sensitive so they must never be uppercased
29reg_case_is_important = re.compile(r"\s*#|\s*INCLUDE", re.IGNORECASE)
30
31reg_all_decl_variable = [
32 r"^\s*INTEGER\s*[\‍(*,:\s]",
33 r"^\s*REAL\s*[\‍(*,:\s]",
34 r"^\s*DOUBLE PRECISION\s*[\‍(*,:\s]",
35 r"^\s*CHARACTER\s*[\‍(*,:\s]",
36 r"^\s*LOGICAL\s*[\‍(*,:\s]",
37 r"^\s*TYPE\s*\‍(",
38 r"^\s*CLASS\s*\‍(",
39]
40reg_all_decl = [
41 r"^\s*$",
42 r"^\s*!",
43 reg_proc_name.pattern,
44 r"^\s* ",
45 r"^\s*USE[,\s]",
46 r"^\s*#",
47 r"^\s*IMPLICIT NONE",
48 r"^\s*include ",
49 *reg_all_decl_variable,
50]
51
52reg_is_still_decl = re.compile("|".join(x for x in reg_all_decl), re.IGNORECASE)
53reg_is_variable_decl = re.compile(
54 "|".join(x for x in reg_all_decl_variable), re.IGNORECASE
55)
56
57
58class GenModiError(Exception):
59 """Source file whose interface module cannot be generated"""
60
61
62def is_modi_needed(lines):
63 # If a module is declared in the file, then no interface is needed
64 for line in lines:
65 if line.startswith("MODULE "):
66 return False
67 return True
68
69
71 # Remove comments (except ACDC directives), remove double spaces, join lines using
72 # continuation marker (&)
73 lines = []
74 buf = ""
75 for line in src:
76 line = line.strip()
77 if reg_acdc.match(line):
78 # directive kept as is
79 lines.append(line + "\n")
80 continue
81 if line.startswith("!"):
82 continue
83 while " " in line:
84 line = line.replace(" ", " ")
85 if not reg_case_is_important.match(line):
86 line = line.upper()
87 if "!" in line and not line.startswith("#"):
88 # When '!' is in the middle of a line, most of the time what follow it is comment.
89 # But sometimes, it is a negation in an ifdef, see: #if ! defined foo
90 line = line.split("!")[0].strip()
91 if line.endswith("&"):
92 buf += line.replace("&", "")
93 else:
94 lines.append(buf + line.replace("&", "") + "\n")
95 buf = ""
96 return lines
97
98
100 to_rm = []
101 depth = 0
102
103 for idx, line in enumerate(lines):
104 if reg_proc_name.match(line):
105 depth = depth + 1
106 if depth > 1:
107 to_rm.append(idx)
108 if reg_proc_end.match(line):
109 depth = depth - 1
110 for idx in reversed(to_rm):
111 lines.pop(idx)
112
113
115 ifdef = []
116 for idx, line in enumerate(lines):
117 if line.startswith("#if"):
118 ifdef.append(idx)
119 if line.startswith("#endif"):
120 ifdef.pop()
121 for idx in reversed(ifdef):
122 lines.pop(idx)
123
124
126 use_only = {} # line_idx -> "use only" values
127 # list of lines with used module without an only clause,
128 # or imported value that are not used in the procedure signature
129 to_rm = []
130
131 # Retrieve all explicitly imported values (eg. use foo, only: stuff)
132 # If there is no 'only' clause, the line is mark for deletion
133 for idx, line in enumerate(lines):
134 if line.startswith("USE "):
135 matches = reg_use_module_only.match(line)
136 if not matches:
137 to_rm.append(idx)
138 else:
139 use_only[idx] = [v.strip() for v in matches.group(1).split(",") if v.strip()]
140
141 # Identifiers used in the variable declarations (whole words only, string
142 # constants and derived type components removed: 'TM06' does not use TM06,
143 # LRMC01 does not use RMC01)
144 used = set()
145 for line in lines:
146 if reg_is_variable_decl.match(line):
147 line = reg_component.sub("", reg_string.sub("", line))
148 used.update(reg_identifier.findall(line))
149
150 # Only the imported values used in a variable declaration are kept, a line
151 # without any of them is removed
152 for idx, values in use_only.items():
153 kept = []
154 for val in values:
155 # renaming (local => used): the local name is the one used
156 local = val.split("=>")[0].strip()
157 # generic operators and assignments are always kept
158 if local.startswith(("OPERATOR", "ASSIGNMENT")) or local in used:
159 kept.append(val)
160 if kept:
161 module = reg_use_module_name.match(lines[idx]).group(1)
162 lines[idx] = f"USE {module}, ONLY: {', '.join(kept)}\n"
163 else:
164 to_rm.append(idx)
165
166 for idx in reversed(sorted(to_rm)):
167 lines.pop(idx)
168
169
171 # Retrieve type of procedure, name, arguments (with result if any)
172 matches = reg_proc_name.match(line)
173 proc_type = matches.group(1)
174 proc_name = matches.group(2)
175
176 # arguments are searched after the procedure name (not in the type)
177 end_name = matches.end()
178 proc_args = []
179 matches = reg_proc_args.search(line, end_name)
180 if matches:
181 proc_args = [arg.strip() for arg in matches.group(1).split(",")]
182
183 if proc_type == "FUNCTION":
184 matches = reg_func_result.search(line, end_name)
185 if matches:
186 proc_args.append(matches.group(1).strip())
187
188 return proc_type, proc_name, proc_args
189
190
192 newlines = []
193 for line in lines:
194 # Comments (ACDC directives) cannot be split
195 while len(line) > 80 and not line.lstrip().startswith("!"):
196 break_idx_space = line[0:80].rfind(" ")
197 break_idx_comma = line[0:80].rfind(",")
198
199 # Find which one let us have the longest line of less than 80 chars
200 if break_idx_comma > break_idx_space:
201 break_idx = break_idx_comma
202 else:
203 break_idx = break_idx_space
204
205 # If no space or comma was found, force break the line at 80 chars
206 if break_idx == -1:
207 break_idx = 80
208
209 newlines.append(line[:break_idx] + "&\n")
210 line = line[break_idx:]
211 newlines.append(line)
212 return newlines
213
214
215def check_procedures(f90, lines):
216 # The file must contain exactly one procedure (outside a module), whose
217 # name is the file name: the interface module of xxx.F90 is MODI_XXX in
218 # modi_xxx.F90
219 names = [reg_proc_name.match(line).group(2) for line in lines
220 if reg_proc_name.match(line)]
221 if not names:
222 raise GenModiError(f"{f90}: no SUBROUTINE or FUNCTION found")
223 if len(names) > 1:
224 raise GenModiError(f"{f90}: several procedures found outside a module "
225 f"({', '.join(names)}), only one is allowed")
226 if names[0].upper() != f90.stem.upper():
227 raise GenModiError(f"{f90}: the procedure name ({names[0]}) must be the "
228 f"file name ({f90.stem})")
229
230
231def gen_modi(f90):
232 modi_path = Path(modi_dir / Path("modi_" + str(f90.name)))
233 # No outdated file is left in case of error
234 modi_path.unlink(missing_ok=True)
235 with open(f90, "r") as src:
236 lines = simplify_code(src)
237 if not is_modi_needed(lines):
238 modi_path.touch()
239 return
240
242 check_procedures(f90, lines)
243
244 modi_lines = []
245 proc_type = ""
246 proc_name = ""
247 proc_args = []
248 for line in lines:
249 if not proc_name:
250 if reg_proc_name.match(line):
251 proc_type, proc_name, proc_args = get_proc_signature(line)
252 modi_lines.append(f"MODULE MODI_{proc_name}\nINTERFACE\n")
253
254 matches = reg_is_still_decl.match(line)
255 if not matches and proc_name:
256 modi_lines.append(f"END {proc_type} {proc_name}\n")
257 modi_lines.append(f"END INTERFACE\n")
258 modi_lines.append(f"END MODULE MODI_{proc_name}\n")
259 proc_name = ""
260 continue
261
262 if proc_name and reg_is_variable_decl.match(line) and "INTENT" not in line:
263 # if there are no intent, it might be a local variable
264 # but sometimes the intent is missing, so we check also
265 # if it's not in the list of arguments, it can also be the result of a function
266 matches = reg_variable_name_simple.search(line)
267 if matches:
268 var_name = matches.group(1)
269 if var_name not in proc_args and var_name != proc_name:
270 continue
271
272 if proc_name:
273 modi_lines.append(line)
274
275 remove_dangling_ifdef(modi_lines)
276 remove_unsed_modules(modi_lines)
277 modi_lines = break_long_lines(modi_lines)
278 with open(modi_path, "w") as modi:
279 modi.write("".join(modi_lines))
280
281
282modi_dir = Path("modi")
283args = sys.argv
284try:
285 idx = args.index("-o")
286except:
287 idx = None
288if idx:
289 modi_dir = Path(args[idx + 1])
290 args.pop(idx + 1)
291 args.pop(idx)
292
293for arg in sys.argv[1:]:
294 file = Path(arg)
295 try:
296 gen_modi(file)
297 except GenModiError as err:
298 print(f"gen_modi.py: error: {err}", file=sys.stderr)
299 sys.exit(1)
get_proc_signature(line)
Definition gen_modi.py:170
simplify_code(src)
Definition gen_modi.py:70
remove_unsed_modules(lines)
Definition gen_modi.py:125
break_long_lines(lines)
Definition gen_modi.py:191
is_modi_needed(lines)
Definition gen_modi.py:62
check_procedures(f90, lines)
Definition gen_modi.py:215
remove_dangling_ifdef(lines)
Definition gen_modi.py:114
remove_contained_procedures(lines)
Definition gen_modi.py:99