
    ueVU                     J   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mZmZ d dlZddlmZmZmZ  ej(                  e      ZdgZ ej0                  d      Z ej0                  d	      Zd
 Z G d d      Z G d d      Z G d d      Z G d de      Zy)    N)contextmanager)RLock)Callable	GeneratorListOptional   )_utilslspurisnumpyz[A-Za-z_0-9]*$z^[A-Za-z_0-9]*c                 B     t        j                          fd       }|S )z&Define an atomic region over a method.c                 `    | j                   5   | g|i |cd d d        S # 1 sw Y   y xY wN)_lock)selfargskwargsmethods      1/usr/lib/python3/dist-packages/pylsp/workspace.pywrapperzlock.<locals>.wrapper   s1    ZZ 	1$000	1 	1 	1s   $-)	functoolswraps)r   r   s   ` r   lockr      s'     __V1 1 N    c                      e Zd ZdZdZdZdZdZd/dZ	 d0de	d	e
fd
Zd Zed        Zed        Zed        Zd Zd Zd Zd Zd/dZ	 d1dZed/d       Zd Zd Zd Z	 d/dZd Zd/dZd Zd Z d Z!e	 	 	 d2de"d e	e"   d!e	e#   d"e
d#e$e%e"e	e#   gdf   ddf   f
d$       Z&	 	 	 d2de"d e	e"   d!e	e#   d"e
d#e"f
d%Z'	 	 d1d&e"d e	e"   d!e	e#   d#dfd'Z(d/d&e"d e	e"   d#dfd(Z)e*jV                  jX                  fd)Z-d* Z.d1d+Z/	 d1d,Z0	 d1d-Z1d. Z2y)3	WorkspaceztextDocument/publishDiagnosticsz
$/progresszwindow/workDoneProgress/createzworkspace/applyEditzwindow/showMessageNc                 
   || _         || _        || _        t        j                  | j                        d   | _        t        j                  | j                        | _        i | _        i | _	        d | _
        d | _        d | _        y )Nr   )_config	_root_uri	_endpointr   urlparse_root_uri_scheme
to_fs_path
_root_path_docs_environments_Workspace__rope_Workspace__rope_config_Workspace__rope_autoimport)r   root_uriendpointconfigs       r   __init__zWorkspace.__init__-   so    !! $dnn =a @//$..9
   !!%r   rope_configmemoryc                 ~    ddl m} | j                   | j                  |      } |||      | _        | j                  S )Nr   )
AutoImport)r0   )rope.contrib.autoimport.sqliter2   r*   _rope_project_builder)r   r/   r0   r2   projects        r   _rope_autoimportzWorkspace._rope_autoimport=   s>    
 	>!!)00=G%/%GD"%%%r   c                    ddl m} | j                  | j                  |k7  r|j	                  d      }|r || j
                  |      | _        n || j
                        | _        | j                  j                  j                  d|j	                  dg              | j                  j                  j                  dd       | j                  j                  j                  d	d       | j                  j                          | j                  S )
Nr   )Project
ropeFolder)
ropefolderextension_modulesextensionModulesignore_syntax_errorsTignore_bad_imports)	rope.base.projectr8   r(   r)   getr%   prefssetvalidate)r   r/   r8   rope_folders       r   r4   zWorkspace._rope_project_builderI   s    - ;;$"4"4"C%//,7K%doo+N%doo6KK!!#[__5G%L KK!!"8$?KK!!"6={{r   c                     | j                   S r   )r&   r   s    r   	documentszWorkspace.documents[   s    zzr   c                     | j                   S r   )r%   rF   s    r   	root_pathzWorkspace.root_path_   s    r   c                     | j                   S r   )r    rF   s    r   r+   zWorkspace.root_uric   s    ~~r   c                 t    | j                   dv xr) t        j                  j                  | j                        S )N) file)r#   ospathexistsr%   rF   s    r   is_localzWorkspace.is_localg   s0    %%5 
277>>OO<
 	
r   c                 ^    | j                   j                  |      xs | j                  |      S )zReturn a managed document if-present, else create one pointing at disk.

        See https://github.com/Microsoft/language-server-protocol/issues/177
        )r&   r@   _create_documentr   doc_uris     r   get_documentzWorkspace.get_documentl   s'    
 zz~~g&H$*?*?*HHr   c                 8    | j                   j                  |      S r   r&   r@   rT   s     r   get_cell_documentzWorkspace.get_cell_documents       zz~~g&&r   c                 8    | j                   j                  |      S r   rX   rT   s     r   get_maybe_documentzWorkspace.get_maybe_documentv   rZ   r   c                 F    | j                  |||      | j                  |<   y )N)sourceversion)rS   r&   )r   rU   r^   r_   s       r   put_documentzWorkspace.put_documenty   s'    "33FG 4 


