Skip to content

Backends

Parser backends convert C/C++ source code into the autopxd IR.

Backend Registry

backends

Parser backends for autopxd.

This package contains parser backend implementations that convert C/C++ source code into the autopxd IR (Intermediate Representation).

Available Backends

pycparser Pure Python C99 parser. Default backend with no external dependencies. Requires preprocessed input (CPP/clang -E output).

libclang LLVM clang-based parser with full C++ support. Requires system libclang library and matching clang2 Python package.

Example

::

from autopxd.backends import get_backend, list_backends

# Get the default backend
backend = get_backend()

# Get a specific backend
backend = get_backend("libclang")

# List available backends
for name in list_backends():
    print(name)

get_backend(name=None)

Get a parser backend instance.

Returns a new instance of the requested backend. If no name is provided, returns the default backend (pycparser).

::

from autopxd.backends import get_backend

# Get default backend
backend = get_backend()

# Get libclang backend
clang = get_backend("libclang")

# Parse a header
header = backend.parse(code, "myheader.h")

Parameters:

Name Type Description Default
name str | None

Backend name (e.g., "pycparser", "libclang"), or None for the default backend.

None

Returns:

Type Description
ParserBackend

New instance of the requested backend.

Raises:

Type Description
ValueError

If the requested backend is not available. Example -------

list_backends()

List names of all registered backends.

::

from autopxd.backends import list_backends

for name in list_backends():
    print(f"Available: {name}")

Returns:

Type Description
list[str]

List of backend names that can be passed to :func:get_backend. Example -------

register_backend(name, backend_class, is_default=False)

Register a parser backend.

Called by backend modules during import to add themselves to the registry. The first registered backend becomes the default unless is_default is explicitly set on a later registration.

Parameters:

Name Type Description Default
name str

Unique name for the backend (e.g., "pycparser", "libclang").

required
backend_class type[ParserBackend]

Class implementing the :class:~autopxd.ir.ParserBackend protocol.

required
is_default bool

If True, this becomes the default backend for :func:get_backend.

False

pycparser Backend

pycparser_backend

pycparser-based parser backend.

This backend uses pycparser (pure Python C99 parser) to parse C header files. It's the default backend since it requires no external dependencies beyond the pycparser package itself.

Limitations

  • C99 only - no C++ support (use libclang for C++)
  • Cannot extract #define macro values (processed by preprocessor)

Example

::

from autopxd.backends.pycparser_backend import PycparserBackend

backend = PycparserBackend()
header = backend.parse(code, "myheader.h")

PycparserBackend

Parser backend using pycparser.

The default autopxd parser backend, using the pure-Python pycparser library. This backend has no external dependencies but requires preprocessed C code as input.

Properties

name : str Returns "pycparser". supports_macros : bool Returns False - macros are consumed by the preprocessor. supports_cpp : bool Returns False - pycparser only supports C99.

Example

::

from autopxd.backends.pycparser_backend import PycparserBackend

backend = PycparserBackend()

# Parse preprocessed code
preprocessed = run_cpp("myheader.h")
header = backend.parse(preprocessed, "myheader.h")

for decl in header.declarations:
    print(decl)
