
    :;iK                        d Z ddlZddlZ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 ddlmZmZ ddlmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZ erddlmZ ej@                  jC                  ej@                  jE                  e#      d      Z$dZ%d Z&d Z'd Z(d Z)d Z* G d d      Z+ G d de+      Z, G d de+      Z- G d d      Z. G d d      Z/ G d d      Z0y) a  
Makes it possible to do the compiled analysis in a subprocess. This has two
goals:

1. Making it safer - Segfaults and RuntimeErrors as well as stdout/stderr can
   be ignored and dealt with.
2. Make it possible to handle different Python versions as well as virtualenvs.

The architecture here is briefly:
 - For each Jedi `Environment` there is a corresponding subprocess which
   operates within the target environment. If the subprocess dies it is replaced
   at this level.
 - `CompiledSubprocess` manages exactly one subprocess and handles communication
   from the parent side.
 - `Listener` runs within the subprocess, processing each request and yielding
   results.
 - `InterpreterEnvironment` provides an API which matches that of `Environment`,
   but runs functionality inline rather than within a subprocess. It is thus
   used both directly in places where a subprocess is unnecessary and/or
   undesirable and also within subprocesses themselves.
 - `InferenceStateSubprocess` (or `InferenceStateSameProcess`) provide high
   level access to functionality within the subprocess from within the parent.
   Each `InterpreterState` has an instance of one of these, provided by its
   environment.
    N)partial)Thread)DictTYPE_CHECKING)pickle_dumppickle_load)debug)memoize_method)	functions)DirectObjectAccess
AccessPathSignatureParam)InternalErrorInferenceStatez__main__.py   c                      t         j                  dk(  r	 t        j                  }||d<   dt
        j                  v |d<   t        j                  | i |S # t        $ r d}Y <w xY w)Nnti   creationflagsposix	close_fds)osname
subprocessCREATE_NO_WINDOWAttributeErrorsysbuiltin_module_namesPopen)argskwargsr   s      h/home/rose/Desktop/poly/venv/lib/python3.12/site-packages/jedi/inference/compiled/subprocess/__init__.py_GeneralizedPopenr#   6   sn    	ww$	*):: #3 "S%=%==F;T,V,,  	*)	*s   A A"!A"c                 \    t        | j                  d      D ]  }|j                  |        y )N    )iterreadlineput)outqueue_lines      r"   _enqueue_outputr,   E   s#    S\\3'

4 (r%   c                     	 	 | j                         }|j                  dd      }t        j                  d|j	                  d      z         K# t
        j                  $ r Y y w xY w)Nutf-8replacezstderr output: %s
)
get_nowaitdecoder	   warningrstripqueueEmpty)stderr_queuer+   s     r"   _add_stderr_to_debugr8   J   s`    
	**,D;;w	2DMM-D0AAB  {{ 		s   A	A A#"A#c                 "    t        t        |       S N)getattrr   )r   s    r"   _get_functionr<   V   s    9d##r%   c                    	 | j                          | j                          |j                          | j                  | j
                  | j                  fD ]  }	 |j                           y # t        $ r Y Uw xY w# t        $ r Y 1w xY wr:   )killwaitOSErrorjoinstdinstdoutstderrclose)processthreadstreams      r"   _cleanup_processrI   Z   sw     KKM=='..'..A	LLN B	    		s#    A, A;,	A87A8;	BBc                   &    e Zd ZddZd Zd Zd Zy)_InferenceStateProcessNc                 F    t        j                  |      | _        i | _        y r:   )weakrefref_inference_state_weakref_handles)selfinference_states     r"   __init__z_InferenceStateProcess.__init__k   s    (/O(D%13r%   c                     t        |      }	 | j                  |      S # t        $ r= t        | j	                         |      }t        | ||      }| j                  |       |cY S w xY wr:   )idget_access_handleKeyErrorr   rO   AccessHandleset_access_handle)rQ   objid_accesshandles        r"   get_or_create_access_handlez2_InferenceStateProcess.get_or_create_access_handleo   sf    g	))#.. 	'(E(E(GMF!$4F""6*M		s    AA$#A$c                      | j                   |   S r:   )rP   )rQ   r[   s     r"   rV   z(_InferenceStateProcess.get_access_handley   s    }}S!!r%   c                 6    || j                   |j                  <   y r:   )rP   rU   )rQ   r]   s     r"   rY   z(_InferenceStateProcess.set_access_handle|   s    #)fii r%   )rR   r   returnN)__name__
__module____qualname__rS   r^   rV   rY    r%   r"   rK   rK   j   s    4"*r%   rK   c                       e Zd ZdZd Zy)InferenceStateSameProcessz
    Basically just an easy access to functions.py. It has the same API
    as InferenceStateSubprocess and does the same thing without using a subprocess.
    This is necessary for the Interpreter process.
    c                 H    t        t        |      | j                               S r:   )r   r<   rO   rQ   r   s     r"   __getattr__z%InferenceStateSameProcess.__getattr__   s    }T*D,I,I,KLLr%   N)rb   rc   rd   __doc__rj   re   r%   r"   rg   rg      s    
