U
    ҥcD_                     @   s  U 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Z	ddl
mZ ddlmZ ddlZddlmZ ddlmZ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" d	dl#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/ zddl0m1Z1 W n e2k
rD   dZ1Y nX z ddl3m4Z5 ddl3m6Z7 dZ8W n e2k
r   dZ8Y nX dZ9dd Z:e; Z<da=e	j>e" e?d< dd Z@e:e_Ae@e_BG dd de,ZCG dd  d eCZ+dS )!z!The IPython kernel implementation    N)contextmanager)partial)release)line_at_cursortoken_at_cursor)AnyBool	HasTraitsInstanceListTypeobserveobserve_compat)	ZMQStream   BaseComm)CommManager)XCachingCompiler)Debugger_is_debugpy_available)_use_appnope)Kernel)_accepts_cell_id)ZMQInteractiveShell)_asyncio_runner)provisionalcompleter)rectify_completionsTFZ_jupyter_types_experimentalc                  O   s
   t | |S )zCreate a new Comm.r   argskwargs r!   1lib/python3.8/site-packages/ipykernel/ipkernel.py_create_comm.   s    r#   _comm_managerc               	   O   s.   t dkr*t t dkr t| |a W 5 Q R X t S )zCreate a new CommManager.N)r$   
_comm_lockr   r   r!   r!   r"   _get_comm_manager8   s
    r&   c                
       s  e Zd ZdZedddZeeZe	dddj
ddZerDeeddndZe Zed	ed
d ZeedddZededd Ze Ze Z fddZeddejdd  ddddddddddddddddd d!dgj
ddZd"Zej Z!d#ej " d$ d%d"ejd$ d&d'd( d#d)d*Z#d+d, Z$e%d-d. Z&d/d0 Z' fd1d2Z(dZ fd4d5	Z) fd6d7Z*d8d9 Z+d[d;d<Z,d=d> Z-e%d?d@ Z.e.j/dAd@ Z.e0dBdC Z1d\ddDdEdFZ2dGdH Z3dIdJ Z4dKdL Z5d]dNdOZ6d^dPdQZ7dRdS Z8dTdU Z9dVdW Z:dXdY Z;  Z<S )_IPythonKernelzThe IPython Kernel class.z1IPython.core.interactiveshell.InteractiveShellABCT)
allow_nonezUSet this flag to False to deactivate the use of experimental IPython completion APIs.)help)ZconfigNuser_modulec                 C   s   | j d k	r|d | j _d S Nnew)shellr*   selfZchanger!   r!   r"   _user_module_changedU   s    
z"IPythonKernel._user_module_changed)r   r(   user_nsc                 C   s$   | j d k	r |d | j _| j   d S r+   )r-   r1   Zinit_user_nsr.   r!   r!   r"   _user_ns_changed]   s    
zIPythonKernel._user_ns_changedc                    s"  t  jf | tr2t| j| j| j| j| j| j	| _
| jj| | j| j| j| td| _| j| jj_tjd}|rz|| jjd< | j| jj_| d| jj_| j| jj_| j| jj_t | _t| jtst | jj!"| j dddg}|D ]}t#| j|| j$|< qt% r| j&rdd	l'}|(  d	S )
zInitialize the kernel.)parentprofile_dirr*   r1   ZkernelZcompiler_classZJPY_SESSION_NAMEZ__session__Zexecute_resultZ	comm_openZcomm_msgZ
comm_closer   N))super__init__r   r   logdebugpy_streamZ_publish_debug_eventZdebug_shell_socketsessionZdebug_just_my_codedebuggershell_classinstancer4   r*   r1   r   r-   displayhookosenvirongetiopub_socketZ
pub_socket_topicZtopicZdisplay_pubcommget_comm_managerZcomm_manager
isinstancer	   AssertionErrorZconfigurablesappendgetattrZshell_handlersr   Z_darwin_app_napappnopeZnope)r/   r    Zjupyter_session_nameZcomm_msg_typesZmsg_typerI   	__class__r!   r"   r6   i   sF    


