Skip to content

C/C++ Analysis

This page documents the C and C++ related APIs in the CLDK library.

Use the table of contents to navigate classes, functions, and submodules exposed under the C/C++ analysis and schema packages.

Analysis#

C/C++ analysis utilities and workflows.

C analysis utilities.

Provides a high-level API to analyze C projects using a Clang-based analyzer and to query functions, macros, typedefs, structs/unions, enums, and globals.

CAnalysis #

Source code in cldk/analysis/c/c_analysis.py
class CAnalysis:

    def __init__(self, project_dir: Path) -> None:
        """Initialize the C analysis backend.

        Args:
            project_dir (Path): Path to the C project directory.
        """
        if not isinstance(project_dir, Path):
            project_dir = Path(project_dir)
        self.c_application = self._init_application(project_dir)

    def _init_application(self, project_dir: Path) -> CApplication:
        """Construct the C application model from project sources.

        Args:
            project_dir (Path): Path to the project directory.

        Returns:
            CApplication: Application model.

        Examples:
            Build an application model from a project directory:

            >>> from pathlib import Path
            >>> ca = CAnalysis(project_dir=Path('.'))  # doctest: +SKIP
            >>> isinstance(ca.get_c_application(), CApplication)  # doctest: +SKIP
            True
        """
        analyzer = ClangAnalyzer()

        # Analyze each file
        translation_units = {}
        for source_file in project_dir.rglob("*.c"):
            tu = analyzer.analyze_file(source_file)
            translation_units[str(source_file)] = tu

        # Create application model
        return CApplication(translation_units=translation_units)

    def get_c_application(self) -> CApplication:
        """Return the C application object.

        Returns:
            CApplication: Application model.

        Examples:
            >>> # Assuming CAnalysis was constructed
            >>> isinstance(CAnalysis(project_dir=Path('.')).get_c_application(), CApplication)  # doctest: +SKIP
            True
        """
        return self.c_application

    def get_imports(self) -> List[str]:
        """Return all include/import statements in the project.

        Raises:
            NotImplementedError: This functionality is not implemented yet.

        Examples:
            >>> from pathlib import Path
            >>> CAnalysis(project_dir=Path('.')).get_imports()  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_variables(self, **kwargs):
        """Return all variables discovered across the project.

        Raises:
            NotImplementedError: This functionality is not implemented yet.

        Examples:
            >>> from pathlib import Path
            >>> CAnalysis(project_dir=Path('.')).get_variables()  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_application_view(self) -> CApplication:
        """Return the application view of the C project.

        Returns:
            CApplication: Application model summarizing translation units.

        Examples:
            >>> from pathlib import Path
            >>> ca = CAnalysis(project_dir=Path('.'))  # doctest: +SKIP
            >>> isinstance(ca.get_application_view(), CApplication)  # doctest: +SKIP
            True
        """
        return self.c_application

    def get_symbol_table(self) -> Dict[str, CTranslationUnit]:
        """Return a symbol table view keyed by file path.

        Raises:
            NotImplementedError: This functionality is not implemented yet.

        Examples:
            >>> from pathlib import Path
            >>> CAnalysis(project_dir=Path('.')).get_symbol_table()  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_compilation_units(self) -> List[CTranslationUnit]:
        """Return all compilation units parsed from C sources.

        Raises:
            NotImplementedError: This functionality is not implemented yet.

        Examples:
            >>> from pathlib import Path
            >>> CAnalysis(project_dir=Path('.')).get_compilation_units()  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def is_parsable(self, source_code: str) -> bool:
        """Check if the source code is parsable using Clang.

        Args:
            source_code (str): Source code to parse.

        Returns:
            bool: True if parsable, False otherwise.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).is_parsable('int f(){return 1;}')  # doctest: +SKIP
            True
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_call_graph(self) -> nx.DiGraph:
        """Return the call graph of the C code.

        Returns:
            networkx.DiGraph: Call graph.

        Examples:
            >>> isinstance(CAnalysis(project_dir=Path('.')).get_call_graph(), nx.DiGraph)  # doctest: +SKIP
            True
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_call_graph_json(self) -> str:
        """Return the call graph serialized as JSON.

        Returns:
            str: Call graph encoded as JSON.

        Raises:
            NotImplementedError: Single-file mode unsupported.

        Examples:
            >>> isinstance(CAnalysis(project_dir=Path('.')).get_call_graph_json(), str)  # doctest: +SKIP
            True
        """

        raise NotImplementedError("Producing a call graph over a single file is not implemented yet.")

    def get_callers(self, function: CFunction) -> Dict:
        """Return callers of a function.

        Args:
            function (CFunction): Target function.

        Returns:
            dict: Mapping of callers to call sites/details.

        Raises:
            NotImplementedError: Not implemented yet.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).get_callers(CFunction(name='f', return_type='int', parameters=[], storage_class=None, is_inline=False, is_variadic=False, body='', comment='', call_sites=[], local_variables=[], start_line=1, end_line=1))  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Generating all callers over a single file is not implemented yet.
        """

        raise NotImplementedError("Generating all callers over a single file is not implemented yet.")

    def get_callees(self, function: CFunction) -> Dict:
        """Return callees of a function.

        Args:
            function (CFunction): Source function.

        Returns:
            dict: Callee details.

        Raises:
            NotImplementedError: Not implemented yet.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).get_callees(CFunction(name='f', return_type='int', parameters=[], storage_class=None, is_inline=False, is_variadic=False, body='', comment='', call_sites=[], local_variables=[], start_line=1, end_line=1))  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Generating all callees over a single file is not implemented yet.
        """
        raise NotImplementedError("Generating all callees over a single file is not implemented yet.")

    def get_functions(self) -> Dict[str, CFunction]:
        """Return all functions in the project.

        Returns:
            dict[str, CFunction]: Functions keyed by signature/name for a translation unit.

        Examples:
            >>> funcs = CAnalysis(project_dir=Path('.')).get_functions()  # doctest: +SKIP
            >>> isinstance(funcs, dict)  # doctest: +SKIP
            True
        """
        for _, translation_unit in self.c_application.translation_units.items():
            return translation_unit.functions

    def get_function(self, function_name: str, file_name: Optional[str]) -> CFunction | List[CFunction]:
        """Return a function object.

        Args:
            function_name (str): Function name.
            file_name (str | None): Optional file name.

        Returns:
            CFunction | list[CFunction]: Function object(s) matching the query.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).get_function('main', None)  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_C_file(self, file_name: str) -> str:
        """Return a C file path by name.

        Args:
            file_name (str): File name.

        Returns:
            str: C source file path.

        Raises:
            NotImplementedError: Not implemented yet.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).get_C_file('hello.c')  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_C_compilation_unit(self, file_path: str) -> CTranslationUnit:
        """Return the compilation unit for a C source file.

        Args:
            file_path (str): Absolute path to a C source file.

        Returns:
            CTranslationUnit: Compilation unit object.

        Examples:
            >>> # Retrieve a compilation unit by path
            >>> cu = CAnalysis(project_dir=Path('.')).get_C_compilation_unit('file.c')  # doctest: +SKIP
            >>> (cu is None) or hasattr(cu, 'functions')  # doctest: +SKIP
            True
        """
        return self.c_application.translation_units.get(file_path)

    def get_functions_in_file(self, file_name: str) -> List[CFunction]:
        """Return all functions in a given file.

        Args:
            file_name (str): File name.

        Returns:
            list[CFunction]: Functions in the file.

        Raises:
            NotImplementedError: Not implemented yet.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).get_functions_in_file('file.c')  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_macros(self) -> List[CMacro]:
        """Return all macros in the project.

        Returns:
            list[CMacro]: All macros.

        Raises:
            NotImplementedError: Not implemented yet.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).get_macros()  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

    def get_macros_in_file(self, file_name: str) -> List[CMacro] | None:
        """Return all macros in the given file.

        Args:
            file_name (str): File name.

        Returns:
            list[CMacro] | None: Macros in the file, or None if not found.

        Raises:
            NotImplementedError: Not implemented yet.

        Examples:
            >>> CAnalysis(project_dir=Path('.')).get_macros_in_file('file.c')  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            NotImplementedError: Support for this functionality has not been implemented yet.
        """
        raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_c_application() #

