U
    ҥch                  
   @   s  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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lmZ W n  ek
r   dd	lmZ Y nX d
dlmZmZmZ z0ddlmZ ddlmZ ddlmZmZ dZ W nR ek
r   dZ Y n< e!k
r0 Z" ze"j#j$dkrdZ ne"W 5 dZ"["X Y nX e%eddpDej&Z'G dd dZ(G dd dZ)G dd dZ*G dd dZ+G dd dZ,G dd dZ-G dd  d Z.dS )!z/Debugger implementation for the IPython kernel.    N)get_ipython)leading_empty_lines)Event)Queue)jsonapi)json_default)date_default   )get_file_nameget_tmp_directoryget_tmp_hash_seed)api)pydevd_frame_utils)SuspendedFramesManager_FramesTrackerTFZDebuggerInitializationError
ROUTING_IDc                   @   s   e Zd ZdZdd ZdS )	_FakeCodezFake code class.c                 C   s   || _ || _dS Init.N)co_filenameco_name)selfr   r    r   1lib/python3.8/site-packages/ipykernel/debugger.py__init__2   s    z_FakeCode.__init__N__name__
__module____qualname____doc__r   r   r   r   r   r   /   s   r   c                   @   s   e Zd ZdZdd ZdS )
_FakeFramezFake frame class.c                 C   s   || _ || _|| _d| _dS r   )f_code	f_globalsf_localsf_back)r   r!   r"   r#   r   r   r   r   ;   s    z_FakeFrame.__init__Nr   r   r   r   r   r    8   s   r    c                   @   s   e Zd ZdZdd ZdS )
_DummyPyDBzFake PyDb class.c                 C   s   ddl m} | | _dS )r   r   )	PyDevdAPIN)Z_pydevd_bundle.pydevd_apir&   ZVariablePresentationZvariable_presentation)r   r&   r   r   r   r   F   s    z_DummyPyDB.__init__Nr   r   r   r   r   r%   C   s   r%   c                   @   s2   e Zd ZdZdd Zdd Zdd Zdd	d
ZdS )VariableExplorerzA variable explorer.c                 C   s*   t  | _t | _t| j| j| _d| _dS )zInitialize the explorer.N)r   suspended_frame_managerr%   Zpy_dbr   trackerframer   r   r   r   r   P   s    zVariableExplorer.__init__c                 C   s:   t  j}ttdtd||| _| jdt	| j dS )zStart tracking.<module>zsys._getframe()Zthread1N)
r   Zuser_nsr    r   r
   r*   r)   trackr   Zcreate_frames_list_from_frame)r   varr   r   r   r-   W   s    zVariableExplorer.trackc                 C   s   | j   dS )zStop tracking.N)r)   untrack_allr+   r   r   r   r/   ]   s    zVariableExplorer.untrack_allNc                 C   s0   |}|st | j}| j|}dd | D S )z1Get the child variables for a variable reference.c                 S   s   g | ]}|  qS r   )Zget_var_data).0xr   r   r   
<listcomp>g   s     z;VariableExplorer.get_children_variables.<locals>.<listcomp>)idr*   r(   Zget_variableget_children_variables)r   Zvariable_refZvar_ref	variablesr   r   r   r4   a   s
    
z'VariableExplorer.get_children_variables)N)r   r   r   r   r   r-   r/   r4   r   r   r   r   r'   M   s
   r'   c                   @   sH   e Zd ZdZdZdZdZdZdd Zdd	 Z	d
d Z
dd Zdd ZdS )DebugpyMessageQueuezA debugpy message queue.zContent-Length:    z

   c                 C   s&   d| _ |   || _t | _|| _dS )zInit the queue. N)
tcp_buffer_reset_tcp_posevent_callbackr   message_queuelog)r   r<   r>   r   r   r   r   r   s
    zDebugpyMessageQueue.__init__c                 C   s   d| _ d| _d| _d| _d S )Nr   )
