o ?OgFm@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)StringIOicCsDtsddlm}|jD]\}}t|tkr|t|<q t||S)N)python_symbols) _type_reprsZpygramr__dict__itemstypeint setdefault)Ztype_numrnamevalr 5/opt/alt/python310/lib64/python3.10/lib2to3/pytree.py type_reprs   rc@seZdZdZdZdZdZdZdZddZ ddZ dZ d d Z d d Z d dZddZddZddZddZddZeddZeddZddZdd Zd!d"Zejd#kr]d$d%ZdSdS)&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. Nr FcO|tusJdt|S)z7Constructor that prevents Base from being instantiated.zCannot instantiate Base)robject__new__clsargskwdsr r rr1 z Base.__new__cCs|j|jurtS||S)zW Compare two nodes for equality. This calls the method _eq(). ) __class__NotImplemented_eqselfotherr r r__eq__6s  z Base.__eq__cCt)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. NotImplementedErrorrr r rrBs zBase._eqcCr )zr Return a cloned (deep) copy of self. This must be implemented by the concrete subclass. r!rr r rcloneMz Base.clonecCr )zx Return a post-order iterator for the tree. This must be implemented by the concrete subclass. r!r#r r r post_orderUr%zBase.post_ordercCr )zw Return a pre-order iterator for the tree. This must be implemented by the concrete subclass. r!r#r r r pre_order]r%zBase.pre_ordercCs|jdus Jt||dusJt|ts|g}g}d}|jjD]"}||ur>|r2J|jj||f|dur;||d}q!||q!|sNJ|j||f|j||j_|D]}|j|_qYd|_dS)z/Replace this node with a new one in the parent.NFT)parentstr isinstancelistchildrenextendappendchanged)rnewZ l_childrenfoundchxr r rreplacees&        z Base.replacecCs2|}t|ts|js dS|jd}t|tr|jS)z9Return the line number which generated the invocant node.Nr)r*Leafr,linenornoder r r get_lineno|s   zBase.get_linenocCs|jr|jd|_dS)NT)r(r/ was_changedr#r r rr/s  z Base.changedcCsN|jr#t|jjD]\}}||ur"|j|jj|=d|_|Sq dSdS)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/)rir8r r rremoves  z Base.removec Cs^|jdurdSt|jjD]\}}||ur,z |jj|dWSty+YdSwq dS)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)r(r;r, IndexErrorrr<childr r r next_siblings  zBase.next_siblingcCsR|jdurdSt|jjD]\}}||ur&|dkrdS|jj|dSq dS)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)r(r;r,r?r r r prev_siblings zBase.prev_siblingccs |jD] }|EdHqdSN)r,leavesrr@r r rrDs z Base.leavescCs|jdurdSd|jS)Nrr)r(depthr#r r rrFs z Base.depthcCs|j}|dur dS|jS)z Return the string immediately following the invocant node. This is effectively equivalent to node.next_sibling.prefix N)rAprefix)rZnext_sibr r r get_suffixszBase.get_suffixrcCst|dS)Nascii)r)encoder#r r r__str__sz Base.__str__)__name__ __module__ __qualname____doc__rr(r,r:Z was_checkedrr__hash__rr$r&r'r4r9r/r=propertyrArBrDrFrIsys version_inforNr r r rrs8       rc@seZdZdZ   dddZddZddZejd kreZ d d Z d d Z ddZ ddZ eddZejddZddZddZddZdS)Nodez+Concrete implementation for interior nodes.NcCsv|dksJ|||_t||_|jD]}|jdus Jt|||_q|dur+||_|r6|dd|_dSd|_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,r(reprrHfixers_applied)rrr,contextrHrZr2r r r__init__s    z Node.__init__cCsd|jjt|j|jfS))Return a canonical string representation.z %s(%s, %r))rrOrrr,r#r r r__repr__sz Node.__repr__cCsdtt|jS)k Return a pretty string representation. This reproduces the input source exactly. rG)joinmapr)r,r#r r r __unicode__szNode.__unicode__rJcC|j|jf|j|jfkSzCompare two nodes for equality.)rr,rr r rrzNode._eqcCst|jdd|jD|jdS)$Return a cloned (deep) copy of self.cSsg|]}|qSr )r$).0r2r r r szNode.clone..rZ)rWrr,rZr#r r rr$sz Node.cloneccs&|jD] }|EdHq|VdSz*Return a post-order iterator for the tree.N)r,r&rEr r rr&s  zNode.post_orderccs&|V|jD] }|EdHqdSz)Return a pre-order iterator for the tree.N)r,r'rEr r rr' s  zNode.pre_ordercCs|jsdS|jdjS)zO The whitespace and comments preceding this node in the input. rGrr,rHr#r r rrHs z Node.prefixcCs|jr ||jd_dSdSNrrlrrHr r rrHscCs(||_d|j|_||j|<|dS)z Equivalent to 'node.children[i] = child'. This method also sets the child's parent attribute appropriately. N)r(r,r/r?r r r 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)r(r,insertr/r?r r r insert_child*s zNode.insert_childcCs||_|j||dS)z Equivalent to 'node.children.append(child)'. This method also sets the child's parent attribute appropriately. N)r(r,r.r/rEr r r append_child3s  zNode.append_childNNN)rOrPrQrRr\r^rbrUrVrNrr$r&r'rTrHsetterrorqrrr r r rrWs*     rWc@seZdZdZdZdZdZddgfddZddZd d Z e j d kr#e Z d d Z ddZddZddZddZeddZejddZdS)r5z'Concrete implementation for leaf nodes.rGrNcCsjd|kr dksJ|J||dur|\|_\|_|_||_||_|dur,||_|dd|_dS)z Initializer. Takes a type constant (a token number < 256), a string value, and an optional context keyword argument. rrXN)_prefixr6columnrvaluerZ)rrrwr[rHrZr r rr\Fs$ z Leaf.__init__cCsd|jj|j|jfS)r]z %s(%r, %r))rrOrrwr#r r rr^Ysz Leaf.__repr__cCs|jt|jS)r_)rHr)rwr#r r rrb_szLeaf.__unicode__rJcCrcrd)rrwrr r rrjrezLeaf._eqcCs$t|j|j|j|j|jff|jdS)rfri)r5rrwrHr6rvrZr#r r rr$ns z Leaf.cloneccs |VdSrCr r#r r rrDts z Leaf.leavescc |VdSrjr r#r r rr&w zLeaf.post_orderccrxrkr r#r r rr'{ryzLeaf.pre_ordercCs|jS)zP The whitespace and comments preceding this token in the input. )rur#r r rrHsz Leaf.prefixcCs|||_dSrC)r/rurnr r rrHs )rOrPrQrRrur6rvr\r^rbrUrVrNrr$rDr&r'rTrHrtr r r rr5=s,   r5cCsJ|\}}}}|s ||jvrt|dkr|dSt|||dSt|||dS)z Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build strictly bottom-up. rr)r[)Z number2symbollenrWr5)ZgrZraw_noderrwr[r,r r rconverts  r{c@sPeZdZdZdZdZdZddZddZddZ dd d Z dd d Z d dZ dS) BasePatterna A pattern is a tree matching pattern. It looks for a specific node type (token or symbol), and optionally for a specific content. This is an abstract base class. There are three concrete subclasses: - LeafPattern matches a single leaf node; - NodePattern matches a single node (usually non-leaf); - WildcardPattern matches a sequence of nodes of variable length. NcOr)z>Constructor that prevents BasePattern from being instantiated.zCannot instantiate BasePattern)r|rrrr r rrrzBasePattern.__new__cCsVt|j|j|jg}|r|ddur|d=|r|ddusd|jjdtt|fS)Nz%s(%s)z, ) rrcontentr rrOr`rarY)rrr r rr^s zBasePattern.__repr__cCs|S)z A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect. r r#r r roptimizer%zBasePattern.optimizecCsn|jdur |j|jkr dS|jdur)d}|duri}|||s"dS|r)|||dur5|jr5|||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)rr~ _submatchupdater )rr8resultsrr r rmatchs     zBasePattern.matchcCs t|dkrdS||d|S)z Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns. rFr)rzr)rnodesrr r r match_seqs zBasePattern.match_seqccs0i}|r||d|rd|fVdSdSdS)z} Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. rrN)r)rrrr r rgenerate_matchess zBasePattern.generate_matchesrC) rOrPrQrRrr~r rr^rrrrr r r rr|s   r|c@s*eZdZdddZd ddZd ddZdS) LeafPatternNcCs`|durd|krdksJ|J||dur%t|ts%Jt|||_||_||_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. NrrX)r*r)rYrr~r )rrr~r r r rr\s $ zLeafPattern.__init__cCst|tsdSt|||S)z*Override match() to insist on a leaf node.F)r*r5r|rrr8rr r rr 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. )r~rwrr r rrs zLeafPattern._submatchrsrC)rOrPrQr\rrr r r rrs  rc@s$eZdZdZdddZdddZdS) NodePatternFNcCs|dur |dks J||dur;t|trJt|t|}t|D]\}}t|ts2J||ft|tr:d|_q#||_||_ ||_ 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. NrXT) r*r)rYr+r;r|WildcardPattern wildcardsrr~r )rrr~r r<itemr r rr\$s  zNodePattern.__init__cCs|jr$t|j|jD]\}}|t|jkr!|dur||dSq dSt|jt|jkr0dSt|j|jD] \}}|||sDdSq7dS)rNTF)rrr~r,rzrzipr)rr8rcr subpatternr@r r rrAs   zNodePattern._submatchrsrC)rOrPrQrr\rr r r rr s rc@s^eZdZdZddedfddZddZddd Zdd d Zd d Z ddZ ddZ ddZ dS)ra 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|krtksnJ||f|dur:ttt|}t|s+Jt||D] }t|s9Jt|q-||_||_||_||_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) HUGEtuplerarzrYr~minmaxr )rr~rrr altr r rr\ks, zWildcardPattern.__init__cCsd}|jdurt|jdkrt|jddkr|jdd}|jdkrA|jdkrA|jdur3t|jdS|durA|j|jkrA|S|jdkrgt|trg|jdkrg|j|jkrgt|j|j|j|j|j|jS|S)z+Optimize certain stacked wildcard patterns.Nrr)r ) r~rzrrrr rr*r)rrr r rrs"      zWildcardPattern.optimizecCs||g|S)z'Does this pattern exactly match a node?)rrr r rrszWildcardPattern.matchcCsP||D] \}}|t|kr%|dur"|||jr"t|||j<dSqdS)z4Does this pattern exactly match a sequence of nodes?NTF)rrzrr r+)rrrrrr r rrs  zWildcardPattern.match_seqc cs>|jdur,t|jdtt||jD]}i}|jr$|d|||j<||fVqdS|jdkr9||VdSttdrEtj }t t_ zPz| |dD]\}}|jr]|d|||j<||fVqMWn$t y| |D]\}}|jr|d|||j<||fVqpYnwWttdr|t_ dSdSttdr|t_ w)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_name getrefcountr)r~rangerrzrr _bare_name_matcheshasattrrUstderrr_recursive_matches RuntimeError_iterative_matches)rrcountrZ save_stderrr r rrs>         z WildcardPattern.generate_matchesc cst|}d|jkrdifVg}|jD]}t||D]\}}||fV|||fqq|r{g}|D]A\}} ||krt||jkrt|jD]0}t|||dD]$\} } | dkrri}|| || || |fV||| |fqNqCq3|}|s/dSdS)z(Helper to iteratively yield the matches.rN)rzrr~rr.rr) rrZnodelenrrrrZ new_resultsc0r0c1r1r r rrs6         z"WildcardPattern._iterative_matchescCszd}i}d}t|}|s0||kr0d}|jD]}|d|||r)|d7}d}nq|s0||ks|d|||j<||fS)z(Special optimized matcher for bare_name.rFTrN)rzr~rr )rrrrZdonerZleafr r rrs   z"WildcardPattern._bare_name_matchesc cs|jdusJ||jkrdifV||jkrK|jD]2}t||D](\}}|||d|dD]\}}i}|||||||fVq1q!qdSdS)z(Helper to recursively yield the matches.Nrr)r~rrrrr) rrrrrrrrrr r rr s        z"WildcardPattern._recursive_matchesrC) rOrPrQrRrr\rrrrrrrr r r rr]s #   - rc@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*r|rYr~)rr~r r rr\s  zNegatedPattern.__init__cCsdS)NFr r7r r rr(szNegatedPattern.matchcCs t|dkSrm)rz)rrr r rr,s zNegatedPattern.match_seqccsR|jdurt|dkrdifVdSdS|j|D]\}}dSdifVdSrm)r~rzr)rrrrr r rr0s  zNegatedPattern.generate_matchesrC)rOrPrQr\rrrr r r rrs    rc cs|s difVdS|d|dd}}||D]-\}}|s&||fVqt|||dD]\}}i}|||||||fVq/qdS)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)rr) patternsrprestrrrrrr r rr<s    r)rR __author__rUiorrrrrrrWr5r{r|rrrrrr r r rs&   1nNV,== #