Here's a Python program that analyzes Fortran source code files to create a call tree of subroutines and functions. This program will:
- Scan all Fortran files in a directory
- Identify subroutine and function definitions
- Track calls between them
- Output a call tree to a text file
import os
import re
from collections import defaultdict
class FortranCallTree:
def __init__(self):
# Dictionary to store caller -> callees relationships
self.call_graph = defaultdict(set)
# Dictionary to store routine -> file relationships
self.routine_locations = {}
# Set to store all defined routines
self.defined_routines = set()
def process_file(self, filepath):
"""Process a single Fortran file to extract routine definitions and calls."""
current_routine = None
# Regular expressions for Fortran syntax
routine_start = re.compile(r'^\s*(?:subroutine|function)\s+(\w+)', re.IGNORECASE)
call_pattern = re.compile(r'^\s*call\s+(\w+)', re.IGNORECASE)
end_routine = re.compile(r'^\s*end\s+(?:subroutine|function)', re.IGNORECASE)
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
# Skip comments
if line.startswith('!'):
continue
# Find routine definitions
routine_match = routine_start.match(line)
if routine_match:
current_routine = routine_match.group(1).lower()
self.defined_routines.add(current_routine)
self.routine_locations[current_routine] = filepath
continue
# Find end of routine
if end_routine.match(line):
current_routine = None
continue
# Find calls within routines
if current_routine:
call_match = call_pattern.match(line)
if call_match:
called_routine = call_match.group(1).lower()
self.call_graph[current_routine].add(called_routine)
def process_directory(self, directory):
"""Process all Fortran files in the given directory."""
fortran_extensions = ('.f', '.for', '.f90', '.f95', '.f03', '.f08')
for root, _, files in os.walk(directory):
for filename in files:
if filename.lower().endswith(fortran_extensions):
filepath = os.path.join(root, filename)
self.process_file(filepath)
def generate_call_tree(self, root_routine, level=0, visited=None):
"""Generate a string representation of the call tree starting from root_routine."""
if visited is None:
visited = set()
if root_routine in visited:
return f"{' ' * level}* {root_routine} (recursive call)\n"
output = []
visited.add(root_routine)
# Add current routine
location = self.routine_locations.get(root_routine, "unknown file")
file_name = os.path.basename(location)
marker = "" if root_routine in self.defined_routines else " (not defined in source)"
output.append(f"{' ' * level}- {root_routine}{marker} [{file_name}]")
# Add callees
callees = sorted(self.call_graph[root_routine])
for callee in callees:
subtree = self.generate_call_tree(callee, level + 1, visited.copy())
output.append(subtree)
return "\n".join(output)
def find_root_routines(self):
"""Find routines that are not called by any other routine (potential entry points)."""
all_callees = set()
for callees in self.call_graph.values():
all_callees.update(callees)
root_routines = set(self.call_graph.keys()) - all_callees
return sorted(root_routines)
def write_call_tree(self, output_file):
"""Write the complete call tree to a file."""
root_routines = self.find_root_routines()
with open(output_file, 'w', encoding='utf-8') as f:
f.write("Fortran Call Tree Analysis\n")
f.write("=========================\n\n")
if not root_routines:
f.write("No root routines found. Possible reasons:\n")
f.write("- No subroutines/functions defined\n")
f.write("- All routines are called by others (possible circular references)\n")
return
f.write(f"Found {len(root_routines)} potential root routines\n\n")
for i, root in enumerate(root_routines, 1):
f.write(f"Call Tree {i}: Starting from {root}\n")
f.write("-" * 50 + "\n")
tree = self.generate_call_tree(root)
f.write(tree)
f.write("\n\n")
def main():
# Get directory from user
directory = input("Enter the directory containing Fortran source files: ").strip()
if not os.path.isdir(directory):
print(f"Error: {directory} is not a valid directory")
return
# Create output file name
output_file = "fortran_call_tree.txt"
print(f"Processing Fortran files in {directory}...")
analyzer = FortranCallTree()
analyzer.process_directory(directory)
analyzer.write_call_tree(output_file)
print(f"Call tree analysis complete. Results written to {output_file}")
if __name__ == "__main__":
main()
This program does the following:
-
The FortranCallTree class handles the main analysis:
process_file: Analyzes a single Fortran file, looking for routine definitions and calls
process_directory: Processes all Fortran files in a directory
generate_call_tree: Creates a formatted call tree
find_root_routines: Identifies potential entry points
write_call_tree: Writes the complete analysis to a file
-
The program handles:
- Common Fortran file extensions (.f, .for, .f90, etc.)
- Case-insensitive matching (Fortran is case-insensitive)
- Comments (lines starting with !)
- Basic subroutine and function definitions
- CALL statements
-
The output file will contain:
- A list of root routines (routines not called by others)
- A hierarchical call tree for each root routine
- File locations for each routine
- Indications of undefined routines (routines called but not defined in the source)
- Detection of recursive calls
To use the program:
- Save it as
fortran_call_tree.py
- Run it:
python fortran_call_tree.py
- Enter the path to your directory containing Fortran files
- Check the output file
fortran_call_tree.txt
Limitations and notes:
-
This is a basic analyzer and might not handle all Fortran syntax variations:
- Doesn't handle modules and USE statements
- Doesn't handle interface blocks
- Doesn't handle contained procedures
- Doesn't distinguish between subroutines and functions
- Doesn't handle alternate entry points
-
For more complex Fortran code, you might need to enhance the regular expressions or add additional parsing logic.
-
The program assumes modern Fortran free-format source. For fixed-format source, you would need to modify the parsing logic.
To improve the program, you could:
- Add support for modules and USE statements
- Add handling of contained procedures
- Distinguish between subroutines and functions
- Add support for fixed-format source
- Add handling of interface blocks and procedure pointers
- Add visualization options (e.g., generate DOT files for graphviz)
The output will look something like this:
Fortran Call Tree Analysis
=========================
Found 2 potential root routines
Call Tree 1: Starting from main_program
--------------------------------------------------
- main_program [main.f90]
- init_data [init.f90]
- read_config [io.f90]
- process_data [process.f90]
- calculate [math.f90]
- update [math.f90]
Call Tree 2: Starting from standalone_routine
--------------------------------------------------
- standalone_routine [utils.f90]
- helper [utils.f90]