Creating a Fortran call tree using Python involves parsing Fortran source files to extract subroutine and function definitions, then identifying which routines call which others.
Below is a Python script that:
- Reads all
.f90 or .f Fortran source files in a directory.
- Parses routine names (subroutines and functions).
- Identifies calls to other routines within the body of each routine.
- Builds a call tree showing which routines are called by which others.
- Outputs this tree into a text file (
call_tree.txt).
✅ Features:
- Supports Fortran 90/77 style syntax.
- Handles both
call xyz(...) and direct usage like xyz(...).
- Case-insensitive matching.
- Skips comments and strings.
📁 Assumptions:
- Your code is in a folder named
fortran_code/
- Files have extensions
.f, .F, .f90, or .F90
- You want output in
call_tree.txt
✅ Python Script: build_call_tree.py
import os
import re
# Regular expressions for parsing Fortran
RE_ROUTINE = re.compile(r'\b(subroutine|function)\s+([a-zA-Z0-9_]+)', re.IGNORECASE)
RE_CALL = re.compile(r'\bcall\s+([a-zA-Z0-9_]+)', re.IGNORECASE)
RE_DIRECT_CALL = re.compile(r'\b([a-zA-Z0-9_]+)\s*$', re.IGNORECASE) # Simple case
RE_COMMENT = re.compile(r'!.*$', re.MULTILINE)
RE_STRING = re.compile(r'(["\'])(?:\\.|\1|[^\\])*?\1', re.DOTALL)
def remove_comments_and_strings(line):
line = RE_COMMENT.sub('', line)
line = RE_STRING.sub('', line)
return line
def find_routines_in_directory(directory):
routines = {} # name -> filename
for root, _, files in os.walk(directory):
for f in files:
if f.endswith(('.f', '.F', '.f90', '.F90')):
path = os.path.join(root, f)
with open(path, 'r') as file:
content = file.read()
lines = content.split('\n')
i = 0
while i < len(lines):
line = lines[i].strip()
if not line:
i += 1
continue
match = RE_ROUTINE.match(line)
if match:
kind, name = match.groups()
name = name.lower()
routines[name] = f
i += 1
return routines
def analyze_file(file_path, all_routines, call_graph):
with open(file_path, 'r') as file:
content = file.read()
current_routine = None
lines = content.split('\n')
for line in lines:
line = remove_comments_and_strings(line).strip().lower()
# Detect start of routine
rmatch = RE_ROUTINE.search(line)
if rmatch:
current_routine = rmatch.group(2).lower()
if current_routine not in call_graph:
call_graph[current_routine] = set()
# Find calls
if current_routine:
for call_match in RE_CALL.finditer(line):
called = call_match.group(1).lower()
if called in all_routines:
call_graph[current_routine].add(called)
# Optional: detect direct function calls without CALL
if 'call' not in line:
words = re.split(r'\W+', line)
for word in words:
if word.lower() in all_routines and word != current_routine:
call_graph[current_routine].add(word.lower())
# Detect end of routine
if line.startswith('end'):
current_routine = None
return call_graph
def write_call_tree(call_graph, output_file='call_tree.txt'):
with open(output_file, 'w') as f:
def print_node(name, indent=0, visited=None):
if visited is None:
visited = set()
if name in visited:
f.write(' ' * indent + '--> [RECURSIVE]\n')
return
visited.add(name)
children = sorted(call_graph.get(name, []))
for child in children:
f.write(' ' * indent + '--> ' + child + '\n')
print_node(child, indent + 4, visited.copy())
for routine in sorted(call_graph):
f.write(f'{routine}:\n')
print_node(routine)
f.write('\n')
def main():
src_dir = 'fortran_code'
output_file = 'call_tree.txt'
print("Scanning for routines...")
all_routines = find_routines_in_directory(src_dir)
print("Analyzing call graph...")
call_graph = {}
for root, _, files in os.walk(src_dir):
for f in files:
if f.endswith(('.f', '.F', '.f90', '.F90')):
path = os.path.join(root, f)
analyze_file(path, all_routines, call_graph)
print(f"Writing call tree to {output_file}...")
write_call_tree(call_graph, output_file)
if __name__ == '__main__':
main()
🔧 How to Use:
- Place your Fortran code in a directory named
fortran_code/.
- Save the above script as
build_call_tree.py.
- Run it:
python build_call_tree.py
- Output will be saved to
call_tree.txt.
📝 Sample Output (call_tree.txt):
main_program:
--> input_data
--> process_data
--> compute_stats
--> update_values
--> log_value
--> output_results
compute_stats:
--> log_value
log_value:
⚠️ Notes / Limitations:
- This parser is not perfect, but works well for most standard Fortran code.
- May miss some indirect calls or module procedure calls.
- Does not handle preprocessor macros (
#ifdef, etc.) or complex overloading.
If you need deeper parsing (e.g., modules, interfaces, or type-bound procedures), consider using a full Fortran parser like fortran-src or integrating with a tool like cflow or doxygen.
Let me know if you'd like support for modules, type-bound procedures, or graphviz visualization!