zIPythonKernel.__init__zPython Referencezhttps://docs.python.org/%i.%i   )textZurlzIPython Referencez&https://ipython.org/documentation.htmlzNumPy Referencez+https://docs.scipy.org/doc/numpy/reference/zSciPy Referencez+https://docs.scipy.org/doc/scipy/reference/zMatplotlib Referencez$https://matplotlib.org/contents.htmlzSymPy Referencez'http://docs.sympy.org/latest/index.htmlzpandas Referencez-https://pandas.pydata.org/pandas-docs/stable/ZipythonZpythonr   ztext/x-python)nameversionz	ipython%d   z.py)rN   rO   ZmimetypeZcodemirror_modeZpygments_lexerZnbconvert_exporterZfile_extensionc                 C   s4   t r0|d jd}| jd| | jj| d S )Nr   zutf-8zDebugpy received: %s)r   bytesdecoder7   debugr:   Z
tcp_clientZreceive_dap_frame)r/   msgframer!   r!   r"   dispatch_debugpy   s    zIPythonKernel.dispatch_debugpyc                 C   s   | j jS N)r-   bannerr/   r!   r!   r"   rX      s    zIPythonKernel.bannerc                    s   | j  I dH  q dS )zPoll the stopped queue.N)r:   Zhandle_stopped_eventrY   r!   r!   r"   poll_stopped_queue   s    z IPythonKernel.poll_stopped_queuec                    s\   d| j _| jdkr | jd n| jj| jdd t   | jrXt	
|  | jjj dS )zStart the kernel.FNz7debugpy_stream undefined, debugging will not be enabledcopy)r-   exit_nowr8   r7   ZwarningZon_recvrV   r5   startasyncioZrun_coroutine_threadsaferZ   Zcontrol_threadio_loopZasyncio_looprY   rJ   r!   r"   r^      s    

 zIPythonKernel.startr-   c                    s(   t  ||| |dkr$| j| dS )zmOverridden from parent to tell the display hook and output streams
        about the parent message.
        r-   N)r5   
set_parentr-   )r/   identr3   channelrJ   r!   r"   ra      s    zIPythonKernel.set_parentc                    s"   t  |}|d| jd |S )zVInitialize metadata.

        Run at the beginning of each execution request.
        T)dependencies_metZengine)r5   init_metadataupdaterb   )r/   r3   ZmdrJ   r!   r"   re      s    zIPythonKernel.init_metadatac                 C   s0   |d |d< |d dkr,|d dkr,d|d< |S )zXFinish populating metadata.

        Run after completing an execution request.
        statuserrorenameZUnmetDependencyFrd   r!   )r/   r3   metadatareply_contentr!   r!   r"   finish_metadata   s    zIPythonKernel.finish_metadataFc                 C   s*   || _ tj| _| jt_tj| _| jt_dS )zZForward raw_input and getpass to the current frontend.

        via input_request
        N)Z_allow_stdinbuiltinsinput_sys_raw_inputZ	raw_inputgetpass_save_getpass)r/   allow_stdinr!   r!   r"   _forward_input
  s
    zIPythonKernel._forward_inputc                 C   s   | j t_| jt_dS )zRestore raw_input, getpassN)ro   rm   rn   rq   rp   rY   r!   r!   r"   _restore_input  s    zIPythonKernel._restore_inputc                 C   s   | j jS rW   )r-   execution_countrY   r!   r!   r"   ru     s    zIPythonKernel.execution_countc                 C   s   d S rW   r!   )r/   valuer!   r!   r"   ru   !  s    c              
   #   sl   t  dd }t|| |t|  fdd}ttj|}z
dV  W 5 ttj| X dS )aP  ContextManager for capturing SIGINT and cancelling a future

        SIGINT raises in the event loop when running async code,
        but we want it to halt a coroutine.

        Ideally, it would raise KeyboardInterrupt,
        but this turns it into a CancelledError.
        At least it gets a decent traceback to the user.
        c                 S   s    |   s|  rd S |   d S rW   )	cancelleddonecancel)fZ_ignoredr!   r!   r"   cancel_unless_done6  s    z;IPythonKernel._cancel_on_sigint.<locals>.cancel_unless_donec                     s   fdd} j | d S )Nc                      s"      s  rd S  d d S )Nr   )rw   rx   Z
set_resultr!   )sigint_futurer!   r"   set_sigint_resultC  s    zQIPythonKernel._cancel_on_sigint.<locals>.handle_sigint.<locals>.set_sigint_result)r`   Zadd_callback)r   r}   r/   r|   r!   r"   handle_sigintB  s    z6IPythonKernel._cancel_on_sigint.<locals>.handle_sigintN)r_   ZFutureZadd_done_callbackr   signalSIGINT)r/   Zfuturer{   r   Zsave_sigintr!   r~   r"   _cancel_on_sigint'  s    

zIPythonKernel._cancel_on_sigint)cell_idc                   sn  | j  | | i }t dr>t dr> j} j}	t|}
ndd }	 fdd}t j}
zd}z| j |}W n  t	k
r   |}t
 }Y nX trJ jtkrJt  rJ|	|||drJ|
