
    c,                         d dl Z d dlmZmZmZmZmZmZ d dlm	Z	m
Z
mZ d dlmZ  G d d          Zd Z G d d	          ZdS )
    N)astbuiltinschangecodeanalyzelibutils
taskhandle)
patchedastsimilarfindersourceutils)module_importsc                   T    e Zd ZdZddZdddej        fdZd Zd Z	d Z
d Zdd
ZdS )Restructurea  A class to perform python restructurings

    A restructuring transforms pieces of code matching `pattern` to
    `goal`.  In the `pattern` wildcards can appear.  Wildcards match
    some piece of code based on their kind and arguments that are
    passed to them through `args`.

    `args` is a dictionary of wildcard names to wildcard arguments.
    If the argument is a tuple, the first item of the tuple is
    considered to be the name of the wildcard to use; otherwise the
    "default" wildcard is used.  For getting the list arguments a
    wildcard supports, see the pydoc of the wildcard.  (see
    `rope.refactor.wildcard.DefaultWildcard` for the default
    wildcard.)

    `wildcards` is the list of wildcard types that can appear in
    `pattern`.  See `rope.refactor.wildcards`.  If a wildcard does not
    specify its kind (by using a tuple in args), the wildcard named
    "default" is used.  So there should be a wildcard with "default"
    name in `wildcards`.

    `imports` is the list of imports that changed modules should
    import.  Note that rope handles duplicate imports and does not add
    the import if it already appears.

    Example #1::

      pattern ${pyobject}.get_attribute(${name})
      goal ${pyobject}[${name}]
      args pyobject: instance=rope.base.pyobjects.PyObject

    Example #2::

      pattern ${name} in ${pyobject}.get_attributes()
      goal ${name} in {pyobject}
      args pyobject: instance=rope.base.pyobjects.PyObject

    Example #3::

      pattern ${pycore}.create_module(${project}.root, ${name})
      goal generate.create_module(${project}, ${name})

      imports
       from rope.contrib import generate

      args
       project: type=rope.base.project.Project

    Example #4::

      pattern ${pow}(${param1}, ${param2})
      goal ${param1} ** ${param2}
      args pow: name=mod.pow, exact

    Example #5::

      pattern ${inst}.longtask(${p1}, ${p2})
      goal
       ${inst}.subtask1(${p1})
       ${inst}.subtask2(${p2})
      args
       inst: type=mod.A,unsure

    Nc                     || _         || _        || _        || _        | j        i | _        || _        | j        g | _        || _        t          j        | j                  | _        dS )z_Construct a restructuring

        See class pydoc for more info about the arguments.

        N)	projectpatterngoalargsimports	wildcardsr
   CodeTemplatetemplate)selfr   r   r   r   r   r   s          9lib/python3.11/site-packages/rope/refactor/restructure.py__init__zRestructure.__init__J   sh     		9 	DI< 	DL"%249==    c                     |Rt          j        dt          d           |                                D ]!\  }}t	          j        |           j        |<   "|#t          j        dt          d           | _        t          j	        d j
         d j         d          }| fd	|D             }n j                                        }|                    d
t          |                    }	|D ]}
|	                    |
j                    j                            |
          }t	          j        | j                  }t+          |                     j
         j                            }                     ||          }|                                }|D                     |
| j                  }|                    t          j        |
|                     |	                                 |S )a  Get the changes needed by this restructuring

        `resources` can be a list of `rope.base.resources.File` to
        apply the restructuring on.  If `None`, the restructuring will
        be applied to all python files.

        `checks` argument has been deprecated.  Use the `args` argument
        of the constructor.  The usage of::

          strchecks = {'obj1.type': 'mod.A', 'obj2': 'mod.B',
                       'obj3.object': 'mod.C'}
          checks = restructuring.make_checks(strchecks)

        can be replaced with::

          args = {'obj1': 'type=mod.A', 'obj2': 'name=mod.B',
                  'obj3': 'object=mod.C'}

        where obj1, obj2 and obj3 are wildcard names that appear
        in restructuring pattern.

        Nz]The use of checks parameter is deprecated; use the args parameter of the constructor instead.   )