header_posseparator_posmessage_sizemessage_posr+   r   r   r   r;   z   s    z"DebugpyMessageQueue._reset_tcp_posc                 C   s   | j d ttjttjf t|}|d dkrZ| j d | j | | 	| n$| j d | j | | j
| d S )NzQUEUE - _put_message:typeeventzQUEUE - received event:zQUEUE - put message:)r>   debugtcastZDictstrZAnyr   loadsr<   r=   
put_nowait)r   Zraw_msgmsgr   r   r   _put_message   s    z DebugpyMessageQueue._put_messagec                 C   s  |  j |7  _ | jd | jdkr4| j tj| _| jdkrBdS | jd| j | jdkrz| jtj }| j tj	|| _| jdkrdS | jd| j | j
dkr| jtj }| jtj | _
t| j || j | _| jd| j
 | jd| j t| j | j
 | jk rdS | | j | j
| j
| j   t| j | j
 | jkrb| jd d	| _ |   dS | j | j
| j d | _ | jd
| j  |   qdS )zPut a tcp frame in the queue.zQUEUE - received framer?   NzQUEUE - found header at pos %iz!QUEUE - found separator at pos %izQUEUE - found message at pos %izQUEUE - message size is %izQUEUE - resetting tcp_bufferr9   zQUEUE - slicing tcp_buffer: %s)r:   r>   rF   r@   findr6   HEADERrA   HEADER_LENGTH	SEPARATORrC   SEPARATOR_LENGTHintrB   lenrM   r;   )r   r*   ZhintZsize_posr   r   r   put_tcp_frame   s@    




z!DebugpyMessageQueue.put_tcp_framec                    s   | j  I dH S )zGet a message from the queue.N)r=   getr+   r   r   r   get_message   s    zDebugpyMessageQueue.get_messageN)r   r   r   r   rO   rP   rQ   rR   r   r;   rM   rU   rW   r   r   r   r   r6   j   s   /r6   c                   @   sh   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )DebugpyClientzA client for debugpy.c                 C   sL   || _ || _|| _t| j| j | _d| _d| _d| _d| _	t
 | _d| _dS )zInitialize the client.	127.0.0.1r?   NT)r>   debugpy_streamr<   r6   _forward_eventr=   debugpy_hostdebugpy_port
routing_idwait_for_attachr   
init_eventinit_event_seq)r   r>   rZ   r<   r   r   r   r      s    zDebugpyClient.__init__c                 C   s    |   \}}d| d t| S )Ntcp://:)get_host_portrI   )r   hostportr   r   r   _get_endpoint   s    zDebugpyClient._get_endpointc                 C   s.   |d dkr | j   |d | _| | d S )NrE   Zinitializedseq)r`   setra   r<   r   rL   r   r   r   r[      s    

zDebugpyClient._forward_eventc                 C   s   | j d kr| jjt| _ tj|tddd}tt	|}t
j| t
j d}||7 }| jd | j| j  | j| | j| j |f d S )NF)defaultZensure_asciiZ	allow_nanasciizDEBUGPYCLIENT:)r^   rZ   socket
getsockoptr   r   dumpsr   rI   rT   r6   rO   rQ   encoder>   rF   Zsend_multipart)r   rL   contentZcontent_lengthbufr   r   r   _send_request   s"    
zDebugpyClient._send_requestc                    s   | j  I d H S N)r=   rW   r+   r   r   r   _wait_for_response   s    z DebugpyClient._wait_for_responsec                    sP   | j  I d H  dt| jd dd}| | |  I d H  |  I d H }|S )Nrequestr	   configurationDone)rD   rh   command)r`   waitrS   ra   rs   ru   )r   rw   Z
attach_repr   r   r   _handle_init_sequence   s    
z#DebugpyClient._handle_init_sequencec                 C   sn   | j dkrb| jj}|d| j  |tjd| _	|
| j	 | j	d}| j	|d d | _ | j| j fS )zGet the host debugpy port.r?   rb   utf-8rc   r	   N)r]   rZ   rm   Zbind_to_random_portr\   rn   zmqZLAST_ENDPOINTdecodeendpointZunbindrfind)r   rm   indexr   r   r   rd     s    
zDebugpyClient.get_host_portc                 C   s&   | j j|   | j jt| _dS )zConnect to the tcp socket.N)rZ   rm   connectrg   rn   r   r^   r+   r   r   r   connect_tcp_socket  s    z DebugpyClient.connect_tcp_socketc                 C   s0   | j j|   d| _t | _d| _d| _dS )zDisconnect from the tcp socket.Nr?   T)	rZ   rm   
disconnectrg   r^   r   r`   ra   r_   r+   r   r   r   disconnect_tcp_socket  s
    z#DebugpyClient.disconnect_tcp_socketc                 C   s   | j | dS )zReceive a dap frame.N)r=   rU   )r   r*   r   r   r   receive_dap_frame  s    zDebugpyClient.receive_dap_framec                    sb   |  | | jr4|d dkr4|  I dH }d| _|S |  I dH }| jd | j| |S dS )zSend a dap request.rx   attachNFzDEBUGPYCLIENT - returning:)rs   r_   rz   ru   r>   rF   )r   rL   repr   r   r   send_dap_request"  s    
