f _8mc@sdZdZddlZddlmZdZiaddZGdd d eZ Gd d d e Z Gd d d e Z ddZ GdddeZ Gddde ZGddde ZGddde ZGddde ZddZdS)z Python parse tree definitions. This is a very concrete parse tree; we need to keep every token and even the comments and whitespace between tokens. There's also a pattern matching implementation here. z#Guido van Rossum N)StringIOicCsDts8ddlm}|jD]\}}t|tkr|t|<qt||S)N)python_symbols) _type_reprsZpygramrZ__dict__ZitemstypeZintZ setdefault)Ztype_numrnameZvalr'/usr/lib64/python3.10/lib2to3/pytree.py type_reprs  r c@seZdZdZdZdZdZdZdZddZ ddZ dZ d d Z d d Z d dZddZddZddZddZddZeddZeddZddZdd Zd!d"Zejd#krd$d%ZdS)&Basez Abstract base class for Node and Leaf. This provides some default functionality and boilerplate using the template pattern. A node may be a subnode of at most one parent. NrFcO|tusJdt|S)z7Constructor that prevents Base from being instantiated.zCannot instantiate Base)r object__new__ZclsargsZkwdsrrrr 1z Base.__new__cCs|j|jurtS||S)zW Compare two nodes for equality. This calls the method _eq(). ) __class__ZNotImplemented_eqselfZotherrrr__eq__6 z Base.__eq__cCtdS)a_ Compare two nodes for equality. This is called by __eq__ and __ne__. It is only called if the two nodes have the same type. This must be implemented by the concrete subclass. Nodes should be considered equal if they have the same structure, ignoring the prefix string and other context information. NZNotImplementedErrorrrrrrBs zBase._eqcCr)zr Return a cloned (deep) copy of self. This must be implemented by the concrete subclass. NrrrrrcloneMz Base.clonecCr)zx Return a post-order iterator for the tree. This must be implemented by the concrete subclass. Nrrrrr post_orderUrzBase.post_ordercCr)zw Return a pre-order iterator for the tree. This must be implemented by the concrete subclass. Nrrrrr pre_order]rzBase.pre_ordercCs|jdusJt||dus"Jt|ts2|g}g}d}|jjD]D}||ur||rdJ|jj||f|durv||d}qB||qB|sJ|j||f|j||j_|D] }|j|_qd|_dS)z/Replace this node with a new one in the parent.NFT)parentstr isinstancelistchildrenZextendappendchanged)rZnewZ l_childrenZfoundchZxrrrreplacees&       z Base.replacecCs*|}t|ts$|jsdS|jd}q|jS)z9Return the line number which generated the invocant node.Nr)r Leafr"linenornoderrr get_lineno|s   zBase.get_linenocCs|jr|jd|_dS)NT)rr$ was_changedrrrrr$s z Base.changedcCsH|jrDt|jjD]0\}}||ur|j|jj|=d|_|SdS)z Remove the node from the tree. Returns the position of the node in its parent's children before it was removed. N)r enumerater"r$)rir*rrrremoves  z Base.removec Cs\|jdurdSt|jjD]<\}}||urz|jj|dWStyVYdS0dS)z The node immediately following the invocant in their parent's children list. If the invocant does not have a next sibling, it is None Nr)rr-r"Z IndexErrorrr.childrrr next_siblings  zBase.next_siblingcCsP|jdurdSt|jjD]0\}}||ur|dkr8dS|jj|dSdS)z The node immediately preceding the invocant in their parent's children list. If the invocant does not have a previous sibling, it is None. Nrr)rr-r"r0rrr prev_siblings zBase.prev_siblingccs|jD]}|EdHqdSN)r"leavesrr1rrrr5s z Base.leavescCs|jdurdSd|jS)Nrr)rdepthrrrrr7s z Base.depthcCs|j}|durdS|jS)z Return the string immediately following the invocant node. This is effectively equivalent to node.next_sibling.prefix N)r2prefix)rZnext_sibrrr get_suffixszBase.get_suffixircCst|dS)NZascii)rZencoderrrr__str__z Base.__str__)__name__ __module__ __qualname____doc__rrr"r,Z was_checkedr rZ__hash__rrrrr&r+r$r/propertyr2r3r5r7r:sys version_infor<rrrrr s4        r c@seZdZdZdddZddZddZejd kr4eZ d d Z d d Z ddZ ddZ eddZejddZddZddZddZdS)Nodez+Concrete implementation for interior nodes.NcCst|dksJ|||_t||_|jD] }|jdus@Jt|||_q&|durV||_|rj|dd|_nd|_dS)z Initializer. Takes a type constant (a symbol number >= 256), a sequence of child nodes, and an optional context keyword argument. As a side effect, the parent pointers of the children are updated. N)rr!r"rreprr9fixers_applied)rrr"contextr9rHr%rrr__init__s   z Node.__init__cCsd|jjt|j|jfS))Return a canonical string representation.z %s(%s, %r))rr>r rr"rrrr__repr__sz Node.__repr__cCsdtt|jS)k Return a pretty string representation. This reproduces the input source exactly. r8)joinmaprr"rrrr __unicode__rzNode.__unicode__r;cC|j|jf|j|jfkSzCompare two nodes for equality.)rr"rrrrrzNode._eqcCst|jdd|jD|jdS)$Return a cloned (deep) copy of self.cSsg|] }|qSr)r)Z.0r%rrrZ szNode.clone..rH)rErr"rHrrrrrsz Node.cloneccs$|jD]}|EdHq|VdSz*Return a post-order iterator for the tree.N)r"rr6rrrrs zNode.post_orderccs$|V|jD]}|EdHq dSz)Return a pre-order iterator for the tree.N)r"rr6rrrr s zNode.pre_ordercCs|js dS|jdjS)zO The whitespace and comments preceding this node in the input. r8rr"r9rrrrr9sz Node.prefixcCs|jr||jd_dSNrrXrr9rrrr9scCs(||_d|j|_||j|<|dS)z Equivalent to 'node.children[i] = child'. This method also sets the child's parent attribute appropriately. N)rr"r$r0rrr set_child s  zNode.set_childcCs ||_|j|||dS)z Equivalent to 'node.children.insert(i, child)'. This method also sets the child's parent attribute appropriately. N)rr"Zinsertr$r0rrr insert_child*szNode.insert_childcCs||_|j||dS)z Equivalent to 'node.children.append(child)'. This method also sets the child's parent attribute appropriately. N)rr"r#r$r6rrr append_child3s zNode.append_childNNN)r>r?r@rArJrLrPrCrDr<rrrrrBr9setterr[r\r]rrrrrEs"      rEc@seZdZdZdZdZdZddgfddZddZd d Z e j d krFe Z d d Z ddZddZddZddZeddZejddZdS)r'z'Concrete implementation for leaf nodes.r8rNcCsdd|krdksnJ||dur8|\|_\|_|_||_||_|durR||_|dd|_dS)z Initializer. Takes a type constant (a token number < 256), a string value, and an optional context keyword argument. rrFN)_prefixr(columnrvaluerH)rrrbrIr9rHrrrrJFs z Leaf.__init__cCsd|jj|j|jfS)rKz %s(%r, %r))rr>rrbrrrrrLYsz Leaf.__repr__cCs|jt|jS)rM)r9rrbrrrrrP_rzLeaf.__unicode__r;cCrQrR)rrbrrrrrjrSzLeaf._eqcCs$t|j|j|j|j|jff|jdS)rTrU)r'rrbr9r(rarHrrrrrns z Leaf.cloneccs |VdSr4rrrrrr5tr=z Leaf.leavescc |VdSrVrrrrrrwrSzLeaf.post_orderccrcrWrrrrrr{rSzLeaf.pre_ordercCs|jS)zP The whitespace and comments preceding this token in the input. )r`rrrrr9sz Leaf.prefixcCs|||_dSr4)r$r`rZrrrr9s)r>r?r@rAr`r(rarJrLrPrCrDr<rrr5rrrBr9r_rrrrr'=s*   r'cCsJ|\}}}}|s||jvrConstructor that prevents BasePattern from being instantiated.zCannot instantiate BasePattern)rfr r rrrrr rzBasePattern.__new__cCsHt|j|j|jg}|r,|ddur,|d=qd|jjdtt|fS)Niz%s(%s)z, ) r rcontentrrr>rNrOrG)rrrrrrLszBasePattern.__repr__cCs|S)z A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect. rrrrroptimizerzBasePattern.optimizecCsn|jdur|j|jkrdS|jdurRd}|dur4i}|||sDdS|rR|||durj|jrj|||j<dS)a# Does this pattern exactly match a node? Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. Default implementation for non-wildcard patterns. NFT)rrg _submatchupdater)rr*resultsrrrrmatchs     zBasePattern.matchcCs t|dkrdS||d|S)z Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns. rFr)rdrm)rnodesrkrrr match_seqrzBasePattern.match_seqccs&i}|r"||d|r"d|fVdS)z} Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. rrN)rm)rrnrlrrrgenerate_matchesszBasePattern.generate_matchesr4r4) r>r?r@rArrgrr rLrhrmrorprrrrrfs  rfc@s*eZdZdddZd ddZd ddZdS) LeafPatternNcCsZ|dur&d|krdks&nJ||durDt|tsDJt|||_||_||_dS)ap Initializer. Takes optional type, content, and name. The type, if given must be a token type (< 256). If not given, this matches any *leaf* node; the content may still be required. The content, if given, must be a string. If a name is given, the matching node is stored in the results dict under that key. NrrF)r rrGrrgr)rrrgrrrrrJs zLeafPattern.__init__cCst|tsdSt|||S)z*Override match() to insist on a leaf node.F)r r'rfrmrr*rkrrrrm s zLeafPattern.matchcCs |j|jkS) Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated. )rgrbrrrrrris zLeafPattern._submatchr^r4r4)r>r?r@rJrmrirrrrrqs  rqc@s$eZdZdZdddZdddZdS) NodePatternFNcCs|dur|dksJ||durvt|tr6Jt|t|}t|D].\}}t|tsdJ||ft|trFd|_qF||_||_ ||_ dS)ad Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), except if content is not None, in which it only matches non-leaf nodes that also match the content pattern. The content, if not None, must be a sequence of Patterns that must match the node's children exactly. If the content is given, the type must not be None. If a name is given, the matching node is stored in the results dict under that key. NrFT) r rrGr!r-rfWildcardPattern wildcardsrrgr)rrrgrr.ZitemrrrrJ$s zNodePattern.__init__cCs|jrFt|j|jD],\}}|t|jkr|dur<||dSdSt|jt|jkr^dSt|j|jD]\}}|||sldSdS)rsNTF)rvrprgr"rdrjZziprm)rr*rkcrl subpatternr1rrrriAs   zNodePattern._submatchr^r4)r>r?r@rvrJrirrrrrt s rtc@s^eZdZdZddedfddZddZddd Zdd d Zd d Z ddZ ddZ ddZ dS)rua A wildcard pattern can match zero or more nodes. This has all the flexibility needed to implement patterns like: .* .+ .? .{m,n} (a b c | d e | f) (...)* (...)+ (...)? (...){m,n} except it always uses non-greedy matching. NrcCsd|kr|krtks,nJ||f|durtttt|}t|sVJt||D]}t|sZJt|qZ||_||_||_||_dS)a Initializer. Args: content: optional sequence of subsequences of patterns; if absent, matches one node; if present, each subsequence is an alternative [*] min: optional minimum number of times to match, default 0 max: optional maximum number of times to match, default HUGE name: optional name assigned to this match [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is equivalent to (a b c | d e | f g h); if content is None, this is equivalent to '.' in regular expression terms. The min and max parameters work as follows: min=0, max=maxint: .* min=1, max=maxint: .+ min=0, max=1: .? min=1, max=1: . If content is not None, replace the dot with the parenthesized list of alternatives, e.g. (a b c | d e | f g h)* rN) HUGEZtuplerOrdrGrgminmaxr)rrgrzr{raltrrrrJks,zWildcardPattern.__init__cCsd}|jdur\}}|t|kr |durD|||jrDt|||j<dSdS)z4Does this pattern exactly match a sequence of nodes?NTF)rprdrjrr!)rrnrkrwrlrrrros  zWildcardPattern.match_seqc cs<|jdurTt|jdtt||jD]*}i}|jrF|d|||j<||fVq&n|jdkrl||Vnttdrtj }t t_ zz<| |dD]*\}}|jr|d|||j<||fVqWnJt y | |D]*\}}|jr|d|||j<||fVqYn0Wttdr8|t_ nttdr6|t_ 0dS)a" Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches. NrZ bare_nameZ getrefcountr)rgZrangerzrdr{r_bare_name_matchesZhasattrrCZstderrr_recursive_matchesZ RuntimeError_iterative_matches)rrncountrlZ save_stderrrrrrps2      z WildcardPattern.generate_matchesc cst|}d|jkrdifVg}|jD]0}t||D] \}}||fV|||fq4q&|rg}|D]\}} ||krd||jkrd|jD]`}t|||dD]H\} } | dkri}|| || || |fV||| |fqqqd|}qXdS)z(Helper to iteratively yield the matches.rN)rdrzrgrpr#r{rj) rrnZnodelenrkr|rwrlZ new_resultsc0r0c1r1rrrrs*        z"WildcardPattern._iterative_matchescCspd}i}d}t|}|sV||krVd}|jD](}|d|||r*|d7}d}qq*q|d|||j<||fS)z(Special optimized matcher for bare_name.rFTrN)rdrgrmr)rrnrrlZdoner{Zleafrrrr}s  z"WildcardPattern._bare_name_matchesc cs|jdusJ||jkr"difV||jkr|jD]`}t||D]P\}}|||d|dD].\}}i}|||||||fVq`q@q2dS)z(Helper to recursively yield the matches.Nrr)rgrzr{rpr~rj) rrnrr|rrrrrlrrrr~ s       z"WildcardPattern._recursive_matchesr4r4) r>r?r@rAryrJrhrmrorprr}r~rrrrru]s #  -ruc@s.eZdZd ddZddZddZdd ZdS) NegatedPatternNcCs(|durt|tsJt|||_dS)a Initializer. The argument is either a pattern or None. If it is None, this only matches an empty sequence (effectively '$' in regex lingo). If it is not None, this matches whenever the argument pattern doesn't have any matches. N)r rfrGrg)rrgrrrrJs zNegatedPattern.__init__cCsdS)NFrr)rrrrm(rSzNegatedPattern.matchcCs t|dkSrY)rd)rrnrrrro,rSzNegatedPattern.match_seqccsJ|jdur"t|dkrFdifVn$|j|D] \}}dSdifVdSrY)rgrdrp)rrnrwrlrrrrp0s    zNegatedPattern.generate_matchesr4)r>r?r@rJrmrorprrrrrs rc cs|sdifVn||d|dd}}||D]Z\}}|sH||fVq0t|||dD].\}}i}|||||||fVqZq0dS)aR Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches. rrN)rprj) ZpatternsrnZpZrestrrrrrlrrrrp<s     rp)rAZ __author__rCZiorryrr r r rEr'rerfrqrtrurrprrrrZs$   1nNV,==#