
    Æe,                     z    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y)
    N)astbuiltinschangecodeanalyzelibutils
taskhandle)
patchedastsimilarfindersourceutils)module_importsc                   \    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y)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                        | _        y)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          ;/usr/lib/python3/dist-packages/rope/refactor/restructure.py__init__zRestructure.__init__J   sf     		99DI<<DL"%22499=    c                 @   |Vt        j                  dt        d       |j                         D ]'  \  }}t	        j
                  |      | j                  |<   ) |#t        j                  dt        d       || _        t        j                  d| j                   d| j                   d      }|0|D cg c]$  }t        j                  | j                  |      r|& }	}n| j                  j                         }	|j!                  dt#        |	            }
|	D ]  }|
j%                  |j&                         | j                  j)                  |      }t	        j*                  || j,                  	      }t/        |j1                  | j                  | j                              }| j3                  ||      }|j5                         }|B| j7                  ||| j                        }|j9                  t        j:                  ||             |
j=                           |S c c}w )
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.

        z]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 <>zCollecting Changes)r   )warningswarnDeprecationWarningitemsr
   _pydefined_to_strr   r   r   	ChangeSetr   r   r   is_python_filer   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resourcefilesjob_setpymodulefindermatchescomputerresultimported_sources                    r   get_changeszRestructure.get_changes\   s   : MME"	  &||~ Ie"/"A"A%"H		$IMME"	 #DL""_T\\N&ST#UV  !***4<<B E  LL113E++,@#e*M 
	#H.||00:H"00T^^TF6--dllDIIFGG,,Wh?H))+F!"&"3"3Hfdll"S""6#8#8?#ST  "
	# 's   4)Hc                 x    t        |j                  |j                         |j                  | j                  |      S N)_ChangeComputersource_codeget_astlinesr   )r   rA   r?   s      r   r0   zRestructure._compute_changes   s5      NNMM
 	
r   c                     |s|S | j                  ||      }t        j                  | j                  ||      }t	        j
                  | j                  |      }|D ]  }|j                  |        |j                         S rG   )_get_import_infosr   get_string_moduler   r   ModuleImports
add_importget_changed_source)r   r<   sourcer   import_infosr?   import_infos          r   r2   zRestructure._add_imports   sv    M--h@--dllFHM ..t||XF' 	,K{+	,))++r   c                     t        j                  | j                  dj                  |      |      }t	        j
                  | j                  |      }|j                  D cg c]  }|j                   c}S c c}w )N
)r   rN   r   joinr   rO   r   rT   )r   r<   r   r?   s       r   rM   zRestructure._get_import_infos   s\    --LL$))G,h
 !..t||XF3:??C##CCCs   A5c                     i }|j                         D ]F  \  }}|j                  d       xr |j                  d       }| j                  ||      }|B|||<   H |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_checksr6   keyr:   rY   	evaluateds          r   make_checkszRestructure.make_checks   so     '--/ 	(JCLL33QCLL<Q8QIu	BI$'s		(
 r   c                     |j                  d      }d }|d   dv r G d d      } |       }n| j                  j                  |d         }|dd  D ]  }||   }| y |j                         } |r|S |S )N.r   )__builtin____builtins__c                       e Zd Zd Zy),Restructure._evaluate.<locals>._BuiltinsStubc                 (    t         j                   |   S rG   )r   )r   r9   s     r   get_attributez:Restructure._evaluate.<locals>._BuiltinsStub.get_attribute   s    #,,T22r   N)__name__
__module____qualname__rg    r   r   _BuiltinsStubre      s    3r   rl      )splitr   
get_module
get_object)r   coderY   
attributespynamerl   pyobject	attributes           r   r[   zRestructure._evaluate   s    ZZ_
a=;;3 3 %H||..z!}=H#AB 	+Ii(F~((*H		+
 #v00r   )NNN)T)rh   ri   rj   __doc__r   r   DEFAULT_TASK_HANDLErE   r0   r2   rM   r_   r[   rk   r   r   r   r      sB    ?B>( 22CJ