zDebugpyClient.send_dap_requestN)r   r   r   r   r   rg   r[   rs   ru   rz   rd   r   r   r   r   r   r   r   r   rX      s   rX   c                   @   s   e Zd ZdZdddddddgZd	d
dddgZd>ddZdd Zdd Zdd Z	dd Z
dd Zedd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Zd=S )?DebuggerzThe debugger class.dumpCellsetBreakpointssource
stackTracer5   r   rw   	debugInfoinspectVariablesrichInspectVariablesmodulescopyToGlobalsTc                 C   s   || _ t||| j| _|| _|| _d| _|| _|| _t	 | _
i | _tjD ]}t| || j|< qHi | _tjD ]}t| || j|< qji | _t | _d| _i | _d| _d| _d| _t | _dS )zInitialize the debugger.FrY   r   N)r>   rX   _handle_eventdebugpy_clientshell_socketsession
is_startedr<   just_my_coder   stopped_queuestarted_debug_handlersr   started_debug_msg_typesgetattrstatic_debug_handlersstatic_debug_msg_typesbreakpoint_listri   stopped_threadsdebugpy_initialized_removed_cleanupr\   r]   r~   r'   variable_explorer)r   r>   rZ   r<   r   r   r   Zmsg_typer   r   r   r   G  s,    

zDebugger.__init__c                 C   s   |d dkrH|d d r(| j | d S | j|d d  | | nL|d dkr|d d rjt | _n| j|d d  | | n
| | d S )NrE   stoppedbodyZallThreadsStoppedZthreadId	continuedZallThreadsContinued)r   rK   r   addr<   ri   removerj   r   r   r   r   h  s    
zDebugger._handle_eventc                    s   | j |I d H S rt   )r   r   rj   r   r   r   _forward_messagez  s    zDebugger._forward_messagec                    s8    fdd|D }|d d|d d|d d|id}|S )	Nc                    s   g | ]}  |d  r|qS nameaccept_variabler0   r.   r+   r   r   r2   ~  s      z6Debugger._build_variables_response.<locals>.<listcomp>rh   responseTrx   r5   )rh   rD   request_seqsuccessrx   r   r   )r   rv   r5   Zvar_listreplyr   r+   r   _build_variables_response}  s    z"Debugger._build_variables_responsec                 C   s   ddddg}||kS )NZIPythonHistorySavingThreadzThread-2zThread-3zThread-4r   )r   Zthread_nameforbid_listr   r   r   _accept_stopped_thread  s    zDebugger._accept_stopped_threadc                    sr   | j  I dH }|d d ddd}| |I dH }|d d D ]"}| |d r@| j|d	  q@| | dS )
zHandle a stopped event.Nrh   r	   rv   threads)rh   rD   rx   r   r   r3   )r   rV   r   r   r   r   r<   )r   rE   Zreqr   threadr   r   r   handle_stopped_event  s    zDebugger.handle_stopped_eventc                 C   s   | j S rt   )r   r+   r   r   r   
tcp_client  s    zDebugger.tcp_clientc           
   	   C   s   | j st }tj|s"t| | j \}}d}|d| d | d 7 }|dd}| j	| j