7r   c                 H    | j                  |||||      | j                  |<   y r   )_create_notebook_documentr&   r   rU   notebook_typecellsr_   metadatas         r   put_notebook_documentzWorkspace.put_notebook_document~   s(     #<<]E7H


7r   c           	   #   @  K   || j                   }t        j                  t        j                  j                  |t        t        j                                           }	 | j                  ||       | | j                  |       y # | j                  |       w xY wwr   )rI   r   from_fs_pathrN   rO   joinstruuiduuid4r`   rm_document)r   r^   rO   uris       r   temp_documentzWorkspace.temp_document   st     <>>DT3tzz|3D EF	"c6*IS!DS!s   AB B 6BBBc                 B    | j                   |   j                  ||       y r   )r&   	add_cells)r   rU   re   starts       r   add_notebook_cellszWorkspace.add_notebook_cells   s    

7%%eU3r   c                 B    | j                   |   j                  ||       y r   )r&   remove_cells)r   rU   rs   delete_counts       r   remove_notebook_cellszWorkspace.remove_notebook_cells   s    

7((=r   c                 ,    || j                   |   _        y r   )r&   rf   )r   rU   rf   s      r   update_notebook_metadataz"Workspace.update_notebook_metadata   s    '/

7$r   c                 H    | j                  |||||      | j                  |<   y r   )_create_cell_documentr&   )r   rU   notebook_urilanguage_idr^   r_   s         r   put_cell_documentzWorkspace.put_cell_document   s(     #88\;


7r   c                 :    | j                   j                  |       y r   )r&   poprT   s     r   rn   zWorkspace.rm_document   s    

wr   c                 h    | j                   |   j                  |       || j                   |   _        y r   )r&   apply_changer_   )r   rU   changer_   s       r   update_documentzWorkspace.update_document   s*    

7((0&-

7#r   c                     | j                   j                  |xs i j                  di              | j                  D ]6  }t	        | j                  |      x}t              r y |j                  |       8 y Npylsp)r   updater@   rG   
isinstancerV   Notebookupdate_config)r   settingsrU   documents       r   r   zWorkspace.update_config   se    X^00"=>~~ 	-Gd&7&7&@@((K ""8,	-r   c                 R    | j                   j                  | j                  d|i      S )Nedit)r!   requestM_APPLY_EDIT)r   r   s     r   
apply_editzWorkspace.apply_edit   s#    ~~%%d&7&7&$HHr   c                 X    | j                   j                  | j                  ||d       y )N)ro   diagnosticsparams)r!   notifyM_PUBLISH_DIAGNOSTICS)r   rU   r   s      r   publish_diagnosticszWorkspace.publish_diagnostics   s*    &&";? 	 	
r   titlemessage
percentageskip_token_initializationreturnc              #      K    j                   r7 j                   j                  j                  di       j                  dd      }nd}|rI j                  ||||      	 d
dt        dt
        t           ddf fd}	 |  j                         y	 d
dt        dt
        t           ddfd	}| y#  j                         w xY ww)a  
        Report progress to the editor / client.

        ``skip_token_initialization` is necessary due to some current
        limitations of our LSP implementation. When `report_progress`
        is used from a synchronous LSP handler, the token initialization
        will time out because we can't receive the response.

        Many editors will still correctly show the progress messages though, which
        is why we are giving progress users the option to skip the initialization
        of the progress token.
        windowworkDoneProgressFNr   r   r   c                 ,    j                  | |       y r   )_progress_report)r   r   r   tokens     r   progress_messagez3Workspace.report_progress.<locals>.progress_message   s     %%eWjAr   c                      y r    )r   r   s     r   dummy_progress_messagez9Workspace.report_progress.<locals>.dummy_progress_message   s     r   r   )r   capabilitiesr@   _progress_beginrk   r   int_progress_end)	r   r   r   r   r   "client_supports_progress_reportingr   r   r   s	   `       @r   report_progresszWorkspace.report_progress   s     ( <<151J1J1N1N"2c$e, / 27.-((w
,EE
 ;?BB*23-BB
*&&""5) 7;		&.sm		
 %$ ""5)s   A:C?B5 2C5CCc                 |   t        t        j                               }|s9	 | j                  j	                  | j
                  d|i      j                  d       d|d}|||d	<   |||d