Source code in autopxd/backends/pycparser_backend.py
class PycparserBackend:
    """Parser backend using pycparser.

    The default autopxd parser backend, using the pure-Python pycparser
    library. This backend has no external dependencies but requires
    preprocessed C code as input.

    Properties
    ----------
    name : str
        Returns ``"pycparser"``.
    supports_macros : bool
        Returns ``False`` - macros are consumed by the preprocessor.
    supports_cpp : bool
        Returns ``False`` - pycparser only supports C99.

    Example
    -------
    ::

        from autopxd.backends.pycparser_backend import PycparserBackend

        backend = PycparserBackend()

        # Parse preprocessed code
        preprocessed = run_cpp("myheader.h")
        header = backend.parse(preprocessed, "myheader.h")

        for decl in header.declarations:
            print(decl)
    """

    @property
    def name(self) -> str:
        return "pycparser"

    @property
    def supports_macros(self) -> bool:
        return False

    @property
    def supports_cpp(self) -> bool:
        return False

    def parse(
        self,
        code: str,
        filename: str,
        include_dirs: list[str] | None = None,
        extra_args: list[str] | None = None,
    ) -> Header:
        """Parse C code using pycparser.

        The code is automatically preprocessed using the system's C preprocessor
        (``cpp`` on Unix/Mac, ``clang -E`` on macOS, or ``cl.exe /E`` on Windows).

        :param code: C source code to parse.
        :param filename: Source filename for error messages and location tracking.
        :param include_dirs: Additional include directories for the preprocessor.
        :param extra_args: Extra arguments to pass to the preprocessor.
        :returns: :class:`~autopxd.ir.Header` containing parsed declarations.
        :raises RuntimeError: If preprocessing fails.
        :raises pycparser.plyparser.ParseError: If the code has syntax errors.
        """
        # pylint: disable=import-outside-toplevel
        from pycparser import (
            c_parser,
        )

        # Preprocess the code
        preprocessed = self._preprocess(code, include_dirs, extra_args)

        parser = c_parser.CParser()
        ast = parser.parse(preprocessed, filename=filename)

        converter = ASTConverter(filename)
        return converter.convert(ast)

    def _preprocess(
        self,
        code: str,
        include_dirs: list[str] | None = None,
        extra_args: list[str] | None = None,
    ) -> str:
        """Preprocess C code using the system's C preprocessor.

        :param code: C source code to preprocess.
        :param include_dirs: Additional include directories.
        :param extra_args: Extra preprocessor arguments (e.g., -DFOO=1).
        :returns: Preprocessed code.
        :raises RuntimeError: If preprocessing fails.
        """
        if include_dirs is None:
            include_dirs = []
        if extra_args is None:
            extra_args = []

        # Build include paths
        includes: list[str] = []
        if platform.system() == "Darwin":
            cmd = ["clang", "-E"]
            includes.append(str(DARWIN_HEADERS_DIR))
        else:
            cmd = ["cpp"]
        includes.append(str(BUILTIN_HEADERS_DIR))

        # Build command
        cmd += [f"-I{inc}" for inc in includes]
        cmd += ["-nostdinc", "-iquote"]
        cmd += [f"-I{inc}" for inc in includes]
        cmd += [
            "-D__attribute__(x)=",
            "-D__extension__=",
            "-D__inline=",
            "-D__asm=",
        ]
        # Add user-specified include dirs
        for inc in include_dirs:
            cmd.append(f"-I{inc}")
        cmd += extra_args
        cmd.append("-")

        with subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        ) as proc:
            stdout, stderr = proc.communicate(input=code.encode("utf-8"))
            if proc.returncode != 0:
                raise RuntimeError(
                    f"C preprocessor failed (exit {proc.returncode}): " f"{stderr.decode('utf-8', errors='replace')}"
                )

        result = stdout.decode("utf-8")
        return result.replace("\r\n", "\n")

parse(code, filename, include_dirs=None, extra_args=None)

Parse C code using pycparser.

The code is automatically preprocessed using the system's C preprocessor (cpp on Unix/Mac, clang -E on macOS, or cl.exe /E on Windows).

Parameters:

Name Type Description Default
code str

C source code to parse.

required
filename str

Source filename for error messages and location tracking.

required
include_dirs list[str] | None

Additional include directories for the preprocessor.

None
extra_args list[str] | None

Extra arguments to pass to the preprocessor.

None

Returns:

Type Description
Header

:class:~autopxd.ir.Header containing parsed declarations.

Raises:

Type Description
RuntimeError

If preprocessing fails.

pycparser.plyparser.ParseError

If the code has syntax errors.