stacklevelz^The use of imports parameter is deprecated; use imports parameter of the constructor, instead.zRestructuring <z> to <>c                 H    g | ]}t          j        j        |          |S  )r   is_python_filer   ).0resourcer   s     r   
<listcomp>z+Restructure.get_changes.<locals>.<listcomp>   s>       *4<BB  r   zCollecting Changes)r   )warningswarnDeprecationWarningitemsr
   _pydefined_to_strr   r   r   	ChangeSetr   r   r   get_python_filescreate_jobsetlenstarted_jobpathget_pymoduleSimilarFinderr   listget_matches_compute_changesget_changed_add_imports
add_changeChangeContentsfinished_job)r   checksr   	resourcestask_handlenamevaluechangesfilesjob_setr$   pymodulefindermatchescomputerresultimported_sources   `                r   get_changeszRestructure.get_changes\   s    :  	IME"	     &||~~ I Ie"/"A%"H"H	$ 	#ME"	    #DL"#UT\#U#U#U#U#UVV 	4    )  EE L1133E++,@#e**MM 
	# 
	#H...|00::H"0T^TTTF6--dlDIFFGGG,,Wh??H))++F U"&"3"3Hfdl"S"S""6#8?#S#STTT  """"r   c                 j    t          |j        |                                |j        | j        |          S N)_ChangeComputersource_codeget_astlinesr   )r   rE   rC   s      r   r5   zRestructure._compute_changes   s6     NM
 
 	
r   c                     |s|S |                      ||          }t          j        | j        ||          }t	          j        | j        |          }|D ]}|                    |           |                                S rK   )_get_import_infosr   get_string_moduler   r   ModuleImports
add_importget_changed_source)r   r$   sourcer   import_infosrC   import_infos          r   r7   zRestructure._add_imports   s     	M--h@@-dlFHMM .t|XFF' 	, 	,K{++++))+++r   c                     t          j        | j        d                    |          |          }t	          j        | j        |          }d |j        D             S )N
c                     g | ]	}|j         
S r!   )rX   )r#   r   s     r   r%   z1Restructure._get_import_infos.<locals>.<listcomp>   s    CCC#CCCr   )r   rR   r   joinr   rS   r   )r   r$   r   rC   s       r   rQ   zRestructure._get_import_infos   sU    -L$))G,,h
 
 !.t|XFFCC7?CCCCr   c                     i }|                                 D ]O\  }}|                    d           o|                    d           }|                     ||          }||||<   P|S )zpConvert str to str dicts to str to PyObject dicts

        This function is here to ease writing a UI.

        z.objectz.type)	is_pyname)r)   endswith	_evaluate)r   string_checksr;   keyr?   r^   	evaluateds          r   make_checkszRestructure.make_checks   s|     '--// 	( 	(JCLL333QCLL<Q<Q8QIu	BBI ('sr   Tc                    |                     d          }d }|d         dv r G d d          } |            }n | j                            |d                   }|dd          D ]#}||         }| d S |                                }$|r|n|S )N.r   )__builtin____builtins__c                       e Zd Zd ZdS ),Restructure._evaluate.<locals>._BuiltinsStubc                 &    t           j         |         S rK   )r   )r   r>   s     r   get_attributez:Restructure._evaluate.<locals>._BuiltinsStub.get_attribute   s    #,T22r   N)__name__
__module____qualname__rl   r!   r   r   _BuiltinsStubrj      s#        3 3 3 3 3r   rp      )splitr   
get_module
get_object)r   coder^   
attributespynamerp   pyobject	attributes           r   r`   zRestructure._evaluate   s    ZZ__
a=;; 	>3 3 3 3 3 3 3 3 %}HH|..z!}==H#ABB 	+ 	+Ii(F tt((**HH"0vv0r   )NNN)T)rm   rn   ro   __doc__r   r   DEFAULT_TASK_HANDLErI   r5   r7   rQ   rd   r`   r!   r   r   r   r      s        ? ?B> > > >( 2C C C CJ
 
 
, , ,D D D  1 1 1 1 1 1r   r   c                 @   t          j        |           }t          |                    |                    }t	          j        |           }t          j        |           }t          j        |          }t          | ||||          }|
                                }	|	| S |	S )zused by other refactorings)r
   RawSimilarFinderr3   r4   r	   get_patched_astr   SourceLinesAdapterr   rL   r6   )