<   | j                  j                  | j                  ||d       |S # t        $ r t        j                  dd       Y aw xY w)Nr   g      ?)timeouta=  There was an error while trying to initialize progress reporting.Likely progress reporting was used in a synchronous LSP handler, which is not supported by progress reporting yet. To prevent waiting for the timeout you can set `skip_token_initialization=True`. Not every editor will show progress then, but many will.T)exc_infobegin)kindr   r   r   r   valuer   )rk   rl   rm   r!   r   M_INITIALIZE_PROGRESSresult	Exceptionlogwarningr   
M_PROGRESS)r   r   r   r   r   r   r   s          r   r   zWorkspace._progress_begin   s     DJJL!(&&..%0@&&% 
 &E)!",E,OO 	 	
 7  	O "  	s   8B  B;:B;r   c                 |    ddi}|r||d<   |r||d<   | j                   j                  | j                  ||d       y )Nr   reportr   r   r   r   r!   r   r   )r   r   r   r   r   s        r   r   zWorkspace._progress_report  sU     H
 &E)",E,OO 	 	
r   c                 n    ddi}|r||d<   | j                   j                  | j                  ||d       y )Nr   endr   r   r   r   )r   r   r   r   s       r   r   zWorkspace._progress_end0  sF    E
 &E)OO 	 	
r   c                 X    | j                   j                  | j                  ||d       y )N)typer   r   )r!   r   M_SHOW_MESSAGE)r   r   msg_types      r   show_messagezWorkspace.show_message?  s)    g(N 	 	
r   c                     t        j                  | j                  |ddg      xs g }t        |D ch c]!  }t        j
                  j                  |      # c}      xs | j                  gS c c}w )z/Return the source roots for the given document.zsetup.pyzpyproject.toml)r
   find_parentsr%   listrN   rO   dirname)r   document_pathfilesproject_files       r   source_rootszWorkspace.source_rootsD  sn     =M0N  	 	 uM|RWW__\2MN 
OOS
 	
Ms   &A-c           	          t        j                  |      }t        || ||| j                  |      | j                        S )N)r^   r_   extra_sys_pathrope_project_builder)r   r$   Documentr   r4   )r   rU   r^   r_   rO   s        r   rS   zWorkspace._create_documentP  s@    w',,T2!%!;!;
 	
r   c                 $    t        ||| |||      S )N)re   r_   rf   )r   rc   s         r   rb   z#Workspace._create_notebook_document[  s#     
 	
r   c                     t        j                  |      }t        |||| ||| j                  |      | j                        S )N)r}   r~   	workspacer^   r_   r   r   )r   r$   Cellr   r4   )r   rU   r}   r~   r^   r_   rO   s          r   r|   zWorkspace._create_cell_documentg  sH     w'%#,,T2!%!;!;	
 		