Source code in autopxd/backends/pycparser_backend.py
def parse(
    self,
    code: str,
    filename: str,
    include_dirs: list[str] | None = None,
    extra_args: list[str] | None = None,
) -> Header:
    """Parse C code using pycparser.

    The code is automatically preprocessed using the system's C preprocessor
    (``cpp`` on Unix/Mac, ``clang -E`` on macOS, or ``cl.exe /E`` on Windows).

    :param code: C source code to parse.
    :param filename: Source filename for error messages and location tracking.
    :param include_dirs: Additional include directories for the preprocessor.
    :param extra_args: Extra arguments to pass to the preprocessor.
    :returns: :class:`~autopxd.ir.Header` containing parsed declarations.
    :raises RuntimeError: If preprocessing fails.
    :raises pycparser.plyparser.ParseError: If the code has syntax errors.
    """
    # pylint: disable=import-outside-toplevel
    from pycparser import (
        c_parser,
    )

    # Preprocess the code
    preprocessed = self._preprocess(code, include_dirs, extra_args)

    parser = c_parser.CParser()
    ast = parser.parse(preprocessed, filename=filename)

    converter = ASTConverter(filename)
    return converter.convert(ast)

libclang Backend

libclang_backend

libclang-based parser backend.

This backend uses libclang (LLVM's C/C++ parser) to parse header files. It provides full C/C++ support including templates, namespaces, and classes.

Requirements

  • System libclang library must be installed
  • Python clang2 bindings version must match system libclang version (e.g., clang2==18.* for LLVM 18)

If system libclang is not available, autopxd2 automatically falls back to the pycparser backend (C99 only).

Advantages over pycparser

  • Full C++ support (classes, templates, namespaces)
  • Handles complex preprocessor constructs
  • Uses the same parser as production compilers
  • Better error messages with source locations

Limitations

  • Macro extraction is limited due to Python bindings constraints
  • Requires system libclang installation

Example

::

from autopxd.backends.libclang_backend import LibclangBackend

backend = LibclangBackend()
header = backend.parse(code, "myheader.hpp", extra_args=["-std=c++17"])

LibclangBackend

Parser backend using libclang.

Uses LLVM's libclang to parse C and C++ code. This backend supports the full C++ language including templates, classes, and namespaces.

Properties

name : str Returns "libclang". supports_macros : bool Returns False - macro extraction is limited in Python bindings. supports_cpp : bool Returns True - full C++ support.

Example

::

from autopxd.backends.libclang_backend import LibclangBackend

backend = LibclangBackend()

# Parse C++ code with specific standard
header = backend.parse(
    code,
    "myheader.hpp",
    extra_args=["-std=c++17", "-DDEBUG=1"]
)
Source code in autopxd/backends/libclang_backend.py
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
class LibclangBackend:
    """Parser backend using libclang.

    Uses LLVM's libclang to parse C and C++ code. This backend supports
    the full C++ language including templates, classes, and namespaces.

    Properties
    ----------
    name : str
        Returns ``"libclang"``.
    supports_macros : bool
        Returns ``False`` - macro extraction is limited in Python bindings.
    supports_cpp : bool
        Returns ``True`` - full C++ support.

    Example
    -------
    ::

        from autopxd.backends.libclang_backend import LibclangBackend

        backend = LibclangBackend()

        # Parse C++ code with specific standard
        header = backend.parse(
            code,
            "myheader.hpp",
            extra_args=["-std=c++17", "-DDEBUG=1"]
        )
    """

    def __init__(self) -> None:
        self._index: clang.cindex.Index | None = None
        # Cache for parsed headers (path -> Header) to avoid re-parsing
        self._parse_cache: dict[str, Header] = {}
        # Visited set to prevent circular includes
        self._visited: set[str] = set()

    @property
    def name(self) -> str:
        return "libclang"

    @property
    def supports_macros(self) -> bool:
        # Supports simple numeric macros (#define NAME 123)
        # Complex macros (expressions, function-like) are not supported
        return True

    @property
    def supports_cpp(self) -> bool:
        return True

    def _get_index(self) -> "clang.cindex.Index":
        """Get or create the clang index."""
        if self._index is None:
            self._index = clang.cindex.Index.create()
        return self._index

    def _resolve_include_path(
        self,
        include_path: str,
        base_dir: str,
        include_dirs: list[str],
    ) -> str | None:
        """Resolve an include path to an absolute path.

        :param include_path: The include path as it appears in the header
        :param base_dir: Directory of the including file
        :param include_dirs: List of include search directories
        :returns: Absolute path to the header file, or None if not found
        """
        # If already absolute, return as-is
        if os.path.isabs(include_path):
            if os.path.exists(include_path):
                return os.path.abspath(include_path)
            return None

        # Try relative to base directory first
        candidate = os.path.join(base_dir, include_path)
        if os.path.exists(candidate):
            return os.path.abspath(candidate)

        # Try each include directory
        for inc_dir in include_dirs:
            candidate = os.path.join(inc_dir, include_path)
            if os.path.exists(candidate):
                return os.path.abspath(candidate)

        return None

    def _parse_header_file(
        self,
        header_path: str,
        include_dirs: list[str],
        extra_args: list[str],
        use_default_includes: bool,
    ) -> Header:
        """Parse a single header file.

        :param header_path: Absolute path to header file
        :param include_dirs: Include directories
        :param extra_args: Extra compiler arguments
        :param use_default_includes: Whether to use system includes
        :returns: Parsed Header IR
        """
        # Check cache
        if header_path in self._parse_cache:
            return self._parse_cache[header_path]

        # Read the file
        with open(header_path, encoding="utf-8", errors="replace") as f:
            code = f.read()

        # Parse using the main parse method
        # Use the basename for the filename to match expected behavior
        filename = os.path.basename(header_path)
        header = self.parse(
            code,
            filename,
            include_dirs=include_dirs,
            extra_args=extra_args,
            use_default_includes=use_default_includes,
            recursive_includes=False,  # Prevent infinite recursion
        )

        # Cache the result
        self._parse_cache[header_path] = header
        return header

    def _parse_recursively(
        self,
        main_header: Header,
        main_path: str,
        include_dirs: list[str],
        extra_args: list[str],
        use_default_includes: bool,
        max_depth: int,
        current_depth: int = 0,
        project_prefixes: tuple[str, ...] | None = None,
    ) -> Header:
        """Recursively parse included headers and combine declarations.

        :param main_header: The main header that was parsed
        :param main_path: Path to the main header file
        :param include_dirs: Include directories
        :param extra_args: Extra compiler arguments
        :param use_default_includes: Whether to use system includes
        :param max_depth: Maximum recursion depth
        :param current_depth: Current recursion depth
        :param project_prefixes: Optional tuple of path prefixes to treat as project (not system)
        :returns: Combined Header with declarations from all includes
        """
        if current_depth >= max_depth:
            return main_header

        all_declarations: list[Declaration] = list(main_header.declarations)
        main_dir = os.path.dirname(os.path.abspath(main_path))

        # Process each included header
        for include_path in main_header.included_headers:
            # Skip system headers (unless whitelisted via project_prefixes)
            if _is_system_header(include_path, project_prefixes):
                continue

            # Get absolute path
            abs_path = self._resolve_include_path(
                include_path,
                main_dir,
                include_dirs,
            )

            if abs_path is None:
                # Could not resolve - skip
                continue

            # Check if already visited (circular include)
            if abs_path in self._visited:
                continue

            self._visited.add(abs_path)

            try:
                # Parse the included header
                sub_header = self._parse_header_file(
                    abs_path,
                    include_dirs,
                    extra_args,
                    use_default_includes,
                )

                # Recursively process its includes
                sub_header = self._parse_recursively(
                    sub_header,
                    abs_path,
                    include_dirs,
                    extra_args,
                    use_default_includes,
                    max_depth,
                    current_depth + 1,
                    project_prefixes,
                )

                # Add declarations from sub-header
                all_declarations.extend(sub_header.declarations)

            except Exception:
                # Skip headers that fail to parse
                # This is common with complex system headers
                continue

        # Deduplicate declarations
        unique_declarations = _deduplicate_declarations(all_declarations)

        # Return combined header
        return Header(
            path=main_header.path,
            declarations=unique_declarations,
            included_headers=main_header.included_headers,
        )

    def parse(
        self,
        code: str,
        filename: str,
        include_dirs: list[str] | None = None,
        extra_args: list[str] | None = None,
        use_default_includes: bool = True,
        recursive_includes: bool = True,
        max_depth: int = 10,
        project_prefixes: tuple[str, ...] | None = None,
    ) -> Header:
        """Parse C/C++ code using libclang.

        Unlike the pycparser backend, this method handles raw (unpreprocessed)
        code and performs preprocessing internally.

        Umbrella header support: If the header has few/no declarations but many
        includes (umbrella header pattern), this method can recursively parse the
        included headers and combine their declarations.

        :param code: C/C++ source code to parse (raw, not preprocessed).
        :param filename: Source filename for error messages and location tracking.
        :param include_dirs: Additional include directories (converted to ``-I`` flags).
        :param extra_args: Additional compiler arguments (e.g., ``["-std=c++17"]``).
        :param use_default_includes: If True (default), automatically detect and add
            system include directories by querying the system clang compiler.
            Set to False to disable this behavior.
        :param recursive_includes: If True (default), detect umbrella headers and
            recursively parse included project headers. System headers are always
            skipped. Set to False to only parse the main file.
        :param max_depth: Maximum recursion depth for include processing (default 10).
            Prevents infinite recursion from circular includes.
        :param project_prefixes: Optional tuple of path prefixes to treat as project
            headers (not system). Use this for umbrella headers of libraries installed
            in system locations (e.g., ``("/opt/homebrew/include/sodium",)``).
        :returns: :class:`~autopxd.ir.Header` containing parsed declarations.
        :raises RuntimeError: If parsing fails with errors.

        Example
        -------
        ::

            # Basic usage
            header = backend.parse(
                code,
                "myheader.hpp",
                include_dirs=["/usr/local/include"],
                extra_args=["-std=c++17", "-DNDEBUG"]
            )

            # Umbrella header (all-includes) pattern
            header = backend.parse(
                code,
                "LibraryAll.h",
                include_dirs=["./include"],
                recursive_includes=True  # Auto-detect and expand includes
            )

            # Umbrella header in system location
            header = backend.parse(
                code,
                "sodium.h",
                include_dirs=["/opt/homebrew/include"],
                project_prefixes=("/opt/homebrew/include/sodium",)  # Whitelist sodium/*
            )
        """
        args: list[str] = []

        # Detect C++ mode from extra_args
        is_cplus = bool(extra_args and any(arg in ("-x", "c++") or arg.startswith("-std=c++") for arg in extra_args))

        # Add user-specified include directories FIRST
        # This is important for C++ where user headers may need to come before system libc++
        if include_dirs:
            for inc_dir in include_dirs:
                args.append(f"-I{inc_dir}")

        # Add system include directories if enabled
        # Always add them when use_default_includes=True, regardless of other -I flags
        if use_default_includes:
            args.extend(get_system_include_dirs(cplus=is_cplus))

        # Add extra arguments
        if extra_args:
            args.extend(extra_args)

        # Parse the code with detailed preprocessing record for macro extraction
        index = self._get_index()
        tu = index.parse(
            filename,
            args=args,
            unsaved_files=[(filename, code)],
            options=clang.cindex.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD,
        )

        # Check for fatal errors
        for diag in tu.diagnostics:
            if diag.severity >= clang.cindex.Diagnostic.Error:
                raise RuntimeError(f"Parse error: {diag.spelling}")

        # Collect included headers
        included_headers: set[str] = set()
        for inclusion in tu.get_includes():
            # inclusion.include is a File with name attribute
            header_path = str(inclusion.include.name)
            # Store full path - caller can extract basename if needed
            included_headers.add(header_path)

        # Convert to IR
        converter = ClangASTConverter(filename, project_prefixes=project_prefixes)
        header = converter.convert(tu)

        # Attach included headers to the IR
        header.included_headers = included_headers

        # Check if we should do recursive include processing
        if recursive_includes and _is_umbrella_header(header, project_prefixes=project_prefixes):
            # Reset visited set for each top-level parse
            self._visited = set()
            # Add current file to visited
            if os.path.exists(filename):
                abs_filename = os.path.abspath(filename)
            else:
                # For in-memory code, use filename as-is
                abs_filename = filename
            self._visited.add(abs_filename)

            # Recursively parse included headers
            header = self._parse_recursively(
                header,
                abs_filename,
                include_dirs or [],
                extra_args or [],
                use_default_includes,
                max_depth,
                project_prefixes=project_prefixes,
            )

        return header

parse(code, filename, include_dirs=None, extra_args=None, use_default_includes=True, recursive_includes=True, max_depth=10, project_prefixes=None)

Parse C/C++ code using libclang.

Unlike the pycparser backend, this method handles raw (unpreprocessed) code and performs preprocessing internally.

Umbrella header support: If the header has few/no declarations but many includes (umbrella header pattern), this method can recursively parse the included headers and combine their declarations.

::

# Basic usage
header = backend.parse(
    code,
    "myheader.hpp",
    include_dirs=["/usr/local/include"],
    extra_args=["-std=c++17", "-DNDEBUG"]
)

# Umbrella header (all-includes) pattern
header = backend.parse(
    code,
    "LibraryAll.h",
    include_dirs=["./include"],
    recursive_includes=True  # Auto-detect and expand includes
)

# Umbrella header in system location
header = backend.parse(
    code,
    "sodium.h",
    include_dirs=["/opt/homebrew/include"],
    project_prefixes=("/opt/homebrew/include/sodium",)  # Whitelist sodium/*
)

Parameters:

Name Type Description Default
code str

C/C++ source code to parse (raw, not preprocessed).

required
filename str

Source filename for error messages and location tracking.

required
include_dirs list[str] | None

Additional include directories (converted to -I flags).

None
extra_args list[str] | None

Additional compiler arguments (e.g., ["-std=c++17"]).

None
use_default_includes bool

If True (default), automatically detect and add system include directories by querying the system clang compiler. Set to False to disable this behavior.

True
recursive_includes bool

If True (default), detect umbrella headers and recursively parse included project headers. System headers are always skipped. Set to False to only parse the main file.

True
max_depth int

Maximum recursion depth for include processing (default 10). Prevents infinite recursion from circular includes.

10
project_prefixes tuple[str, ...] | None

Optional tuple of path prefixes to treat as project headers (not system). Use this for umbrella headers of libraries installed in system locations (e.g., ("/opt/homebrew/include/sodium",)).

None

Returns:

Type Description
Header

:class:~autopxd.ir.Header containing parsed declarations.

Raises:

Type Description
RuntimeError

If parsing fails with errors. Example -------

Source code in autopxd/backends/libclang_backend.py
def parse(
    self,
    code: str,
    filename: str,
    include_dirs: list[str] | None = None,
    extra_args: list[str] | None = None,
    use_default_includes: bool = True,
    recursive_includes: bool = True,
    max_depth: int = 10,
    project_prefixes: tuple[str, ...] | None = None,
) -> Header:
    """Parse C/C++ code using libclang.

    Unlike the pycparser backend, this method handles raw (unpreprocessed)
    code and performs preprocessing internally.

    Umbrella header support: If the header has few/no declarations but many
    includes (umbrella header pattern), this method can recursively parse the
    included headers and combine their declarations.

    :param code: C/C++ source code to parse (raw, not preprocessed).
    :param filename: Source filename for error messages and location tracking.
    :param include_dirs: Additional include directories (converted to ``-I`` flags).
    :param extra_args: Additional compiler arguments (e.g., ``["-std=c++17"]``).
    :param use_default_includes: If True (default), automatically detect and add
        system include directories by querying the system clang compiler.
        Set to False to disable this behavior.
    :param recursive_includes: If True (default), detect umbrella headers and
        recursively parse included project headers. System headers are always
        skipped. Set to False to only parse the main file.
    :param max_depth: Maximum recursion depth for include processing (default 10).
        Prevents infinite recursion from circular includes.
    :param project_prefixes: Optional tuple of path prefixes to treat as project
        headers (not system). Use this for umbrella headers of libraries installed
        in system locations (e.g., ``("/opt/homebrew/include/sodium",)``).
    :returns: :class:`~autopxd.ir.Header` containing parsed declarations.
    :raises RuntimeError: If parsing fails with errors.

    Example
    -------
    ::

        # Basic usage
        header = backend.parse(
            code,
            "myheader.hpp",
            include_dirs=["/usr/local/include"],
            extra_args=["-std=c++17", "-DNDEBUG"]
        )

        # Umbrella header (all-includes) pattern
        header = backend.parse(
            code,
            "LibraryAll.h",
            include_dirs=["./include"],
            recursive_includes=True  # Auto-detect and expand includes
        )

        # Umbrella header in system location
        header = backend.parse(
            code,
            "sodium.h",
            include_dirs=["/opt/homebrew/include"],
            project_prefixes=("/opt/homebrew/include/sodium",)  # Whitelist sodium/*
        )
    """
    args: list[str] = []

    # Detect C++ mode from extra_args
    is_cplus = bool(extra_args and any(arg in ("-x", "c++") or arg.startswith("-std=c++") for arg in extra_args))

    # Add user-specified include directories FIRST
    # This is important for C++ where user headers may need to come before system libc++
    if include_dirs:
        for inc_dir in include_dirs:
            args.append(f"-I{inc_dir}")

    # Add system include directories if enabled
    # Always add them when use_default_includes=True, regardless of other -I flags
    if use_default_includes:
        args.extend(get_system_include_dirs(cplus=is_cplus))

    # Add extra arguments
    if extra_args:
        args.extend(extra_args)

    # Parse the code with detailed preprocessing record for macro extraction
    index = self._get_index()
    tu = index.parse(
        filename,
        args=args,
        unsaved_files=[(filename, code)],
        options=clang.cindex.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD,
    )

    # Check for fatal errors
    for diag in tu.diagnostics:
        if diag.severity >= clang.cindex.Diagnostic.Error:
            raise RuntimeError(f"Parse error: {diag.spelling}")

    # Collect included headers
    included_headers: set[str] = set()
    for inclusion in tu.get_includes():
        # inclusion.include is a File with name attribute
        header_path = str(inclusion.include.name)
        # Store full path - caller can extract basename if needed
        included_headers.add(header_path)

    # Convert to IR
    converter = ClangASTConverter(filename, project_prefixes=project_prefixes)
    header = converter.convert(tu)

    # Attach included headers to the IR
    header.included_headers = included_headers

    # Check if we should do recursive include processing
    if recursive_includes and _is_umbrella_header(header, project_prefixes=project_prefixes):
        # Reset visited set for each top-level parse
        self._visited = set()
        # Add current file to visited
        if os.path.exists(filename):
            abs_filename = os.path.abspath(filename)
        else:
            # For in-memory code, use filename as-is
            abs_filename = filename
        self._visited.add(abs_filename)

        # Recursively parse included headers
        header = self._parse_recursively(
            header,
            abs_filename,
            include_dirs or [],
            extra_args or [],
            use_default_includes,
            max_depth,
            project_prefixes=project_prefixes,
        )

    return header