Return the C application object.

Returns:

Name Type Description
CApplication CApplication

Application model.

Examples:

>>> # Assuming CAnalysis was constructed
>>> isinstance(CAnalysis(project_dir=Path('.')).get_c_application(), CApplication)
True
Source code in cldk/analysis/c/c_analysis.py
def get_c_application(self) -> CApplication:
    """Return the C application object.

    Returns:
        CApplication: Application model.

    Examples:
        >>> # Assuming CAnalysis was constructed
        >>> isinstance(CAnalysis(project_dir=Path('.')).get_c_application(), CApplication)  # doctest: +SKIP
        True
    """
    return self.c_application

get_imports() #

Return all include/import statements in the project.

Raises:

Type Description
NotImplementedError

This functionality is not implemented yet.

Examples:

>>> from pathlib import Path
>>> CAnalysis(project_dir=Path('.')).get_imports()
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_imports(self) -> List[str]:
    """Return all include/import statements in the project.

    Raises:
        NotImplementedError: This functionality is not implemented yet.

    Examples:
        >>> from pathlib import Path
        >>> CAnalysis(project_dir=Path('.')).get_imports()  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_variables(**kwargs) #

Return all variables discovered across the project.

Raises:

Type Description
NotImplementedError

This functionality is not implemented yet.

Examples:

>>> from pathlib import Path
>>> CAnalysis(project_dir=Path('.')).get_variables()
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_variables(self, **kwargs):
    """Return all variables discovered across the project.

    Raises:
        NotImplementedError: This functionality is not implemented yet.

    Examples:
        >>> from pathlib import Path
        >>> CAnalysis(project_dir=Path('.')).get_variables()  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_application_view() #

Return the application view of the C project.

Returns:

Name Type Description
CApplication CApplication

Application model summarizing translation units.

Examples:

>>> from pathlib import Path
>>> ca = CAnalysis(project_dir=Path('.'))
>>> isinstance(ca.get_application_view(), CApplication)
True
Source code in cldk/analysis/c/c_analysis.py
def get_application_view(self) -> CApplication:
    """Return the application view of the C project.

    Returns:
        CApplication: Application model summarizing translation units.

    Examples:
        >>> from pathlib import Path
        >>> ca = CAnalysis(project_dir=Path('.'))  # doctest: +SKIP
        >>> isinstance(ca.get_application_view(), CApplication)  # doctest: +SKIP
        True
    """
    return self.c_application

get_symbol_table() #

Return a symbol table view keyed by file path.

Raises:

Type Description
NotImplementedError

This functionality is not implemented yet.

Examples:

>>> from pathlib import Path
>>> CAnalysis(project_dir=Path('.')).get_symbol_table()
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_symbol_table(self) -> Dict[str, CTranslationUnit]:
    """Return a symbol table view keyed by file path.

    Raises:
        NotImplementedError: This functionality is not implemented yet.

    Examples:
        >>> from pathlib import Path
        >>> CAnalysis(project_dir=Path('.')).get_symbol_table()  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_compilation_units() #

Return all compilation units parsed from C sources.

Raises:

Type Description
NotImplementedError

This functionality is not implemented yet.

Examples:

>>> from pathlib import Path
>>> CAnalysis(project_dir=Path('.')).get_compilation_units()
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_compilation_units(self) -> List[CTranslationUnit]:
    """Return all compilation units parsed from C sources.

    Raises:
        NotImplementedError: This functionality is not implemented yet.

    Examples:
        >>> from pathlib import Path
        >>> CAnalysis(project_dir=Path('.')).get_compilation_units()  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

is_parsable(source_code) #

Check if the source code is parsable using Clang.

Parameters:

Name Type Description Default
source_code str

Source code to parse.

required

Returns:

Name Type Description
bool bool

True if parsable, False otherwise.

Examples:

>>> CAnalysis(project_dir=Path('.')).is_parsable('int f(){return 1;}')
True
Source code in cldk/analysis/c/c_analysis.py
def is_parsable(self, source_code: str) -> bool:
    """Check if the source code is parsable using Clang.

    Args:
        source_code (str): Source code to parse.

    Returns:
        bool: True if parsable, False otherwise.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).is_parsable('int f(){return 1;}')  # doctest: +SKIP
        True
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_call_graph() #

Return the call graph of the C code.

Returns:

Type Description
DiGraph

networkx.DiGraph: Call graph.

Examples:

>>> isinstance(CAnalysis(project_dir=Path('.')).get_call_graph(), nx.DiGraph)
True
Source code in cldk/analysis/c/c_analysis.py
def get_call_graph(self) -> nx.DiGraph:
    """Return the call graph of the C code.

    Returns:
        networkx.DiGraph: Call graph.

    Examples:
        >>> isinstance(CAnalysis(project_dir=Path('.')).get_call_graph(), nx.DiGraph)  # doctest: +SKIP
        True
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_call_graph_json() #

Return the call graph serialized as JSON.

Returns:

Name Type Description
str str

Call graph encoded as JSON.

Raises:

Type Description
NotImplementedError

Single-file mode unsupported.

Examples:

>>> isinstance(CAnalysis(project_dir=Path('.')).get_call_graph_json(), str)
True
Source code in cldk/analysis/c/c_analysis.py
def get_call_graph_json(self) -> str:
    """Return the call graph serialized as JSON.

    Returns:
        str: Call graph encoded as JSON.

    Raises:
        NotImplementedError: Single-file mode unsupported.

    Examples:
        >>> isinstance(CAnalysis(project_dir=Path('.')).get_call_graph_json(), str)  # doctest: +SKIP
        True
    """

    raise NotImplementedError("Producing a call graph over a single file is not implemented yet.")

get_callers(function) #

Return callers of a function.

Parameters:

Name Type Description Default
function CFunction

Target function.

required

Returns:

Name Type Description
dict Dict

Mapping of callers to call sites/details.

Raises:

Type Description
NotImplementedError

Not implemented yet.

Examples:

>>> CAnalysis(project_dir=Path('.')).get_callers(CFunction(name='f', return_type='int', parameters=[], storage_class=None, is_inline=False, is_variadic=False, body='', comment='', call_sites=[], local_variables=[], start_line=1, end_line=1))
Traceback (most recent call last):
NotImplementedError: Generating all callers over a single file is not implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_callers(self, function: CFunction) -> Dict:
    """Return callers of a function.

    Args:
        function (CFunction): Target function.

    Returns:
        dict: Mapping of callers to call sites/details.

    Raises:
        NotImplementedError: Not implemented yet.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).get_callers(CFunction(name='f', return_type='int', parameters=[], storage_class=None, is_inline=False, is_variadic=False, body='', comment='', call_sites=[], local_variables=[], start_line=1, end_line=1))  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Generating all callers over a single file is not implemented yet.
    """

    raise NotImplementedError("Generating all callers over a single file is not implemented yet.")

get_callees(function) #

Return callees of a function.

Parameters:

Name Type Description Default
function CFunction

Source function.

required

Returns:

Name Type Description
dict Dict

Callee details.

Raises:

Type Description
NotImplementedError

Not implemented yet.

Examples:

>>> CAnalysis(project_dir=Path('.')).get_callees(CFunction(name='f', return_type='int', parameters=[], storage_class=None, is_inline=False, is_variadic=False, body='', comment='', call_sites=[], local_variables=[], start_line=1, end_line=1))
Traceback (most recent call last):
NotImplementedError: Generating all callees over a single file is not implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_callees(self, function: CFunction) -> Dict:
    """Return callees of a function.

    Args:
        function (CFunction): Source function.

    Returns:
        dict: Callee details.

    Raises:
        NotImplementedError: Not implemented yet.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).get_callees(CFunction(name='f', return_type='int', parameters=[], storage_class=None, is_inline=False, is_variadic=False, body='', comment='', call_sites=[], local_variables=[], start_line=1, end_line=1))  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Generating all callees over a single file is not implemented yet.
    """
    raise NotImplementedError("Generating all callees over a single file is not implemented yet.")

get_functions() #

Return all functions in the project.

Returns:

Type Description
Dict[str, CFunction]

dict[str, CFunction]: Functions keyed by signature/name for a translation unit.

Examples:

>>> funcs = CAnalysis(project_dir=Path('.')).get_functions()
>>> isinstance(funcs, dict)
True
Source code in cldk/analysis/c/c_analysis.py
def get_functions(self) -> Dict[str, CFunction]:
    """Return all functions in the project.

    Returns:
        dict[str, CFunction]: Functions keyed by signature/name for a translation unit.

    Examples:
        >>> funcs = CAnalysis(project_dir=Path('.')).get_functions()  # doctest: +SKIP
        >>> isinstance(funcs, dict)  # doctest: +SKIP
        True
    """
    for _, translation_unit in self.c_application.translation_units.items():
        return translation_unit.functions

get_function(function_name, file_name) #

Return a function object.

Parameters:

Name Type Description Default
function_name str

Function name.

required
file_name str | None

Optional file name.

required

Returns:

Type Description
CFunction | List[CFunction]

CFunction | list[CFunction]: Function object(s) matching the query.

Examples:

>>> CAnalysis(project_dir=Path('.')).get_function('main', None)
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_function(self, function_name: str, file_name: Optional[str]) -> CFunction | List[CFunction]:
    """Return a function object.

    Args:
        function_name (str): Function name.
        file_name (str | None): Optional file name.

    Returns:
        CFunction | list[CFunction]: Function object(s) matching the query.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).get_function('main', None)  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_C_file(file_name) #

Return a C file path by name.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Name Type Description
str str

C source file path.

Raises:

Type Description
NotImplementedError

Not implemented yet.

Examples:

>>> CAnalysis(project_dir=Path('.')).get_C_file('hello.c')
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_C_file(self, file_name: str) -> str:
    """Return a C file path by name.

    Args:
        file_name (str): File name.

    Returns:
        str: C source file path.

    Raises:
        NotImplementedError: Not implemented yet.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).get_C_file('hello.c')  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_C_compilation_unit(file_path) #

Return the compilation unit for a C source file.

Parameters:

Name Type Description Default
file_path str

Absolute path to a C source file.

required

Returns:

Name Type Description
CTranslationUnit CTranslationUnit

Compilation unit object.

Examples:

>>> # Retrieve a compilation unit by path
>>> cu = CAnalysis(project_dir=Path('.')).get_C_compilation_unit('file.c')
>>> (cu is None) or hasattr(cu, 'functions')
True
Source code in cldk/analysis/c/c_analysis.py
def get_C_compilation_unit(self, file_path: str) -> CTranslationUnit:
    """Return the compilation unit for a C source file.

    Args:
        file_path (str): Absolute path to a C source file.

    Returns:
        CTranslationUnit: Compilation unit object.

    Examples:
        >>> # Retrieve a compilation unit by path
        >>> cu = CAnalysis(project_dir=Path('.')).get_C_compilation_unit('file.c')  # doctest: +SKIP
        >>> (cu is None) or hasattr(cu, 'functions')  # doctest: +SKIP
        True
    """
    return self.c_application.translation_units.get(file_path)

get_functions_in_file(file_name) #

Return all functions in a given file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[CFunction]

list[CFunction]: Functions in the file.

Raises:

Type Description
NotImplementedError

Not implemented yet.

Examples:

>>> CAnalysis(project_dir=Path('.')).get_functions_in_file('file.c')
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_functions_in_file(self, file_name: str) -> List[CFunction]:
    """Return all functions in a given file.

    Args:
        file_name (str): File name.

    Returns:
        list[CFunction]: Functions in the file.

    Raises:
        NotImplementedError: Not implemented yet.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).get_functions_in_file('file.c')  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_macros() #

Return all macros in the project.

Returns:

Type Description
List[CMacro]

list[CMacro]: All macros.

Raises:

Type Description
NotImplementedError

Not implemented yet.

Examples:

>>> CAnalysis(project_dir=Path('.')).get_macros()
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_macros(self) -> List[CMacro]:
    """Return all macros in the project.

    Returns:
        list[CMacro]: All macros.

    Raises:
        NotImplementedError: Not implemented yet.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).get_macros()  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_macros_in_file(file_name) #

Return all macros in the given file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[CMacro] | None