r|||||||d	}n||||||d
}t|}| |< d}z|I dH }W 5  jd |s< jd| X W 5 Q R X n*|
rd j||||d}n j|||d}W 5 |   X |jdk	r|jn|j}|jrd|d< nJd|d< | jpg tt|jt|d t| j| jdd}||d<  j d |d< d|kr&| j!"dd#|d  |d dkrJ $|p@i |d< ni |d<  j%& |d<  j%'  |S )zHandle code execution.run_cell_asyncshould_run_asyncc                 S   s   dS )NFr!   )Zcellr!   r!   r"   <lambda>h      z*IPythonKernel.do_execute.<locals>.<lambda>c                     s    j | |S rW   )run_cellr   r-   r!   r"   r   l  s    z*IPythonKernel.do_execute.<locals>.run_cellN)transformed_cellpreprocessing_exc_tuple)store_historysilentr   r   r   )r   r   r   r   Zpost_executeZpost_run_cell)r   r   r   )r   r   okrg   rh   	tracebackri   ZevalueZexecuteZengine_uuidZ	engine_idmethodengine_infor   ru   r   z Exception in execute request:
%s
user_expressionsZpayload)(r-   rs   hasattrr   r   r   r   rt   Ztransform_cell	Exceptionsysexc_infor   Zloop_runnerr_   Zget_event_loopZ
is_runningZensure_futurer   ZeventsZtriggerZerror_before_execZerror_in_execsuccessrf   _last_tracebackstrtype__name__dictrb   int_idru   r7   infojoinr   Zpayload_managerZread_payloadZclear_payload)r/   coder   r   r   rr   r   rk   r   r   Zwith_cell_idr   r   coroZcoro_futurereserre_infor!   r   r"   
do_executeS  s    




	



	

zIPythonKernel.do_executec                 C   sh   t r| jr| ||S |dkr&t|}t||\}}|| }| jd||\}}|||t| i ddS )zHandle code completion.N r   matchesZ
cursor_endZcursor_startrj   rg   )_use_experimental_60_completionuse_experimental_completions_experimental_do_completelenr   r-   Zcomplete)r/   r   
cursor_poslineoffsetZline_cursorZtxtr   r!   r!   r"   do_complete  s    

zIPythonKernel.do_completec                    s   t r| j|I dH S dS )zHandle a debug request.N)r   r:   Zprocess_request)r/   rT   r!   r!   r"   do_debug_request  s    zIPythonKernel.do_debug_requestc           
      C   s   |dkrt |}t T | jj||}tt||}g }|D ]&}|t|j	|j
|j|j|jd q>W 5 Q R X |r|d j	}|d j
}dd |D }	n|}|}g }	|	||t|iddS )zD
        Experimental completions from IPython, using Jedi.
        N)r^   endrM   r   	signaturer   c                 S   s   g | ]
}|j qS r!   )rM   ).0cr!   r!   r"   
<listcomp>  s     z;IPythonKernel._experimental_do_complete.<locals>.<listcomp>r   r   )r   _provisionalcompleterr-   Z	Completercompletionslist_rectify_completionsrG   r   r^   r   rM   r   r   _EXPERIMENTAL_KEY_NAME)
r/   r   r   Zraw_completionsr   compscompser   r!   r!   r"   r     s:    


z'IPythonKernel._experimental_do_completer!   c                 C   s   t ||}ddi}i |d< i |d< z^tjdkrB| jj|||d}n| jj||d}|d | | jjsv|d d d	|d
< W n tk
r   d|d
< Y nX |S )zHandle code inspection.rg   r   datarj   )   )detail_levelomit_sections)r   z	text/htmlTfoundF)	r   r   version_infor-   Zobject_inspect_mimerf   Zenable_html_pagerpopKeyError)r/   r   r   r   r   rN   rk   Zbundler!   r!   r"   
do_inspect   s&    

zIPythonKernel.do_inspectc
                 C   sv   |dkr | j jj|||dd}
