# This file was generated by stubgen-pyx v0.2.6 from cuda_core/cuda/core/_program.pyx

"""Compilation machinery for CUDA programs.

This module provides :class:`Program` for compiling source code into
:class:`~cuda.core.ObjectCode`, with :class:`ProgramOptions` for configuration.
"""
from __future__ import annotations

from dataclasses import dataclass

from cuda.bindings import nvrtc
from cuda.core._linker import LinkerHandleT
from cuda.core._module import ObjectCode
from cuda.core.typing import (CompilerBackendType, ObjectCodeFormatType,
                              PCHStatusType, SourceCodeType)
from cuda.core.utils._program_cache import ProgramCacheResource


class Program:
    """Represent a compilation machinery to process programs into
    :class:`~cuda.core.ObjectCode`.

    This object provides a unified interface to multiple underlying
    compiler libraries. Compilation support is enabled for a wide
    range of code types and compilation types.

    Parameters
    ----------
    code : str | bytes | bytearray
        The source code to compile. For C++ and PTX, must be a string.
        For NVVM IR, can be str, bytes, or bytearray.
    code_type : SourceCodeType | str
        The type of source code. Must be one of ``"c++"``, ``"ptx"``, or ``"nvvm"``.
    options : :class:`ProgramOptions`, optional
        Options to customize the compilation process.
    """

    def __init__(self, code: str | bytes | bytearray, code_type: SourceCodeType | str, options: ProgramOptions | None=None):
        ...

    def close(self) -> None:
        """Destroy this program."""

    def compile(self, target_type: ObjectCodeFormatType | str, name_expressions: tuple[str, ...] | list[str]=..., logs: object=None, *, cache: ProgramCacheResource | None=None) -> ObjectCode:
        """Compile the program to the specified target type.

        Parameters
        ----------
        target_type : ObjectCodeFormatType | str
            The compilation target. Must be one of ``"ptx"``, ``"cubin"``, or ``"ltoir"``.
        name_expressions : tuple | list, optional
            Sequence of name expressions to make accessible in the compiled code.
            Used for template instantiation and similar cases.
        logs : object, optional
            Object with a ``write`` method to receive compilation logs.
            On a cache hit no compilation runs and ``logs`` receives
            nothing -- callers that rely on log output to confirm a
            compile happened should compile without ``cache=``.
        cache : :class:`~cuda.core.utils.ProgramCacheResource`, optional
            If provided, the compiled binary is looked up in ``cache`` via a
            key derived from the program's code, options, and ``target_type``.
            On a hit the cached bytes are wrapped in a fresh
            :class:`~cuda.core.ObjectCode` (with the same ``target_type``
            and ``ProgramOptions.name``) and returned without re-compiling;
            on a miss the compile output is stored as raw bytes (the cache
            extracts ``bytes(object_code.code)``). Passing a non-empty
            ``name_expressions`` together with ``cache=`` raises
            ``ValueError``: NVRTC populates
            ``ObjectCode.symbol_mapping`` at compile time and that mapping
            is not carried in the binary the cache stores, so cache hits
            would silently miss ``get_kernel(name_expression)`` lookups.
            Options that require an ``extra_digest`` (``include_path``,
            ``pre_include``, ``pch``, ``use_pch``, ``pch_dir``, NVVM
            ``use_libdevice=True``, or NVRTC ``options.name`` with a
            directory component) raise ``ValueError`` via
            :func:`~cuda.core.utils.make_program_cache_key`; for those
            compiles, use the manual ``make_program_cache_key(...)``
            pattern directly.

            ``cache=`` is independent of ``ProgramOptions.no_cache``: the
            former controls this program-level cache (compiled-output
            reuse across calls), while ``no_cache`` is forwarded to the
            Linker to disable its in-process JIT cache for cuLink/nvJitLink.
            Setting ``options.no_cache=True`` does not bypass ``cache=``,
            and vice-versa.

        Returns
        -------
        :class:`~cuda.core.ObjectCode`
            The compiled object code.
        """

    @property
    def pch_status(self) -> PCHStatusType | None:
        """PCH creation outcome from the most recent :meth:`compile` call.

        Possible values:

        * ``"created"`` — PCH file was written successfully.
        * ``"not_attempted"`` — PCH creation was not attempted (e.g. the
          compiler decided not to, or automatic PCH processing skipped it).
        * ``"failed"`` — an error prevented PCH creation.
        * ``None`` — PCH was not requested, the program has not been
          compiled yet, the backend is not NVRTC (e.g. PTX or NVVM),
          or the NVRTC bindings are too old to report status.

        When ``create_pch`` is set in :class:`ProgramOptions` and the PCH
        heap is too small, :meth:`compile` automatically resizes the heap
        and retries, so ``"created"`` should be the common outcome.

        .. note::

           PCH is only supported for ``code_type="c++"`` programs that
           use the NVRTC backend. For PTX and NVVM programs this property
           always returns ``None``.
        """

    @property
    def backend(self) -> CompilerBackendType:
        """Return this Program instance's underlying :class:`CompilerBackendType`."""

    @property
    def handle(self) -> ProgramHandleT:
        """Return the underlying handle object.

        .. note::

           The type of the returned object depends on the backend.

        .. caution::

            This handle is a Python object. To get the memory address of the underlying C
            handle, call ``int(Program.handle)``.
        """

    def __repr__(self) -> str:
        ...