list[CMacro] | None: Macros in the file, or None if not found.

Raises:

Type Description
NotImplementedError

Not implemented yet.

Examples:

>>> CAnalysis(project_dir=Path('.')).get_macros_in_file('file.c')
Traceback (most recent call last):
NotImplementedError: Support for this functionality has not been implemented yet.
Source code in cldk/analysis/c/c_analysis.py
def get_macros_in_file(self, file_name: str) -> List[CMacro] | None:
    """Return all macros in the given file.

    Args:
        file_name (str): File name.

    Returns:
        list[CMacro] | None: Macros in the file, or None if not found.

    Raises:
        NotImplementedError: Not implemented yet.

    Examples:
        >>> CAnalysis(project_dir=Path('.')).get_macros_in_file('file.c')  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: Support for this functionality has not been implemented yet.
    """
    raise NotImplementedError("Support for this functionality has not been implemented yet.")

get_includes(self) #

Return all include statements across the project.

Returns:

Type Description
List[str]

list[str]: All include statements.

Source code in cldk/analysis/c/c_analysis.py
def get_includes(self) -> List[str]:
    """Return all include statements across the project.

    Returns:
        list[str]: All include statements.
    """
    all_includes = []
    for translation_unit in self.translation_units.values():
        all_includes.extend(translation_unit.includes)
    return all_includes

get_includes_in_file(self, file_name) #

Return include statements in a file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[str] | None

list[str] | None: Includes in the file, or None if not found.

Source code in cldk/analysis/c/c_analysis.py
def get_includes_in_file(self, file_name: str) -> List[str] | None:
    """Return include statements in a file.

    Args:
        file_name (str): File name.

    Returns:
        list[str] | None: Includes in the file, or None if not found.
    """
    if file_name in self.translation_units:
        return self.translation_units[file_name].includes
    return None

get_macros(self) #

Return all macro definitions across the project.

Returns:

Type Description
List[CMacro]

list[CMacro]: Macro definitions.

Source code in cldk/analysis/c/c_analysis.py
def get_macros(self) -> List[CMacro]:
    """Return all macro definitions across the project.

    Returns:
        list[CMacro]: Macro definitions.
    """
    all_macros = []
    for translation_unit in self.translation_units.values():
        all_macros.extend(translation_unit.macros)
    return all_macros

get_macros_in_file(self, file_name) #

Return macro definitions in a file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[CMacro] | None

list[CMacro] | None: Macros in the file, or None if not found.

Source code in cldk/analysis/c/c_analysis.py
def get_macros_in_file(self, file_name: str) -> List[CMacro] | None:
    """Return macro definitions in a file.

    Args:
        file_name (str): File name.

    Returns:
        list[CMacro] | None: Macros in the file, or None if not found.
    """
    if file_name in self.translation_units:
        return self.translation_units[file_name].macros
    return None

get_typedefs(self) #

Return typedef declarations across the project.

Returns:

Type Description
List[CTypedef]

list[CTypedef]: Typedef declarations.

Source code in cldk/analysis/c/c_analysis.py
def get_typedefs(self) -> List[CTypedef]:
    """Return typedef declarations across the project.

    Returns:
        list[CTypedef]: Typedef declarations.
    """
    all_typedefs = []
    for translation_unit in self.translation_units.values():
        all_typedefs.extend(translation_unit.typedefs)
    return all_typedefs

get_typedefs_in_file(self, file_name) #

Return typedef declarations in a file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[CTypedef] | None

list[CTypedef] | None: Typedefs in the file, or None if not found.

Source code in cldk/analysis/c/c_analysis.py
def get_typedefs_in_file(self, file_name: str) -> List[CTypedef] | None:
    """Return typedef declarations in a file.

    Args:
        file_name (str): File name.

    Returns:
        list[CTypedef] | None: Typedefs in the file, or None if not found.
    """
    if file_name in self.translation_units:
        return self.translation_units[file_name].typedefs
    return None

get_structs(self) #

Return struct/union declarations across the project.

Returns:

Type Description
List[CStruct]

list[CStruct]: Struct/union declarations.

Source code in cldk/analysis/c/c_analysis.py
def get_structs(self) -> List[CStruct]:
    """Return struct/union declarations across the project.

    Returns:
        list[CStruct]: Struct/union declarations.
    """
    all_structs = []
    for translation_unit in self.translation_units.values():
        all_structs.extend(translation_unit.structs)
    return all_structs

get_structs_in_file(self, file_name) #

Return struct/union declarations in a file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[CStruct] | None

list[CStruct] | None: Structs in the file, or None if not found.

Source code in cldk/analysis/c/c_analysis.py
def get_structs_in_file(self, file_name: str) -> List[CStruct] | None:
    """Return struct/union declarations in a file.

    Args:
        file_name (str): File name.

    Returns:
        list[CStruct] | None: Structs in the file, or None if not found.
    """
    if file_name in self.translation_units:
        return self.translation_units[file_name].structs
    return None

get_enums(self) #

Return enum declarations across the project.

Returns:

Type Description
List[CEnum]

list[CEnum]: Enum declarations.