ru   r   r   rD   rE   r   rO   r   rF   rG   s
             r   replacer      s    +D11F6%%g..//G

$T
*
*C*400E)$//HtS%7CCH!!##F Mr   c                   :    e Zd Zd Zd Zd Zd Zd
dZd Zd Z	d	S )rL   c                     || _         || _        || _        || _        || _        i | _        i | _        |                                 r| j        D ]}|| j        |j        <   d S d S rK   )rV   r   rE   r   rO   matched_asts_nearest_roots_is_expression)r   ru   r   rO   r   rE   matchs          r   r   z_ChangeComputer.__init__   s    	
    	5 5 5/4!%),,	5 	55 5r   c                    |                                  r)|                     | j                  }|| j        k    rd S |S t	          j        | j                  }d}| j        D ]b}|                                \  }}||k     r|                                  s4|}|                     |          }|	                    |||           c|
                                S )N)r   _get_node_textr   rV   r   ChangeCollectorrE   
get_region_get_matched_textr8   r6   )r   rG   	collectorlast_endr   startendreplacements           r   r6   z_ChangeComputer.get_changed   s       	+((22F$ tM#3DK@@IH > >"--//
s8# !..00 ! "44U;;$$UC====((***r   c                 Z    | j         o$t          | j         d         t          j                  S )Nr   )rE   
isinstancer
   ExpressionMatch)r   s    r   r   z_ChangeComputer._is_expression  s+    | 

LO]:!
 !
 	
r   c                    i }| j                                         D ]h}|                    |          }|t          j        d|z            |                                 o
|j        |k    }|                     ||          ||<   i| j                             |          }| 	                    |
                                d         |          S )NzUnknown name <%s>r   )r   	get_namesrN   r
   BadNameInCheckErrorr   r   r   
substitute_auto_indentr   )r   r   mappingr>   nodeforce
unindenteds          r   r   z!_ChangeComputer._get_matched_text  s    I'')) 	= 	=D==&&D T#78Kd8RSSS''))?ei4.?E //e<<GDMMY))'22
  !1!1!3!3A!6
CCCr   Fc                    |s)|| j         v r |                     | j         |                   S t          j        |          \  }}| j        ||         }t          j        |          }|                     |          D ]I}t          j        |          \  }}|                    ||z
  ||z
  | 	                    |                     J|
                                }	|	|S |	S rK   )r   r   r	   node_regionrV   r   r   _get_nearest_rootsr8   r   r6   )
r   r   r   r   r   	main_textr   	sub_startsub_endrG   s
             r   r   z_ChangeComputer._get_node_text  s     	C!22 	C))$*;D*ABBB+D11
sKc	*	/	::	++D11 	 	D!+!7!=!=Iw  E!7U?D4G4G4M4M    &&(( 	r   c                 v   | j                             |          }t          j        | j         |          }g }t	          |                    d                    D ]L\  }}|dk    r,|                                r|                    d|z             |                    |           Md                    |          S )NTr     )	rO   get_line_numberr   get_indents	enumerate
splitlinesstripappendr\   )r   offsettextlinenoindentsrG   indexlines           r   r   z_ChangeComputer._auto_indent+  s    ++F33)$*f==$T__T%:%:;; 	  	 KE4z -djjll -cGm,,,MM$wwvr   c                    || j         vrjg }t          j        |          D ]I}|| j        v r|                    |           !|                    |                     |                     J|| j         |<   | j         |         S rK   )r   r   iter_child_nodesr   r   extendr   )r   r   rG   childs       r   r   z"_ChangeComputer._get_nearest_roots5  s    t** 	/F-d33 B BD-- BMM%((((MM$"9"9%"@"@AAAA(.D%"4((r   N)F)
rm   rn   ro   r   r6   r   r   r   r   r   r!   r   r   rL   rL      s        
5 
5 
5+ + +&
 
 

	D 	D 	D      	) 	) 	) 	) 	)r   rL   )r&   	rope.baser   r   r   r   r   r   rope.refactorr	   r
   r   rope.refactor.importutilsr   r   r   rL   r!   r   r   <module>r      s     N N N N N N N N N N N N N N N N @ @ @ @ @ @ @ @ @ @ 4 4 4 4 4 4R1 R1 R1 R1 R1 R1 R1 R1j  S) S) S) S) S) S) S) S) S) S)r   