d|d| j
t | jj| j
d	d
\}}|d d dk| _ t jj}t|kr|t}	||	| j|	< | j  | j S )zStart the debugger.zimport debugpy;zdebugpy.listen(("z",z))T)codeZsilentZexecute_requestNr   )moderq   statusok)r   r   ospathexistsmakedirsr   rd   r   sendr   rn   r   Zrecvr   input_transformer_managercleanup_transformsr   r   popr   r   )
r   Ztmp_dirre   rf   r   rq   identrL   r   r   r   r   r   start  s.    





zDebugger.startc                 C   s@   | j   t jj}t| jD ]}| j|}||| qdS )zStop the debugger.N)	r   r   r   r   r   sortedr   r   insert)r   r   r   funcr   r   r   stop  s
    

zDebugger.stopc              	      sX   |d d }t |}t|ddd}|| W 5 Q R X d|d d|d	 d
|id}|S )zHandle a dump cell message.	argumentsr   wr{   encodingr   rh   Trx   Z
sourcePathrD   r   r   rx   r   )r
   openwrite)r   messager   	file_namefr   r   r   r   r     s    zDebugger.dumpCellc                    s2   |d d d }|d d | j |< | |I dH S )z!Handle a set breakpoints message.r   r   r   breakpointsN)r   r   )r   r   r   r   r   r   r     s    zDebugger.setBreakpointsc              	      s~   d|d |d d}|d d d }t j|rbt|dd	}d
|d< d| i|d< W 5 Q R X nd|d< d|d< i |d< |S )zHandle a source message.r   rh   rx   )rD   r   rx   r   r   r   r{   r   Tr   rq   r   Fzsource unavailabler   )r   r   isfiler   read)r   r   r   source_pathr   r   r   r   r     s    zDebugger.sourcec                    s~   |  |I dH }zT|d d }t|tdd tt|dD  }|d d d|d  |d d< W n tk
rx   Y nX |S )zHandle a stack trace message.Nr   ZstackFramesc                 s   s*   | ]"\}}|d  dkr|dkr|V  qdS )r   r,   r	   Nr   )r0   ivr   r   r   	<genexpr>  s      z&Debugger.stackTrace.<locals>.<genexpr>r	   )r   rT   next	enumeratereversedStopIteration)r   r   r   Zsf_listZ
module_idxr   r   r   r     s    

$zDebugger.stackTracec                 C   sb   ddddddddd	d
ddddddddddg}||k}|oHt td| }|o\|dd dk}|S )zAccept a variable by name.r   r   __package__
__loader____spec____annotations____builtins__Z__builtin__Z__display__r   ZdebugpyexitquitZInZOutZ_ohZ_dh___Z___z^_\dr      Z_i)boolresearch)r   Zvariable_namer   Zcondr   r   r   r     s2    zDebugger.accept_variablec                    s`   i } j s* j|d d } ||S  |I dH } fdd|d d D |d d< |S )zHandle a variables message.r   ZvariablesReferenceNc                    s   g | ]}  |d  r|qS r   r   r   r+   r   r   r2   +  s     z&Debugger.variables.<locals>.<listcomp>r   r5   )r   r   r4   r   r   )r   r   r   r5   r   r+   r   r5      s    


zDebugger.variablesc                    sP   | j  \}}||d|d d< d|d d< | js@dg|d d< | |I dH S )	zHandle an attach message.)re   rf   r   r   TZ	logToFileZDebugStdLibZdebugOptionsN)r   rd   r   r   )r   r   re   rf   r   r   r   r   0  s    zDebugger.attachc                    s    |d d|d d|d d}|S )z$Handle a configuration done message.rh   r   Trx   )rh   rD   r   r   rx   r   )r   r   r   r   r   r   rw   =  s    zDebugger.configurationDonec                    sl   g }| j  D ]\}}|||d qd|d d|d | jdt t tj d|t| j	ddgd		d
}|S )zHandle a debug info message.)r   r   r   rh   Trx   ZMurmur2.pyzPython Exceptions)	Z	isStartedZ
hashMethodZhashSeedZtmpFilePrefixZtmpFileSuffixr   ZstoppedThreadsZrichRenderingZexceptionPathsr   )
r   itemsappendr   r   r   r   seplistr   )r   r   r   keyvaluer   r   r   r   r   H  s&    
zDebugger.debugInfoc                    s2   | j   t | _ | j   | j  }| ||S )z$Handle an insepct variables message.)r   r/   r'   r-   r4   r   )r   r   r5   r   r   r   r   `  s
    