,D1r   r   c                 (   t        j                  |       }t        |j                  |            }t	        j
                  |       }t        j                  |       }t        j                  |      }t        | ||||      }|j                         }	|	| S |	S )zused by other refactorings)r
   RawSimilarFinderr.   r/   r	   get_patched_astr   SourceLinesAdapterr   rH   r1   )
rq   r   r   r@   rA   r   rK   r   rB   rC   s
             r   replacer|      s    ++D1F6%%g./G

$
$T
*C**40E))$/HtS%7CH!!#F~Mr   c                   8    e Zd Zd Zd Zd Zd Zd	dZd Zd Z	y)
rH   c                     || _         || _        || _        || _        || _        i | _        i | _        | j                         r+| j                  D ]  }|| j
                  |j                  <    y y rG   )rR   r   rA   r   rK   matched_asts_nearest_roots_is_expression)r   rq   r   rK   r   rA   matchs          r   r   z_ChangeComputer.__init__   sm    	
   5/4!!%)),5 !r   c                    | j                         r-| j                  | j                        }|| j                  k(  ry |S t	        j
                  | j                        }d}| j                  D ]Q  }|j                         \  }}||k  r| j                         s,|}| j                  |      }|j                  |||       S |j                         S )N)r   _get_node_textr   rR   r   ChangeCollectorrA   
get_region_get_matched_textr3   r1   )r   rC   	collectorlast_endr   startendreplacements           r   r1   z_ChangeComputer.get_changed   s     ((2F$M#33DKK@IH >"--/
s8#..0 "44U;$$UC=> ((**r   c                 l    | j                   xr' t        | j                   d   t        j                        S )Nr   )rA   
isinstancer
   ExpressionMatch)r   s    r   r   z_ChangeComputer._is_expression  s-    || 

LLO]::!
 	
r   c                    i }| j                   j                         D ]c  }|j                  |      }|t        j                  d|z        | j                         xr |j                  |k(  }| j                  ||      ||<   e | j                   j                  |      }| j                  |j                         d   |      S )NzUnknown name <%s>r   )r   	get_namesrJ   r
   BadNameInCheckErrorr   r   r   
substitute_auto_indentr   )r   r   mappingr9   nodeforce
unindenteds          r   r   z!_ChangeComputer._get_matched_text  s    II'') 	=D==&D|#778Kd8RSS'')?eii4.?E //e<GDM	= YY))'2
  !1!1!3A!6
CCr   c                    |s,|| j                   v r| j                  | j                   |         S t        j                  |      \  }}| j                  || }t        j                  |      }| j                  |      D ]B  }t        j                  |      \  }}|j                  ||z
  ||z
  | j                  |             D |j                         }	|	|S |	S rG   )r   r   r	   node_regionrR   r   r   _get_nearest_rootsr3   r   r1   )
r   r   r   r   r   	main_textr   	sub_startsub_endrC   s
             r   r   z_ChangeComputer._get_node_text  s    !2!22))$*;*;D*ABB++D1
sKKc*	//	:	++D1 	D!+!7!7!=Iw  E!7U?D4G4G4M	
 &&(>r   c                 V   | j                   j                  |      }t        j                  | j                   |      }g }t	        |j                  d            D ]?  \  }}|dk7  r$|j                         r|j                  d|z         |j                  |       A dj                  |      S )NTr     )	rK   get_line_numberr   get_indents	enumerate
splitlinesstripappendrW   )r   offsettextlinenoindentsrC   indexlines           r   r   z_ChangeComputer._auto_indent+  s    ++F3))$**f=$T__T%:; 	 KE4zdjjlcGm,MM$	  wwvr   c                    || j                   vrkg }t        j                  |      D ]B  }|| j                  v r|j	                  |       #|j                  | j                  |             D || j                   |<   | j                   |   S rG   )r   r   iter_child_nodesr   r   extendr   )r   r   rC   childs       r   r   z"_ChangeComputer._get_nearest_roots5  s    t***F--d3 BD---MM%(MM$"9"9%"@A	B
 )/D%""4((r   N)F)
rh   ri   rj   r   r1   r   r   r   r   r   rk   r   r   rH   rH      s&    
5+&

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