Source code in cldk/analysis/c/c_analysis.py
def get_enums(self) -> List[CEnum]:
    """Return enum declarations across the project.

    Returns:
        list[CEnum]: Enum declarations.
    """
    all_enums = []
    for translation_unit in self.translation_units.values():
        all_enums.extend(translation_unit.enums)
    return all_enums

get_enums_in_file(self, file_name) #

Return enum declarations in a file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[CEnum] | None

list[CEnum] | None: Enums in the file, or None if not found.

Source code in cldk/analysis/c/c_analysis.py
def get_enums_in_file(self, file_name: str) -> List[CEnum] | None:
    """Return enum declarations in a file.

    Args:
        file_name (str): File name.

    Returns:
        list[CEnum] | None: Enums in the file, or None if not found.
    """
    if file_name in self.translation_units:
        return self.translation_units[file_name].enums
    return None

get_globals(self, file_name) #

Return global variable declarations in a file.

Parameters:

Name Type Description Default
file_name str

File name.

required

Returns:

Type Description
List[CVariable] | None

list[CVariable] | None: Globals in the file, or None if not found.

Source code in cldk/analysis/c/c_analysis.py
def get_globals(self, file_name: str) -> List[CVariable] | None:
    """Return global variable declarations in a file.

    Args:
        file_name (str): File name.

    Returns:
        list[CVariable] | None: Globals in the file, or None if not found.
    """
    if file_name in self.translation_units:
        return self.translation_units[file_name].globals
    return None

Schema#

Data models used by the C/C++ analyzers.

StorageClass #

Bases: Enum

Represents C storage class specifiers.

Source code in cldk/models/c/models.py
class StorageClass(Enum):
    """Represents C storage class specifiers."""

    AUTO = "auto"
    REGISTER = "register"
    STATIC = "static"
    EXTERN = "extern"
    TYPEDEF = "typedef"

CVariable #

Bases: BaseModel

Represents a variable declaration in C.

Attributes:

Name Type Description
name str

The name of the variable

type str

The type of the variable (including any type qualifiers)

storage_class Optional[StorageClass]

The storage class specifier (if any)

is_const bool

Whether the variable is const-qualified

is_volatile bool

Whether the variable is volatile-qualified

initializer str

Initial value expression, if any

array_dimensions List[str]

Dimensions if this is an array variable

is_pointer bool

Whether this is a pointer variable

pointer_level int

Level of pointer indirection (e.g., 2 for char**)

Source code in cldk/models/c/models.py
class CVariable(BaseModel):
    """Represents a variable declaration in C.

    Attributes:
        name (str): The name of the variable
        type (str): The type of the variable (including any type qualifiers)
        storage_class: The storage class specifier (if any)
        is_const (bool): Whether the variable is const-qualified
        is_volatile (bool): Whether the variable is volatile-qualified
        initializer (str): Initial value expression, if any
        array_dimensions (List[str]): Dimensions if this is an array variable
        is_pointer (bool): Whether this is a pointer variable
        pointer_level (int): Level of pointer indirection (e.g., 2 for char**)
    """

    name: str
    type: str
    storage_class: Optional[StorageClass] = None
    is_const: bool = False
    is_volatile: bool = False
    initializer: Optional[str] = None
    array_dimensions: List[str] = []
    is_pointer: bool = False
    pointer_level: int = 0
    start_line: int
    end_line: int

CFunctionPointer #

Bases: BaseModel

Represents a function pointer type.

Attributes:

Name Type Description
return_type str

Return type of the function being pointed to

parameter_types List[str]

Types of the parameters

calling_convention Optional[str]

Calling convention if specified

Source code in cldk/models/c/models.py
class CFunctionPointer(BaseModel):
    """Represents a function pointer type.

    Attributes:
        return_type (str): Return type of the function being pointed to
        parameter_types (List[str]): Types of the parameters
        calling_convention (Optional[str]): Calling convention if specified
    """

    return_type: str
    parameter_types: List[str]
    calling_convention: Optional[str] = None

CMacro #

Bases: BaseModel

Represents a C preprocessor macro.

Attributes:

Name Type Description
name str

Name of the macro

parameters List[str]

Parameters for function-like macros

replacement str

Replacement text

is_function_like bool

Whether this is a function-like macro

start_line int

Starting line in source

end_line int

Ending line in source

Source code in cldk/models/c/models.py
class CMacro(BaseModel):
    """Represents a C preprocessor macro.

    Attributes:
        name (str): Name of the macro
        parameters (List[str]): Parameters for function-like macros
        replacement (str): Replacement text
        is_function_like (bool): Whether this is a function-like macro
        start_line (int): Starting line in source
        end_line (int): Ending line in source
    """

    name: str
    parameters: List[str] = []
    replacement: str
    is_function_like: bool = False
    start_line: int
    end_line: int

CParameter #

Bases: BaseModel

Represents a parameter in a function declaration.

Attributes:

Name Type Description
name str

Parameter name (may be empty in declarations)

type str

Parameter type

is_const bool

Whether parameter is const-qualified

is_volatile bool

Whether parameter is volatile-qualified

is_pointer bool

Whether parameter is a pointer

pointer_level int

Level of pointer indirection

array_dimensions List[str]

Array dimensions if parameter is array