zDebugger.inspectVariablesc              	      s>  d|d d|d d}|d d }t |}|sZi i d|d	< |d
ksN|dkrVd|d< |S i  i }| jst ||i| }|dddkr|di  |di }nhd| d}|d d }|d }	| dd|	d ||dddI dH }|d rt|d	 d i i \ }  fdd| D d}
|
|d	< d|d< |S ) z(Handle a rich inspect variables message.r   rh   Frx   )rD   Zsequence_seqr   rx   r   ZvariableName)datametadatar   zspecial variableszfunction variablesTr   r   errorr   r   r   z'get_ipython().display_formatter.format()frameIdrv   Zevaluater	   Z	clipboard)
expressionr   contextrD   rx   rh   r   Nresultc                    s   i | ]\}}| kr||qS r   r   )r0   kr   Z	repr_datar   r   
<dictcomp>  s       z1Debugger.richInspectVariables.<locals>.<dictcomp>)	rI   isidentifierr   r   Zuser_expressionsrV   r   evalr   )r   r   r   Zvar_nameZ
valid_nameZrepr_metadatar   r   Zframe_idrh   r   r   r   r   r   k  sJ    



zDebugger.richInspectVariablesc              	      s^   |d d }|d d }|d d }d| d}|d }|  dd	|d
 |||ddI d H S )Nr   ZdstVariableNameZsrcVariableNameZ
srcFrameIdzglobals()['z']rh   rv   ZsetExpressionr	   )r   r   r   r   )r   )r   r   Zdst_var_nameZsrc_var_nameZsrc_frame_idr   rh   r   r   r   r     s    zDebugger.copyToGlobalsc           
         s   t tj }|dd}|dt|}g }t||D ]B}|| }tt|dddd}|r8|dr8|	||j
|d q8d	|t|d
i}	|	S )zHandle a modules message.startModuler   moduleCountr   Noriginr   )r3   r   r   r   )r   ZtotalModules)r   sysr   valuesrV   rT   ranger   endswithr   r   )
r   r   r   r  r  modsr   modulefilenamer   r   r   r   r     s    zDebugger.modulesc                    s   i }|d dkrV| j r$| jd n2|  | _ | j rB| jd nd|d dddd	}| j|d d
}|d
k	r||I d
H }n@| j r| j|d d
}|d
k	r||I d
H }n| |I d
H }|d dkr|   i | _	t
 | _d| _ | jd |S )zProcess a request.rx   Z
initializez The debugger has already startedzThe debugger has startedrh      Fr   )rx   r   rh   r   rD   Nr   zThe debugger has stopped)r   r>   infor   r   rV   r   r   r   r   ri   r   )r   r   r   Zhandlerr   r   r   process_request  s8    
zDebugger.process_requestN)T)r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r   r5   r   rw   r   r   r   r   r   r  r   r   r   r   r   0  sP   	 
!

4r   )/r   r   r   r  typingrG   r|   ZIPython.core.getipythonr   ZIPython.core.inputtransformer2r   Ztornado.locksr   Ztornado.queuesr   Z	zmq.utilsr   Zjupyter_client.jsonutilr   ImportErrorr   Zcompilerr
   r   r   Zdebugpy.serverr   Z_pydevd_bundler   Z&_pydevd_bundle.pydevd_suspended_framesr   r   Z_is_debugpy_available	Exceptione	__class__r   r   ZIDENTITYr   r   r    r%   r'   r6   rX   r   r   r   r   r   <module>   sD   	
Vp