o
    (c7                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZm	Z	 d dl
mZ d dlmZmZmZmZmZmZmZmZ d dlmZ d dlmZ dd	lmZ G d
d deZG dd deZG dd dZG dd deZedeeef Z dedefddZ!dZ"dS )    N)DistutilsSetupError)IntEnumauto)	lru_cache)AnyDictListNewTypeOptionalSequenceUnioncast)
SimpleSpec)Literal   )format_called_process_errorc                   @   s6   e Zd ZdZe Ze Ze Ze Zde	fddZ
dS )Bindinga  
    Enumeration of possible Rust binding types supported by ``setuptools-rust``.

    Attributes:
        PyO3: This is an extension built using
            `PyO3 <https://github.com/pyo3/pyo3>`_.
        RustCPython: This is an extension built using
            `rust-cpython <https://github.com/dgrunwald/rust_cpython>`_.
        NoBinding: Bring your own bindings for the extension.
        Exec: Build an executable instead of an extension.
    returnc                 C      | j j d| j S N.	__class____name__nameself r   =usr/lib/python3.10/site-packages/setuptools_rust/extension.py__repr__#      zBinding.__repr__N)r   
__module____qualname____doc__r   PyO3ZRustCPythonZ	NoBindingExecstrr   r   r   r   r   r      s    r   c                   @   s0   e Zd ZdZe Ze Ze ZdefddZ	dS )Stripz
    Enumeration of modes for stripping symbols from the built extension.

    Attributes:
        No: Do not strip symbols.
        Debug: Strip debug symbols.
        All: Strip all symbols.
    r   c                 C   r   r   r   r   r   r   r   r   5   r    zStrip.__repr__N)
r   r!   r"   r#   r   NoZDebugZAllr&   r   r   r   r   r   r'   '   s    	r'   c                    @   sN  e Zd ZdZddddddddejejddddfdee	e
e	e	f f de	d	eee	  d
eee	  deee	  deee	  dee	 dedee dedededededed fddZdede	fddZdee fddZdee	 fddZdee	 fd d!Zd"e	d#e	ddfd$d%Zdedd&fd'd(Ze d)e	dedd&fd*d+Zdefd,d-ZdS ).RustExtensionab  Used to define a rust extension module and its build configuration.

    Args:
        target: The full Python dotted name of the extension, including any
            packages, i.e *not* a filename or pathname. It is possible to
            specify multiple binaries, if extension uses ``Binding.Exec``
            binding mode. In that case first argument has to be dictionary.
            Keys of the dictionary correspond to the rust binary names and
            values are the full dotted name to place the executable inside
            the python package. To install executables with kebab-case names,
            the final part of the dotted name can be in kebab-case. For
            example, `hello_world.hello-world` will install an executable
            named `hello-world`.
        path: Path to the ``Cargo.toml`` manifest file.
        args: A list of extra arguments to be passed to Cargo. For example,
            ``args=["--no-default-features"]`` will disable the default
            features listed in ``Cargo.toml``.
        cargo_manifest_args: A list of extra arguments to be passed to Cargo.
            These arguments will be passed to every ``cargo`` command, not just
            ``cargo build``. For valid options, see
            `the Cargo Book <https://doc.rust-lang.org/cargo/commands/cargo-build.html#manifest-options>`_.
            For example, ``cargo_manifest_args=["--locked"]`` will require
            ``Cargo.lock`` files are up to date.
        features: Cargo `--features` to add to the build.
        rustc_flags: A list of additional flags passed to `cargo rustc`. These
            only affect the final artifact, usually you should set the
            `RUSTFLAGS` environment variable.
        rust_version: Minimum Rust compiler version required for this
            extension.
        quiet: Suppress Cargo's output.
        debug: Controls whether ``--debug`` or ``--release`` is passed to
            Cargo. If set to `None` (the default) then build type is
            automatic: ``inplace`` build will be a debug build, ``install``
            and ``wheel`` builds will be release.
        binding: Informs ``setuptools_rust`` which Python binding is in use.
        strip: Strip symbols from final file. Does nothing for debug build.
        native: Build extension or executable with ``-Ctarget-cpu=native``
            (deprecated, set environment variable RUSTFLAGS=-Ctarget-cpu=native).
        script: Generate console script for executable if ``Binding.Exec`` is
            used (deprecated, just use ``RustBin`` instead).
        optional: If it is true, a build failure in the extension will not
            abort the build process, and instead simply not install the failing
            extension.
        py_limited_api: Similar to ``py_limited_api`` on
            ``setuptools.Extension``, this controls whether the built extension
            should be considered compatible with the PEP 384 "limited API".

            - ``'auto'``: the ``--py-limited-api`` option of
              ``setup.py bdist_wheel`` will control whether the extension is
              built as a limited api extension. The corresponding
              ``pyo3/abi3-pyXY`` feature will be set accordingly.
              This is the recommended setting, as it allows
              ``python setup.py install`` to build a version-specific extension
              for best performance.

            - ``True``: the extension is assumed to be compatible with the
              limited abi. You must ensure this is the case (e.g. by setting
              the ``pyo3/abi3`` feature).

            - ``False``: the extension is version-specific.
    