r   c                 R    | j                   r| j                   j                          y y r   )r*   closerF   s    r   r   zWorkspace.closew  s"    !!""((* "r   r   )FNN)NNF)3__name__
__module____qualname__r   r   r   r   r   r.   r   boolr6   r4   propertyrG   rI   r+   rQ   rV   rY   r\   r`   rg   r   rp   rt   rx   rz   r   rn   r   r   r   r   rk   r   r   r   r   r   r   r   r   MessageTypeInfor   r   rS   rb   r|   r   r   r   r   r   r   &   sB   =J<(L)N&& 
&
& 
&$      

I''
 EI
 " "4>0 CG
 .-I
  "&$(*/3%3% #3% SM	3%
 $(3% 
8S(3-0$67tC	D3% 3%p "&$(*/)) #) SM	)
 $() 
)\ "&$(	

 #
 SM	

 

,
3 
# 
$ 
 .1__-A-A 



	
 EI

 HL
 +r   r   c                       e Zd Z	 	 	 	 	 ddZd Zd Zeed               Zeed               Z	d Z
ed        Zd	 Zd
 Zedd       Zedd       ZddZddZy)r   Nc                    || _         || _        t        j                  |      | _        t        j                  | j                        | _        t        j                  j                  | j                        | _
        i | _        |j                  | _        || _        || _        || _        |xs g | _        || _        t%               | _        y r   )ro   r_   r   r$   rO   r
   path_to_dot_namedot_pathrN   basenamefilenameshared_datar   
_workspace_local_source_extra_sys_pathr4   r   r   )r   ro   r   r^   r_   localr   r   s           r   r.   zDocument.__init__}  s     OOC(	//		:((3 ((#-3%9"W
r   c                 ,    t        | j                        S r   rk   ro   rF   s    r   __str__zDocument.__str__  s    488}r   c                 d    ddl m} |j                  | j                  |      | j                        S )Nr   )libutils)	rope.baser   path_to_resourcer4   rO   )r   r/   r   s      r   _rope_resourcezDocument._rope_resource  s,    &((&&{3TYY
 	
r   c                 8    | j                   j                  d      S )NT)r^   
splitlinesrF   s    r   lineszDocument.lines  s     {{%%d++r   c                     | j                   <t        j                  | j                  dd      5 }|j	                         cd d d        S | j                   S # 1 sw Y   | j                   S xY w)Nrzutf-8)encoding)r   ioopenrO   read)r   fs     r   r^   zDocument.source  sV     <<C':  avvx   || ||s   AA)c                 b    | j                   j                  |xs i j                  di              y r   )r   r   r@   )r   r   s     r   r   zDocument.update_config  s%    X^00"=>r   c                 N   |d   }|j                  d      }|s|| _        y|d   d   }|d   d   }|d   d   }|d   d   }|t        | j                        k(  r| j                  |z   | _        yt        j                         }t        | j                        D ]w  \  }	}
|	|k  r|j                  |
       |	|kD  r|j                  |
       4|	|k(  r%|j                  |
d|        |j                  |       |	|k(  sd|j                  |
|d        y |j                         | _        y)zApply a change to the document.textrangeNrs   line	characterr   )
r@   r   lenr   r^   r   StringIO	enumeratewritegetvalue)r   r   r  change_range
start_line	start_colend_lineend_colnewir  s              r   r   zDocument.apply_change  s)    f~zz'*DL!'*62
 )+6	&v.u%k2 TZZ(;;-DLkkm
 !, 	*GAt:~		$8|		$J		$z	*+		$H}		$wx.)	*  ||~r   c           	      b    |d   t        dj                  | j                  d|d                z   S )z8Return the byte-offset pointed at by the given position.r  rL   Nr  )r  rj   r   )r   positions     r   offset_at_positionzDocument.offset_at_position  s1    $s2774::>P@P3Q+R'SSSr   c                     |d   t        | j                        k\  ry| j                  |d      }|d   }|d| }||d }t        j                  |      }t        j                  |      }|d   |d   z   S )zDGet the word under the cursor returning the start and end positions.r  rL   r  Nr   )r  r   RE_START_WORDfindallRE_END_WORD)r   r  r  r  rs   r   m_startm_ends           r   word_at_positionzDocument.word_at_position  s    Fs4::.zz(6*+[!Ra12h  ''.##C(qzE"I%%r   c                 J    | j                         }|j                  |||      S )N)
all_scopesdefinitions
references)jedi_script	get_names)r   r  r  r  scripts        r   
jedi_nameszDocument.jedi_names  s/    !!#!{z   
 	
r   c                    g }d }d }| j                   r| j                   j                  d| j                        }|j                  dt              t
        j                  _        |j                  d      }|r2t        j                  dk7  rt        j                  j                  |      }|j                  d      xs g }|j                  d      }|t        j                  j                         }|j                  dd        |r| j                  ||	      nd }| j                  ||	      |z   }| j                   j"                  }	|rJ|t        j                  j%                  t        j                  j'                  | j                              gz  }| j(                  | j                  |t        j*                  |	|
      d}
|r|
t-        j.                  | |      z  }
t        j0                  di |
S )Njedi)r   auto_import_modulesenvironmentntextra_pathsenv_vars
PYTHONPATH)r*  )rO   sys_path)coderO   r'  r5   r   )r   plugin_settingsrO   r@   DEFAULT_AUTO_IMPORT_MODULESr%  r   r&  rN   name
expanduserenvironcopyr   get_enviromentr,  r   rI   normpathr   r^   r8   r
   position_to_jedi_linecolumnScript)r   r  use_document_pathr)  environment_pathr*  jedi_settingsr'  r,  project_pathr   s              r   r   zDocument.jedi_script  s   << LL88dii 9 M 1>0A0A%'B1DMM-  -00?  BGGtO#%77#5#56F#G '++M:@bK$((4H zz(H\4(    08D 	
 ==!1H=ES00 ))"''//$))*DEFFH KKII&||I	
 f88xHHF{{$V$$r   c                 N   |*t         j                  j                  j                         }|S || j                  j
                  v r| j                  j
                  |   }|S t         j                  j                  j                  |d|      }|| j                  j
                  |<   |S )NF)rO   safer*  )r%  apir'  get_cached_default_environmentr   r'   create_environment)r   r9  r*  r'  s       r   r4  zDocument.get_enviroment.  s    #((..MMOK   4??#@#@@"oo;;<LM  #hh22EE) F  CN--.>?r   c                     t        | j                        }| j                  ||      }|j                  |j	                                |S )N)r9  r*  )r   r   r4  extendget_sys_path)r   r9  r*  rO   r'  s        r   r,  zDocument.sys_path=  sJ     D(()))- * 
 	K,,./r   NNTNN)FTF)NFr   )r   r   r   r.   r   r   r   r   r   r^   r   r   r  r  r#  r   r4  r,  r   r   r   r   r   |  s    
 !2
 	, 
 , 	 
 ? 
)& 
)&VT&$ 

 

 
2% 
2%hr   r   c                   t    e Zd ZdZ	 ddZd ZdededdfdZded	eddfd
Z	d Z
e	 	 	 	 ddee   fd       Zy)r   zRepresents a notebook.Nc                     || _         || _        || _        || _        |xs g | _        |xs i | _        t               | _        y r   )ro   rd   r   r_   re   rf   r   r   )r   ro   rd   r   re   r_   rf   s          r   r.   zNotebook.__init__K  s@     *"[b
 BW
r   c                 2    dt        | j                        z  S )NzNotebook with URI '%s'r   rF   s    r   r   zNotebook.__str__V  s    '#dhh-77r   	new_cellsrs   r   c                 "    || j                   || y r   re   )r   rH  rs   s      r   rr   zNotebook.add_cellsY  s    "+

5r   rw   c                 (    | j                   |||z   = y r   rJ  )r   rs   rw   s      r   rv   zNotebook.remove_cells\  s    JJuu|334r   c                     i }d}| j                   D ]L  }|d   }| j                  j                  |      }|j                  }|||z   dz
  |j                  d||<   ||z  }N |S )zExtract current cell data.

        Returns a dict (ordered by cell position) where the key is the cell uri and the
        value is a dict with line_start, line_end, and source attributes.
        r   r   r	   )
line_startline_endr^   )re   r   rY   
line_countr^   )r   	cell_dataoffsetcellcell_uricell_document	num_liness          r   rP  zNotebook.cell_data_  s     	JJ 		 DJ'H NN<<XFM%00I$"Y.2'..#Ih
 iF		  r   up_to_cell_uric                    t               }| j                  D ]K  }|d   }| j                  j                  |      }|j	                  |j                  |||             ||k(  sK n |D 	ch c]  }	|	j                   c}	S c c}	w )z
        Get the names in the notebook up to a certain cell.

        Parameters
        ----------
        up_to_cell_uri: str, optional
            The cell uri to stop at. If None, all cells are considered.
        r   )rB   re   r   rY   r   r#  r0  )
r   rV  r  r  r  namesrR  rS  rT  r0  s
             r   r#  zNotebook.jedi_namess  s|      JJ 	DJ'H NN<<XFMLL11*k:VW>)	 ',,d		,,,s   )A?)NNN)NFTF)r   r   r   __doc__r.   r   r   r   rr   rv   rP  r   r   rk   r#  r   r   r   r   r   H  s}      QU	8,4 , , ,5# 5S 5T 5( 
 )-- - 
-r   r   c                   H     e Zd ZdZ	 	 	 	 	 d fd	Zeed               Z xZS )r   z
    Represents a cell in a notebook.

    Notes
    -----
    We inherit from Document for now to get the same API. However, a cell document differs from text documents in that
    they have a language id.
    c
           	      L    t         
|   |||||||	       || _        || _        y r   )superr.   r~   r}   )r   ro   r}   r~   r   r^   r_   r   r   r   	__class__s             r   r.   zCell.__init__  s4     	FGUNDX	
 '(r   c                 J    t        | j                  j                  d            S )z2 "Return the number of lines in the cell document.
)r  r^   splitrF   s    r   rO  zCell.line_count  s     4;;$$T*++r   rD  )	r   r   r   rY  r.   r   r   rO  __classcell__)r]  s   @r   r   r     s:     !)$ 	, 
 ,r   r   ) r   r   loggingrN   rerl   
contextlibr   	threadingr   typingr   r   r   r   r%  rL   r
   r   r   	getLoggerr   r   r/  compiler  r  r   r   r   r   r   r   r   r   <module>ri     s     	  	 	  %  6 6   g!&i  

+,bjj)*S+ S+l
I IXB- B-J ,8  ,r   