fparser

0.2.2 · active · verified Fri Apr 17

fparser is a Python implementation of a Fortran parser that provides the ability to parse Fortran code (F77, Fortran 2003, 2008, 2018 standards) and represent it as an Abstract Syntax Tree (AST). This allows for static analysis, refactoring, or code generation. The current stable version is 0.2.2, with active development and regular releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a Fortran code string into an AST using the Fortran2003 parser, then walk the tree to identify call statements and type declarations. It also shows how to access specific AST nodes and hints at code regeneration.

import os
from fparser.two import Fortran2003
from fparser.two.utils import walk
from fparser.common.readfortran import read_string

# Example Fortran code as a string
fortran_code = """
MODULE my_module
  INTEGER, PARAMETER :: DP = KIND(1.0D0)
CONTAINS
  SUBROUTINE my_sub(a, b)
    REAL(DP), INTENT(IN) :: a
    REAL(DP), INTENT(OUT) :: b
    b = a * 2.0_DP
  END SUBROUTINE my_sub
END MODULE my_module
PROGRAM main
  USE my_module
  IMPLICIT NONE
  REAL(DP) :: x, y
  x = 10.0_DP
  CALL my_sub(x, y)
  PRINT *, "Result:", y
END PROGRAM main
"""

# Read the Fortran code from a string
reader = read_string(fortran_code, ignore_comments=True)

# Parse the Fortran code using the Fortran 2003 standard parser
tree = Fortran2003.parse(reader)

# Walk the AST to find specific nodes, e.g., subroutine calls and variable declarations
print("Walking the AST to find subroutine calls and type declarations:")
for node in walk(tree):
    if isinstance(node, Fortran2003.Call_Stmt):
        print(f"  Found Call Statement: {node.items[0].name}")
    elif isinstance(node, Fortran2003.Declaration_Type_Spec):
        # For simplicity, just printing the type spec itself. 
        # Inspecting parent/sibling nodes would reveal variable names.
        print(f"  Found Type Declaration: {node.items[0]} (raw: {node})")

# Example: Accessing specific parts of the tree (e.g., the program name)
if tree.children and isinstance(tree.children[-1], Fortran2003.Main_Program):
    program_name = tree.children[-1].get_name()
    print(f"\nMain Program name: {program_name}")

# You can also regenerate the code from the AST
# print("\nRegenerated Fortran code:")
# print(tree.tofortran())

view raw JSON →