Cargo.tomlr   NFr   targetpathargscargo_manifest_argsfeaturesrustc_flagsrust_versionquietdebugbindingstripscriptnativeoptionalpy_limited_api)r   TFc                 C   s   t |trddd | D }n|}d|i}|| _|| _tj|| _t	|p)d| _
t	|p0d| _t	|p7d| _t	|p>d| _|| _|| _|	| _|
| _|| _|| _|| _|| _|rjtdt g | jdR | _|
tjkry|r{tdt d S d S d S )	Nz; c                 s   s     | ]\}}d ||f V  qdS )z%s=%sNr   ).0keyvalr   r   r   	<genexpr>   s    z)RustExtension.__init__.<locals>.<genexpr> r   zB`native` is deprecated, set RUSTFLAGS=-Ctarget-cpu=native instead.z-Ctarget-cpu=nativezG`Binding.Exec` with `script=True` is deprecated, use `RustBin` instead.)
isinstancedictjoinitemsr   r+   osr,   relpathtupler-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r8   r9   warningswarnDeprecationWarningr   r%   )r   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r   r   r   r   __init__x   s>   
zRustExtension.__init__r   c                   s\   | j |d}|d d   fdd|d D \}|d d d	 }t|ts'J td
d|S )z7Parse Cargo.toml to get the name of the shared library.)r2   resolverootc                    s   g | ]
}|d   kr|qS )idr   r:   pZroot_keyr   r   
<listcomp>   s    z.RustExtension.get_lib_name.<locals>.<listcomp>packagestargetsr   r   z[./\\-]_)metadatar?   r&   resub)r   r2   rT   pkgr   r   rO   r   get_lib_name   s   zRustExtension.get_lib_namec                 C   s6   | j d u rd S zt| j W S  ty   td| j w )Nz'Can not parse rust compiler version: %s)r1   r   
ValueErrorr   r   r   r   r   get_rust_version   s   
zRustExtension.get_rust_versionc                 C   s   z| j d}| j |d  W S  ty   Y n ty#   td| j w dd | j D }|rB|d ddd }|s@td| j |S d S )Nz	--profiler   z#Can not parse cargo profile from %sc                 S   s   g | ]	}| d r|qS )z
--profile=)
startswithrM   r   r   r   rP      s    z3RustExtension.get_cargo_profile.<locals>.<listcomp>r   =)r-   indexrY   
IndexErrorr   split)r   r]   Zprofile_argsZprofiler   r   r   get_cargo_profile   s"   zRustExtension.get_cargo_profilec                 C   sX   g }| j r*| jtjkr*| j D ]\}}|d\}}d||t|f }|| q|S )Nr   z%s=%s.%s:run)	r6   r4   r   r%   r+   rB   rsplit_script_nameappend)r   entry_points
executablemodZbase_modr   r6   r   r   r   rd      s   zRustExtension.entry_pointsmodule_nameexe_pathc                 C   s   | j rB| jtjkrDtj|\}}t|}tj|| d}t	|d}|
tjt|d W d    d S 1 s;w   Y  d S d S d S )Nz.pyw)re   )r6   r4   r   r%   rC   r,   r_   rb   rA   openwrite_SCRIPT_TEMPLATEformatrepr)r   rg   rh   dirnamere   script_namefilefr   r   r   install_script   s   "zRustExtension.install_scriptCargoMetadatac                C   s   |  tjdd|S )zzReturns cargo metadata for this extension package.

        Cached - will only execute cargo on first invocation.
        ZCARGOcargo)	_metadatarC   environget)r   r2   r   r   r   rT      s   zRustExtension.metadataru   c              
   C   s   |dd| j ddg}| jr|| j z|rtjnd }tj||dd}W n tjy6 } ztt|d }~ww z	t	t