Source code in cldk/models/c/models.py
class CParameter(BaseModel):
    """Represents a parameter in a function declaration.

    Attributes:
        name (str): Parameter name (may be empty in declarations)
        type (str): Parameter type
        is_const (bool): Whether parameter is const-qualified
        is_volatile (bool): Whether parameter is volatile-qualified
        is_pointer (bool): Whether parameter is a pointer
        pointer_level (int): Level of pointer indirection
        array_dimensions (List[str]): Array dimensions if parameter is array
    """

    name: str
    type: str
    is_const: bool = False
    is_volatile: bool = False
    is_pointer: bool = False
    pointer_level: int = 0
    array_dimensions: List[str] = []

CCallSite #

Bases: BaseModel

Represents a function call in C code.

Attributes:

Name Type Description
function_name str

Name of the called function

argument_types List[str]

Types of the arguments

is_indirect_call bool

Whether this is a call through function pointer

is_macro_expansion bool

Whether this call is from macro expansion

return_type str

Return type of the called function

start_line int

Starting line of the call

start_column int

Starting column of the call

end_line int

Ending line of the call

end_column int

Ending column of the call

Source code in cldk/models/c/models.py
class CCallSite(BaseModel):
    """Represents a function call in C code.

    Attributes:
        function_name (str): Name of the called function
        argument_types (List[str]): Types of the arguments
        is_indirect_call (bool): Whether this is a call through function pointer
        is_macro_expansion (bool): Whether this call is from macro expansion
        return_type (str): Return type of the called function
        start_line (int): Starting line of the call
        start_column (int): Starting column of the call
        end_line (int): Ending line of the call
        end_column (int): Ending column of the call
    """

    function_name: str
    argument_types: List[str]
    is_indirect_call: bool = False
    is_macro_expansion: bool = False
    return_type: str = ""
    start_line: int
    start_column: int
    end_line: int
    end_column: int

CFunction #

Bases: BaseModel

Represents a C function.

Attributes:

Name Type Description
name str

Function name

return_type str

Return type

parameters List[CParameter]

Function parameters

storage_class Optional[StorageClass]

Storage class if specified

is_inline bool

Whether function is inline

is_const bool

Whether function is const-qualified (C++)

is_variadic bool

Whether function takes variable arguments

body str

Function body code

comment str

Associated comments/documentation

referenced_types List[str]

Types referenced in function

accessed_globals List[str]

Global variables accessed

call_sites List[CCallSite]

Function calls made

local_variables List[CVariable]

Local variable declarations

macros_used List[str]

Macros used in function

start_line int

Starting line in source

end_line int

Ending line in source

cyclomatic_complexity Optional[int]

Cyclomatic complexity if calculated

Source code in cldk/models/c/models.py
class CFunction(BaseModel):
    """Represents a C function.

    Attributes:
        name (str): Function name
        return_type (str): Return type
        parameters (List[CParameter]): Function parameters
        storage_class (Optional[StorageClass]): Storage class if specified
        is_inline (bool): Whether function is inline
        is_const (bool): Whether function is const-qualified (C++)
        is_variadic (bool): Whether function takes variable arguments
        body (str): Function body code
        comment (str): Associated comments/documentation
        referenced_types (List[str]): Types referenced in function
        accessed_globals (List[str]): Global variables accessed
        call_sites (List[CCallSite]): Function calls made
        local_variables (List[CVariable]): Local variable declarations
        macros_used (List[str]): Macros used in function
        start_line (int): Starting line in source
        end_line (int): Ending line in source
        cyclomatic_complexity (Optional[int]): Cyclomatic complexity if calculated
    """

    name: str
    return_type: str
    parameters: List[CParameter]
    storage_class: Optional[StorageClass] = None
    is_inline: bool = False
    is_const: bool = False
    is_variadic: bool = False
    body: str
    comment: str = ""
    referenced_types: List[str] = []
    accessed_globals: List[str] = []
    call_sites: List[CCallSite] = []
    local_variables: List[CVariable] = []
    macros_used: List[str] = []
    start_line: int
    end_line: int
    cyclomatic_complexity: Optional[int] = None

CStruct #

Bases: BaseModel

Represents a C struct or union.

Attributes:

Name Type Description
name str

Name of the struct

is_union bool

Whether this is a union

members List[CVariable]

Member variables

is_packed bool

Whether struct is packed

alignment Optional[int]

Specified alignment if any

comment str

Associated comments

referenced_types List[str]

Types referenced in struct

Source code in cldk/models/c/models.py
class CStruct(BaseModel):
    """Represents a C struct or union.

    Attributes:
        name (str): Name of the struct
        is_union (bool): Whether this is a union
        members (List[CVariable]): Member variables
        is_packed (bool): Whether struct is packed
        alignment (Optional[int]): Specified alignment if any
        comment (str): Associated comments
        referenced_types (List[str]): Types referenced in struct
    """

    name: str
    is_union: bool = False
    members: List[CVariable]
    is_packed: bool = False
    alignment: Optional[int] = None
    comment: str = ""
    referenced_types: List[str] = []
    start_line: int
    end_line: int

CEnum #

Bases: BaseModel

Represents a C enum declaration.

Attributes:

Name Type Description
name str