@dataclass
class ProgramOptions:
    """Customizable options for configuring :class:`Program`.

    Attributes
    ----------
    name : str, optional
        Name of the program. If the compilation succeeds, the name is passed down to the generated :class:`ObjectCode`.
        When set to `None`, ``"default_program"`` is used.
    arch : str, optional
        Pass the SM architecture value, such as ``sm_<CC>`` (for generating CUBIN) or
        ``compute_<CC>`` (for generating PTX). If not provided, the current device's architecture
        will be used.
    relocatable_device_code : bool, optional
        Enable (disable) the generation of relocatable device code.
        Default: False
    extensible_whole_program : bool, optional
        Do extensible whole program compilation of device code.
        Default: False
    debug : bool, optional
        Generate debug information. If --dopt is not specified, then turns off all optimizations.
        Default: False
    lineinfo: bool, optional
        Generate line-number information.
        Default: False
    device_code_optimize : bool, optional
        Enable device code optimization. When specified along with '-G', enables limited debug information generation
        for optimized device code.
        Default: None
    ptxas_options : Union[str, list[str]], optional
        Specify one or more options directly to ptxas, the PTX optimizing assembler. Options should be strings.
        For example ["-v", "-O2"].
        Default: None
    max_register_count : int, optional
        Specify the maximum amount of registers that GPU functions can use.
        Default: None
    ftz : bool, optional
        When performing single-precision floating-point operations, flush denormal values to zero or preserve denormal
        values.
        Default: False
    prec_sqrt : bool, optional
        For single-precision floating-point square root, use IEEE round-to-nearest mode or use a faster approximation.
        Default: True
    prec_div : bool, optional
        For single-precision floating-point division and reciprocals, use IEEE round-to-nearest mode or use a faster
        approximation.
        Default: True
    fma : bool, optional
        Enables (disables) the contraction of floating-point multiplies and adds/subtracts into floating-point
        multiply-add operations.
        Default: True
    use_fast_math : bool, optional
        Make use of fast math operations.
        Default: False
    extra_device_vectorization : bool, optional
        Enables more aggressive device code vectorization in the NVVM optimizer.
        Default: False
    link_time_optimization : bool, optional
        Generate intermediate code for later link-time optimization.
        Default: False
    gen_opt_lto : bool, optional
        Run the optimizer passes before generating the LTO IR.
        Default: False
    define_macro : Union[str, tuple[str, str], list[Union[str, tuple[str, str]]]], optional
        Predefine a macro. Can be either a string, in which case that macro will be set to 1, a 2 element tuple of
        strings, in which case the first element is defined as the second, or a list of strings or tuples.
        Default: None
    undefine_macro : Union[str, list[str]], optional
        Cancel any previous definition of a macro, or list of macros.
        Default: None
    include_path : Union[str, list[str]], optional
        Add the directory or directories to the list of directories to be searched for headers.
        Default: None
    pre_include : Union[str, list[str]], optional
        Preinclude one or more headers during preprocessing. Can be either a string or a list of strings.
        Default: None
    no_source_include : bool, optional
        Disable the default behavior of adding the directory of each input source to the include path.
        Default: False
    std : str, optional
        Set language dialect to C++03, C++11, C++14, C++17 or C++20.
        Default: c++17
    builtin_move_forward : bool, optional
        Provide builtin definitions of std::move and std::forward.
        Default: True
    builtin_initializer_list : bool, optional
        Provide builtin definitions of std::initializer_list class and member functions.
        Default: True
    disable_warnings : bool, optional
        Inhibit all warning messages.
        Default: False
    restrict : bool, optional
        Programmer assertion that all kernel pointer parameters are restrict pointers.
        Default: False
    device_as_default_execution_space : bool, optional
        Treat entities with no execution space annotation as __device__ entities.
        Default: False
    device_int128 : bool, optional
        Allow the __int128 type in device code.
        Default: False
    optimization_info : str, optional
        Provide optimization reports for the specified kind of optimization.
        Default: None
    no_display_error_number : bool, optional
        Disable the display of a diagnostic number for warning messages.
        Default: False
    diag_error : Union[int, list[int]], optional
        Emit error for a specified diagnostic message number or comma-separated list of numbers.
        Default: None
    diag_suppress : Union[int, list[int]], optional
        Suppress a specified diagnostic message number or comma-separated list of numbers.
        Default: None
    diag_warn : Union[int, list[int]], optional
        Emit warning for a specified diagnostic message number or comma-separated list of numbers.
        Default: None
    brief_diagnostics : bool, optional
        Disable or enable showing source line and column info in a diagnostic.
        Default: False
    time : str, optional
        Generate a CSV table with the time taken by each compilation phase.
        Default: None
    split_compile : int, optional
        Perform compiler optimizations in parallel.
        Default: 1
    fdevice_syntax_only : bool, optional
        Ends device compilation after front-end syntax checking.
        Default: False
    minimal : bool, optional
        Omit certain language features to reduce compile time for small programs.
        Default: False
    no_cache : bool, optional
        Disable compiler caching.
        Default: False
    fdevice_time_trace : str, optional
        Generate time trace JSON for profiling compilation (NVRTC only).
        Default: None
    device_float128 : bool, optional
        Allow __float128 type in device code (NVRTC only).
        Default: False
    frandom_seed : str, optional
        Set random seed for randomized optimizations (NVRTC only).
        Default: None
    ofast_compile : str, optional
        Fast compilation mode: "0", "min", "mid", or "max" (NVRTC only).
        Default: None
    pch : bool, optional
        Use default precompiled header (NVRTC only, CUDA 12.8+).
        Default: False
    create_pch : str, optional
        Create precompiled header file (NVRTC only, CUDA 12.8+).
        Default: None
    use_pch : str, optional
        Use specific precompiled header file (NVRTC only, CUDA 12.8+).
        Default: None
    pch_dir : str, optional
        PCH directory location (NVRTC only, CUDA 12.8+).
        Default: None
    pch_verbose : bool, optional
        Verbose PCH output (NVRTC only, CUDA 12.8+).
        Default: False
    pch_messages : bool, optional
        Control PCH diagnostic messages (NVRTC only, CUDA 12.8+).
        Default: False
    instantiate_templates_in_pch : bool, optional
        Control template instantiation in PCH (NVRTC only, CUDA 12.8+).
        Default: False
    extra_sources : list of 2-tuples or tuple of 2-tuples, optional
        Additional NVVM IR modules to compile together with the main program, specified as
        ``((name1, source1), (name2, source2), ...)``. Each name is a string identifier used
        in diagnostic messages. Each source can be a string (textual LLVM IR) or bytes/bytearray
        (LLVM bitcode). Only supported for the NVVM backend.
        Default: None
    use_libdevice : bool, optional
        Load NVIDIA's `libdevice <https://docs.nvidia.com/cuda/libdevice-users-guide/>`_
        math builtins library. Only supported for the NVVM backend.
        Default: False
    """
    name: str | None = 'default_program'
    arch: str | None = None
    relocatable_device_code: bool | None = None
    extensible_whole_program: bool | None = None
    debug: bool | None = None
    lineinfo: bool | None = None
    device_code_optimize: bool | None = None
    ptxas_options: str | list[str] | tuple[str] | None = None
    max_register_count: int | None = None
    ftz: bool | None = None
    prec_sqrt: bool | None = None
    prec_div: bool | None = None
    fma: bool | None = None
    use_fast_math: bool | None = None
    extra_device_vectorization: bool | None = None
    link_time_optimization: bool | None = None
    gen_opt_lto: bool | None = None
    define_macro: str | tuple[str, str] | list[str | tuple[str, str]] | tuple[str | tuple[str, str], ...] | None = None
    undefine_macro: str | list[str] | tuple[str] | None = None
    include_path: str | list[str] | tuple[str] | None = None
    pre_include: str | list[str] | tuple[str] | None = None
    no_source_include: bool | None = None
    std: str | None = None
    builtin_move_forward: bool | None = None
    builtin_initializer_list: bool | None = None
    disable_warnings: bool | None = None
    restrict: bool | None = None
    device_as_default_execution_space: bool | None = None
    device_int128: bool | None = None
    optimization_info: str | None = None
    no_display_error_number: bool | None = None
    diag_error: int | list[int] | tuple[int] | None = None
    diag_suppress: int | list[int] | tuple[int] | None = None
    diag_warn: int | list[int] | tuple[int] | None = None
    brief_diagnostics: bool | None = None
    time: str | None = None
    split_compile: int | None = None
    fdevice_syntax_only: bool | None = None
    minimal: bool | None = None
    no_cache: bool | None = None
    fdevice_time_trace: str | None = None
    device_float128: bool | None = None
    frandom_seed: str | None = None
    ofast_compile: str | None = None
    pch: bool | None = None
    create_pch: str | None = None
    use_pch: str | None = None
    pch_dir: str | None = None
    pch_verbose: bool | None = None
    pch_messages: bool | None = None
    instantiate_templates_in_pch: bool | None = None
    extra_sources: list[tuple[str, str | bytes | bytearray]] | tuple[tuple[str, str | bytes | bytearray], ...] | None = None
    use_libdevice: bool | None = None
    numba_debug: bool | None = None

    def __post_init__(self) -> None:
        ...

    def _prepare_nvrtc_options(self) -> list[bytes]:
        ...

    def _prepare_nvvm_options(self, as_bytes: bool=True) -> list[bytes] | list[str]:
        ...

    def as_bytes(self, backend: CompilerBackendType | str, target_type: ObjectCodeFormatType | str | None=None) -> list[bytes]:
        """Convert program options to bytes format for the specified backend.

        This method transforms the program options into a format suitable for the
        specified compiler backend. Different backends may use different option names
        and formats even for the same conceptual options.

        Parameters
        ----------
        backend : CompilerBackendType | str
            The compiler backend to prepare options for. Must be either "nvrtc" or "nvvm".
        target_type : ObjectCodeFormatType | str, optional
            The compilation target type (e.g., "ptx", "cubin", "ltoir"). Some backends
            require additional options based on the target type.

        Returns
        -------
        list[bytes]
            List of option strings encoded as bytes.

        Raises
        ------
        ValueError
            If an unknown backend is specified.
        CUDAError
            If an option incompatible with the specified backend is set.

        Examples
        --------
        >>> options = ProgramOptions(arch="sm_80", debug=True)
        >>> nvrtc_options = options.as_bytes("nvrtc")
        """

    def __repr__(self) -> str:
        ...

    def _prepare_extra_sources_bytes(self) -> list[tuple[bytes, bytes]] | None:
        """Convert extra_sources to bytes format for NVVM."""
__all__ = ['Program', 'ProgramOptions']
ProgramHandleT = nvrtc.nvrtcProgram | int | LinkerHandleT
_nvvm_module = None
_nvvm_import_attempted = False

def _can_load_generated_ptx() -> bool:
    """Check if the driver can load PTX generated by the current NVRTC version."""

def _program_compile_uncached(program, target_type, name_expressions, logs):
    """Run ``Program_compile`` without the cache wrapper.

    Module-level Python function so tests can monkeypatch it from
    ``cuda.core._program`` to avoid invoking NVRTC when exercising the cache
    wrapper in :meth:`Program.compile`. ``Program`` itself is a ``cdef class``
    and its methods cannot be reassigned from Python, so the seam must live
    outside the class.
    """

def _get_nvvm_module() -> object:
    """Get the NVVM module, importing it lazily with availability checks."""

def _find_libdevice_path() -> object:
    """Find libdevice*.bc for NVVM compilation using cuda.pathfinder."""