Mr%   rg   c                   B     e Zd ZdZ	 	 	 	 	 	 d fdZd Zd Zd Z xZS )InferenceStateSubprocessa  
    API to functionality which will run in a subprocess.

    This mediates the interaction between an `InferenceState` and the actual
    execution of functionality running within a `CompiledSubprocess`. Available
    functions are defined in `.functions`, though should be accessed via
    attributes on this class of the same name.

    This class is responsible for indicating that the `InferenceState` within
    the subprocess can be removed once the corresponding instance in the parent
    goes away.
    c                 `    t         |   |       d| _        || _        t	        |       | _        y )NF)superrS   _used_compiled_subprocessrU   _inference_state_id)rQ   rR   compiled_subprocess	__class__s      r"   rS   z!InferenceStateSubprocess.__init__   s/    
 	)
$7!* $&d8 r%   c                 ,     t        |       fd}|S )Nc                      d_         j                  j                  j                  | |      }j	                  |      S )NT)r    r!   )rp   rq   runrr   _convert_access_handles)r    r!   resultfuncrQ   s      r"   wrapperz5InferenceStateSubprocess.__getattr__.<locals>.wrapper   sJ    DJ..22((	 3 F //77r%   )r<   )rQ   r   r{   rz   s   `  @r"   rj   z$InferenceStateSubprocess.__getattr__   s    T"	8 r%   c                 @    t        |t              r t         j                  t        |             S t        |t              rt         fd|D              S t        |t              r|D cg c]  } j                  |       c}S t        |t
              r	  j                  |j                        }|S t        |t              r$t         j                  |j                              S |S c c}w # t        $ r& |j                           j                  |       Y |S w xY w)Nc              3   @   K   | ]  }j                  |        y wr:   )rx   ).0orQ   s     r"   	<genexpr>zCInferenceStateSubprocess._convert_access_handles.<locals>.<genexpr>   s     F#Q55a8#s   )