nH|dkrB| j jj|||||d}
n&|dkrd| j jj|||||	d}
ng }
dt|
d	S )
zHandle code history.tailT)rawoutputZinclude_latestrange)r   r   search)r   r   nuniquer   )rg   history)r-   Zhistory_managerZget_tailZ	get_ranger   r   )r/   Zhist_access_typer   r   r9   r^   stopr   patternr   Zhistr!   r!   r"   
do_history;  s6               zIPythonKernel.do_historyc                 C   s   d| j _td|dS )zHandle kernel shutdown.Tr   )rg   restart)r-   r]   r   )r/   r   r!   r!   r"   do_shutdown^  s    zIPythonKernel.do_shutdownc                 C   sL   t | jdd}|dkr| jj}||\}}d|i}|dkrHd| |d< |S )zHandle an is_complete request.Zinput_transformer_managerNrg   Z
incomplete indent)rH   r-   Zinput_splitterZcheck_complete)r/   r   Ztransformer_managerrg   Zindent_spacesrr!   r!   r"   do_is_completec  s    zIPythonKernel.do_is_completec              
   C   s  zddl m}m} W n$ tk
r8   ddlm}m} Y nX | j}z|j}dt|dd d }	|||dd\}
}}t	|
d	d
}|	d
 }|	d }|	d }|	d }||
|||||di}|
| | d| d| d| d}zt||j|j ||}W 5 |D ]}|| qX ||| jj| jjd}W n tk
r } z|  |jpNg tt|jt|d}t| j| jdd}||d< | j| jd|| ddd | jdd|d  g }d|d< W 5 d}~X Y n
X ddi}||fS ) zHandle an apply request.r   )serialize_objectunpack_apply_messager   _-r   Fr[   r   rz   r   r    resultNz = z(*z,**))buffer_thresholditem_thresholdr   Zapplyr   r   rh   r-   )rb   rc   zException in apply request:
%sr   r   rg   r   ) Zipyparallel.serializer   r   ImportErrorZ	serializer-   r1   r   replacerH   rf   r   execZuser_global_nsr@   r9   r   r   BaseExceptionZshowtracebackr   r   r   r   rb   r   Zsend_responserA   rB   r7   r   r   )r/   ZcontentZbufsZmsg_idZreply_metadatar   r   r-   Zworkingprefixrz   r   r    fnameargnameZ	kwargnameZ
resultnamensr   keyr   Z
result_bufr   rk   r   r!   r!   r"   do_applyo  s^    


zIPythonKernel.do_applyc                 C   s   | j d tddS )zClear the kernel.Fr   )rg   )r-   resetr   rY   r!   r!   r"   do_clear  s    zIPythonKernel.do_clear)r-   )F)TNF)r   r!   )r   r   NNNF)=r   
__module____qualname____doc__r
   r-   r   r   r;   r   tagr   r   r   r8   r   r*   r   r   r0   r   r1   r2   ro   Z_sys_eval_inputr6   r   r   r   Z
help_linksimplementationr   rO   Zimplementation_versionsplitZlanguage_inforV   propertyrX   rZ   r^   ra   re   rl   rs   rt   ru   setterr   r   r   r   r   r   r   r   r   r   r   r   __classcell__r!   r!   rJ   r"   r'   F   s   1"





/    '
       
#Ar'   c                       s    e Zd ZdZ fddZ  ZS )r   z3DEPRECATED.  An alias for the IPython kernel class.c                    s&   ddl }|dt t j|| dS )zDEPRECATED.r   Nz@Kernel is a deprecated alias of ipykernel.ipkernel.IPythonKernel)warningswarnDeprecationWarningr5   r6   )r/   r   r    r   rJ   r!   r"   r6     s    zKernel.__init__)r   r   r   r   r6   r   r!   r!   rJ   r"   r     s   r   )Dr   r_   rm   rp   r>   r   r   	threadingtypingt
contextlibr   	functoolsr   rC   ZIPython.corer   ZIPython.utils.tokenutilr   r   Z	traitletsr   r   r	   r
   r   r   r   r   Zzmq.eventloop.zmqstreamr   Z	comm.commr   Zcomm.managerr   Zcompilerr   r:   r   r   Z
eventloopsr   Z
kernelbaser   Z
KernelBaser   Zzmqshellr   ZIPython.core.interactiveshellr   r   ZIPython.core.completerr   r   r   r   r   r   r#   Lockr%   r$   ZOptional__annotations__r&   Zcreate_commrD   r'   r!   r!   r!   r"   <module>   s\   (


    w