t|W S  tjjyW } z	td| d|d }~ww )	NrT   z--manifest-pathz--format-version1zlatin-1)stderrencodingz[
                Error parsing output of cargo metadata as json; received:
                z
                )r,   r.   extend
subprocessPIPEcheck_outputCalledProcessErrorr   r   r   rt   jsonloadsdecoderJSONDecodeError)r   ru   r2   Zmetadata_commandrz   payloader   r   r   rv      s<   
zRustExtension._metadatac                 C   s   | j tjkS N)r4   r   r%   r   r   r   r   _uses_exec_binding  s   z RustExtension._uses_exec_binding)r   r!   r"   r#   r   r$   r'   r(   r   r&   r   r
   r   boolr   rI   rX   r   rZ   r`   r   rd   rs   rT   r   rv   r   r   r   r   r   r)   9   sp    A



	

7	

r)   c                       s   e Zd ZdZdddddddejdf	deeeeef f dede	e
e  d	e	e
e  d
e	e
e  de	e dede	e dedef fddZdee fddZ  ZS )RustBina  Used to define a Rust binary and its build configuration.

    Args:
        target: Rust binary target name.
        path: Path to the ``Cargo.toml`` manifest file.
        args: A list of extra arguments to be passed to Cargo. For example,
            ``args=["--no-default-features"]`` will disable the default
            features listed in ``Cargo.toml``.
        cargo_manifest_args: A list of extra arguments to be passed to Cargo.
            These arguments will be passed to every ``cargo`` command, not just
            ``cargo build``. For valid options, see
            `the Cargo Book <https://doc.rust-lang.org/cargo/commands/cargo-build.html#manifest-options>`_.
            For example, ``cargo_manifest_args=["--locked"]`` will require
            ``Cargo.lock`` files are up to date.
        features: Cargo `--features` to add to the build.
        rust_version: Minimum Rust compiler version required for this bin.
        quiet: Suppress Cargo's output.
        debug: Controls whether ``--debug`` or ``--release`` is passed to
            Cargo. If set to `None` (the default) then build type is
            automatic: ``inplace`` build will be a debug build, ``install``
            and ``wheel`` builds will be release.
        strip: Strip symbols from final file. Does nothing for debug build.
        optional: If it is true, a build failure in the bin will not
            abort the build process, and instead simply not install the failing
            bin.
    r*   r   NFr+   r,   r-   r.   r/   r1   r2   r3   r5   r8   c                    s*   t  j||||||||tj|
|	dd d S )NF)r+   r,   r-   r.   r/   r1   r2   r3   r4   r8   r5   r9   )superrI   r   r%   )r   r+   r,   r-   r.   r/   r1   r2   r3   r5   r8   r   r   r   rI   1  s   
zRustBin.__init__r   c                 C   s   g S r   r   r   r   r   r   rd   M  s   zRustBin.entry_points)r   r!   r"   r#   r'   r(   r   r&   r   r
   r   r   rI   r   rd   __classcell__r   r   r   r   r     sB    


	
r   rt   re   r   c                 C   s   |  dd}d| S )aa  Generates the name of the installed Python script for an executable.

    Because Python modules must be snake_case, this generated script name will
    replace `-` with `_`.

    >>> _script_name("hello-world")
    '_gen_hello_world'

    >>> _script_name("foo_bar")
    '_gen_foo_bar'

    >>> _script_name("_gen_foo_bar")
    '_gen__gen_foo_bar'
    -rS   Z_gen_)replace)re   r6   r   r   r   rb   T  s   
rb   z
import os
import sys

def run():
    path = os.path.split(__file__)[0]
    file = os.path.join(path, {executable})
    if os.path.isfile(file):
        os.execv(file, sys.argv)
    else:
        raise RuntimeError("can't find " + file)
)#r   rC   rU   r}   rF   distutils.errorsr   enumr   r   	functoolsr   typingr   r   r   r	   r
   r   r   r   Zsemantic_versionr   typing_extensionsr   Z_utilsr   r   r'   r)   r   r&   rt   rb   rl   r   r   r   r   <module>   s(    ( ]<