isinstancer   rx   tuplelistrX   rV   rU   rW   add_subprocessrY   r   accesses)rQ   rZ   r   s   `  r"   rx   z0InferenceStateSubprocess._convert_access_handles   s    c>*!4#?#?c
#KLLU#F#FFFT"=@ASD003SAA\*,,,SVV4 
 Z(d::3<<HII
 B
  ,""4(&&s+ 
,s   *C)C. .+DDc                     | j                   r=| j                  j                  s&| j                  j                  | j                         y y y r:   )rp   rq   
is_crasheddelete_inference_staterr   rQ   s    r"   __del__z InferenceStateSubprocess.__del__   s9    ::d77BB%%<<T=U=UV C:r%   )rR   r   rs   CompiledSubprocessra   N)	rb   rc   rd   rk   rS   rj   rx   r   __classcell__)rt   s   @r"   rm   rm      s9    ,), 2, 
	,<&$Wr%   rm   c                   \    e Zd ZdZdZddZd Zed        Zdi fdZ	d	 Z
d
 Zdi fdZd Zy)r   a  
    A subprocess which runs inference within a target environment.

    This class manages the interface to a single instance of such a process as
    well as the lifecycle of the process itself. See `.__main__` and `Listener`
    for the implementation of the subprocess and details of the protocol.

    A single live instance of this is maintained by `jedi.api.environment.Environment`,
    so that typically a single subprocess is used at a time.
    FNc                 b    || _         || _        t        j                         | _        d | _        y )Nc                       y r:   re   re   r%   r"   <lambda>z-CompiledSubprocess.__init__.<locals>.<lambda>   s    r%   )_executable	_env_varscollectionsdeque_inference_state_deletion_queue_cleanup_callable)rQ   
executableenv_varss      r"   rS   zCompiledSubprocess.__init__   s*    %!/:/@/@/B,!-r%   c           	          t        j                         }d| j                  j                  d| j                  d| j
                  d|d	S )N<z _executable=z, is_crashed=z, pid=>)r   getpidrt   rb   r   r   )rQ   pids     r"   __repr__zCompiledSubprocess.__repr__   s7    iikNN##OO	
 	
r%   c           	         t        j                  d| j                         t        j                  d   j
                  }| j                  t        t        j                  j                  t        j                  j                  |            dj                  d t        j                  d d D              f}t        |t        j                  t        j                  t        j                  | j                        }t!        j"                         | _        t'        t(        |j*                  | j$                  f      x| _        }d|_        |j1                          t3        j4                  | t6        ||      | _        |S )	NzStart environment subprocess %sparso.c              3   2   K   | ]  }t        |        y wr:   )str)r~   xs     r"   r   z2CompiledSubprocess._get_process.<locals>.<genexpr>  s     :%9SV%9s      )rB   rC   rD   env)targetr    T)r	   dbgr   r   modules__file__
_MAIN_PATHr   pathdirnamerA   version_infor#   r   PIPEr   r5   Queue_stderr_queuer   r,   rD   _stderr_threaddaemonstartrM   finalizerI   r   )rQ   
parso_pathr    rF   ts        r"   _get_processzCompiledSubprocess._get_process   s   		3T5E5EF[[)22
GGOOBGGOOJ78HH:S%5%5bq%9::	
 $//????
 #[[]"("..$"4"45#
 	
a 		 ")!1!1$2B2923"5 r%   re   c                     	 	 | j                   j                         }| j                  |d        .# t        $ r Y nw xY wt	        |      sJ | j                  ||||      S r:   )r   pop_send
IndexErrorcallable)rQ   inference_state_idfunctionr    r!   	delete_ids         r"   rw   zCompiledSubprocess.run  sm    , @@DDF	 

9d+   
 !!!zz,hfEEs   0 	<<c                 F    | j                  d t        j                  di       S )Nre   )r   r   get_sys_pathr   s    r"   r   zCompiledSubprocess.get_sys_path*  s    zz$	 6 6B??r%   c                 2    d| _         | j                          y )NT)r   r   r   s    r"   _killzCompiledSubprocess._kill-  s     r%   c           
         | j                   rt        d| j                  z        ||||f}	 t        || j	                         j
                  t               	 t        | j	                         j                        \  }}}t!        | j"                         |r
|f|_        ||S # t        $ r) | j                          t        d| j                  z        w xY w# t        $ r}		 | j	                         j                  j                         j                  dd      }
n# t        $ r}d|z  }
Y d }~nd }~ww xY w| j                          t!        | j"                         t        d| j                  d|	d|
d	      d }	~	ww xY w)
NzThe subprocess %s has crashed.z2The subprocess %s was killed. Maybe out of memory?r.   r/   z<empty/not available (%r)>zThe subprocess z has crashed (z	, stderr=z).)r   r   r   r   r   rB   PICKLE_PROTOCOLBrokenPipeErrorr   r   rC   EOFErrorrD   readr2   	Exceptionr8   r   r    )rQ   r   r   r    r!   datais_exception	tracebackry   	eof_errorrD   excs               r"   r   zCompiledSubprocess._send1  se   ?? @4CSCS STT!8T69	4d//177I	.9$:K:K:M:T:T.U+L)V 	T//0 %,FKL9  	4JJL T"&"2"2!3 4 4	4  	<**,3388:AA'9U <5;<JJL !3!34$$ 	sH   )B  'C  2C	E<8DE7	D0!D+&E7+D00AE77E<c                 :    | j                   j                  |       y)af  
        Indicate that an inference state (in the subprocess) is no longer
        needed.

        The state corresponding to the given id will become inaccessible and the
        id may safely be re-used to refer to a different context.

        Note: it is not guaranteed that the corresponding state will actually be
        deleted immediately.
        N)r   append)rQ   r   s     r"   r   z)CompiledSubprocess.delete_inference_stateV  s    & 	,,334FGr%   r:   )rb   rc   rd   rk   r   rS   r   r
   r   rw   r   r   r   r   re   r%   r"   r   r      sW    	 J.
  > 68 F@! 8:" #JHr%   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)ListeneraM  
    Main loop for the subprocess which actually does the inference.

    This class runs within the target environment. It listens to instructions
    from the parent process, runs inference and returns the results.

    The subprocess has a long lifetime and is expected to process several
    requests, including for different `InferenceState` instances in the parent.
    See `CompiledSubprocess` for the parent half of the system.

    Communication is via pickled data sent serially over stdin and stdout.
    Stderr is read only if the child process crashes.

    The request protocol is a 4-tuple of:
     * inference_state_id | None: an opaque identifier of the parent's
       `InferenceState`. An `InferenceState` operating over an
       `InterpreterEnvironment` is created within this process for each of
       these, ensuring that each parent context has a corresponding context
       here. This allows context to be persisted between requests. Unless
       `None`, the local `InferenceState` will be passed to the given function
       as the first positional argument.
     * function | None: the function to run. This is expected to be a member of
       `.functions`. `None` indicates that the corresponding inference state is
       no longer needed and should be dropped.
     * args: positional arguments to the `function`. If any of these are
       `AccessHandle` instances they will be adapted to the local
       `InferenceState` before being passed.
     * kwargs: keyword arguments to the `function`. If any of these are
       `AccessHandle` instances they will be adapted to the local
       `InferenceState` before being passed.

    The result protocol is a 3-tuple of either:
     * (False, None, function result): if the function returns without error, or
     * (True, traceback, exception): if the function raises an exception
    c                     i | _         y r:   )_inference_statesr   s    r"   rS   zListener.__init__  s
    !#r%   c                     ddl m} 	 | j                  |   }|S # t        $ r( ddlm}  |d  |             }|| j                  |<   Y |S w xY w)Nr   r   )InterpreterEnvironment)projectenvironment)jedi.inferencer   r   rW   jedir   )rQ   r   r   r   rR   r   s         r"   _get_inference_statezListener._get_inference_state  si    1
	I"445GHO   	I3, 24	O :ID""#56	Is    -A
	A
c                    | ||i |S || j                   |= y | j                  ||      }t        |      }t        |      D ]>  \  }}t	        |t
              s|j                  j                  |j                        ||<   @ |j                         D ]>  \  }}	t	        |	t
              s|j                  j                  |	j                        ||<   @  ||g|i |S r:   )
r   r   r   	enumerater   rX   rs   rV   rU   items)
rQ   r   r   r    r!   rR   iargkeyvalues
             r"   _runzListener._run  s    %T,V,, &&'9:"77BTUO :D#D/3c<0-AASSTWTZTZ[DG * %lln
Ue\2"1"E"E"W"WX]X`X`"aF3K - O=d=f==r%   c                    t         j                  }t        t        j                  d      t         _        t         j
                  }|j                  }|j                  }	 	 t        |      }	 dd  | j                   f}t        ||t               1# t        $ r t        d       Y ;w xY w# t        $ r!}dt        j                         |f}Y d }~Qd }~ww xY w)NwTr   F)r   rC   openr   devnullrB   bufferr   r   exitr   r   r   
format_excr   r   )rQ   rC   rB   payloadry   es         r"   listenzListener.listen  s     "**c*
		%e,
9idii&99 8    Q  9y335q89s*   B *B( B%$B%(	C1CCN)rb   rc   rd   rk   rS   r   r   r   re   r%   r"   r   r   l  s    "H$ >,9r%   r   c                   X    e Zd ZdedededdfdZd Zd Zd	 Z	d
 Z
d Zd Zed        Zy)rX   r   r\   r[   ra   Nc                 .    || _         || _        || _        y r:   )r\   _subprocessrU   )rQ   r   r\   r[   s       r"   rS   zAccessHandle.__init__  s     %r%   c                     || _         y r:   )r   )rQ   r   s     r"   r   zAccessHandle.add_subprocess  s
    %r%   c                     	 | j                   }d| j                  j
                  d|dS # t        $ r dt        | j                        z   }Y @w xY w)N#r   z of r   )r\   r   r   rU   rt   rb   )rQ   details     r"   r   zAccessHandle.__repr__  sK    	([[F  $~~66??  	(3tww<'F	(s   + !AAc                     | j                   S r:   rU   r   s    r"   __getstate__zAccessHandle.__getstate__  s    wwr%   c                     || _         y r:   r   )rQ   states     r"   __setstate__zAccessHandle.__setstate__  s	    r%   c                 n    |dv s|j                  d      rt        d      t        | j                  |      S )N)rU   r\   _z$Something went wrong with unpickling)
startswithr   r   _workaroundri   s     r"   rj   zAccessHandle.__getattr__  s7    ##ts'; !GHH t''..r%   c                     |r>t        |d   t              r+ | j                  j                  | j                  |g|i |S  | j
                  |g|i |S )z
        TODO Currently we're passing slice objects around. This should not
        happen. They are also the only unhashable objects that we're passing
        around.
        r   )r   slicer   get_compiled_method_returnrU   _cached_resultsrQ   r   r    r!   s       r"   r   zAccessHandle._workaround  s[     JtAw.>4##>>tww^t^W]^^#t##D:4:6::r%   c                 X     | j                   j                  | j                  |g|i |S r:   )r   r  rU   r  s       r"   r  zAccessHandle._cached_results  s,    :t::477DZ4ZSYZZr%   )rb   rc   rd   rK   r   intrS   r   r   r   r   rj   r   r
   r  re   r%   r"   rX   rX     sb    * # 	
 
&@/; [ [r%   rX   )1rk   r   r   r   r5   r   r   rM   	functoolsr   	threadingr   typingr   r   jedi._compatibilityr   r   r   r	   
jedi.cacher
   "jedi.inference.compiled.subprocessr   jedi.inference.compiled.accessr   r   r   jedi.api.exceptionsr   r   r   r   rA   r   r   r   r   r#   r,   r8   r<   rI   rK   rg   rm   r   r   rX   re   r%   r"   <module>r     s   4  	 
       & 8  % 8  -- WW\\"''//(3]C
-
	$ * *,M 6 MSW5 SWlIH IHXc9 c9L.[ .[r%   