Name of the enum

constants Dict[str, int]

Enum constants and their values

comment str

Associated comments

Source code in cldk/models/c/models.py
class CEnum(BaseModel):
    """Represents a C enum declaration.

    Attributes:
        name (str): Name of the enum
        constants (Dict[str, int]): Enum constants and their values
        comment (str): Associated comments
    """

    name: str
    constants: Dict[str, int]
    comment: str = ""
    start_line: int
    end_line: int

CTypedef #

Bases: BaseModel

Represents a typedef declaration.

Attributes:

Name Type Description
name str

New type name being defined

underlying_type str

The actual type being aliased

is_function_pointer bool

Whether this is a function pointer typedef

function_pointer Optional[CFunctionPointer]

Details if this is a function pointer typedef

Source code in cldk/models/c/models.py
class CTypedef(BaseModel):
    """Represents a typedef declaration.

    Attributes:
        name (str): New type name being defined
        underlying_type (str): The actual type being aliased
        is_function_pointer (bool): Whether this is a function pointer typedef
        function_pointer: Details if this is a function pointer typedef
    """

    name: str
    underlying_type: str
    is_function_pointer: bool = False
    function_pointer: Optional[CFunctionPointer] = None
    start_line: int
    end_line: int

CInclude #

Bases: BaseModel

Represents a C include directive.

Attributes:

Name Type Description
name str

Name of the included file

is_system bool

Whether this is a system include

line_number int

Line number in source

full_text str

Full text of the include directive

Source code in cldk/models/c/models.py
class CInclude(BaseModel):
    """Represents a C include directive.

    Attributes:
        name (str): Name of the included file
        is_system (bool): Whether this is a system include
        line_number (int): Line number in source
        full_text (str): Full text of the include directive
    """

    name: str
    is_system: bool
    line_number: int
    full_text: str

CTranslationUnit #

Bases: BaseModel

Represents a C source file.

Attributes:

Name Type Description
file_path str

Path to the source file

includes List[str]

Header files included

macros List[CMacro]

Macro definitions

typedefs List[CTypedef]

Typedef declarations

structs List[CStruct]

Struct/union declarations

enums List[CEnum]

Enum declarations

globals List[CVariable]

Global variable declarations

functions Dict[str, CFunction]

Function declarations/definitions

is_header bool

Whether this is a header file

Source code in cldk/models/c/models.py
class CTranslationUnit(BaseModel):
    """Represents a C source file.

    Attributes:
        file_path (str): Path to the source file
        includes (List[str]): Header files included
        macros (List[CMacro]): Macro definitions
        typedefs (List[CTypedef]): Typedef declarations
        structs (List[CStruct]): Struct/union declarations
        enums (List[CEnum]): Enum declarations
        globals (List[CVariable]): Global variable declarations
        functions (Dict[str, CFunction]): Function declarations/definitions
        is_header (bool): Whether this is a header file
    """

    file_path: str
    includes: List[CInclude] = []
    macros: List[CMacro] = []
    typedefs: List[CTypedef] = []
    structs: List[CStruct] = []
    enums: List[CEnum] = []
    globals: List[CVariable] = []
    functions: Dict[str, CFunction] = {}
    is_header: bool = False
    is_modified: bool = False

CFunctionDetail #

Bases: BaseModel

Represents detailed information about a function.

Attributes:

Name Type Description
function_declaration str

Full function declaration

file_path str

Path to the file containing the function

function CFunction

Detailed function information

Source code in cldk/models/c/models.py
class CFunctionDetail(BaseModel):
    """Represents detailed information about a function.

    Attributes:
        function_declaration (str): Full function declaration
        file_path (str): Path to the file containing the function
        function (CFunction): Detailed function information
    """

    function_declaration: str
    file_path: str
    function: CFunction

    def __hash__(self):
        return hash((self.function_declaration, self.file_path))

CCallGraphEdge #

Bases: BaseModel

Represents an edge in the call graph.

Attributes:

Name Type Description
source CFunctionDetail

Calling function

target CFunctionDetail

Called function

type str

Type of call relationship

weight str

Edge weight/importance

is_indirect bool

Whether this is through function pointer

Source code in cldk/models/c/models.py
class CCallGraphEdge(BaseModel):
    """Represents an edge in the call graph.

    Attributes:
        source (CFunctionDetail): Calling function
        target (CFunctionDetail): Called function
        type (str): Type of call relationship
        weight (str): Edge weight/importance
        is_indirect (bool): Whether this is through function pointer
    """

    source: CFunctionDetail
    target: CFunctionDetail
    type: str
    weight: str
    is_indirect: bool = False

CApplication #

Bases: BaseModel

Represents a complete C application.

Attributes:

Name Type Description
translation_units Dict[str, CTranslationUnit]

All source files

call_graph List[CCallGraphEdge]

Function call relationships

Source code in cldk/models/c/models.py
class CApplication(BaseModel):
    """Represents a complete C application.

    Attributes:
        translation_units (Dict[str, CTranslationUnit]): All source files
        call_graph (List[CCallGraphEdge]): Function call relationships
    """

    translation_units: Dict[str, CTranslationUnit]
    call_graph: List[CCallGraphEdge] = []