o bcFm@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_reprspygramr__dict__itemstypeint setdefault)type_numrnamevalr%/usr/lib/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. NrFcO|tusJdt|S)z7Constructor that prevents Base from being instantiated.zCannot instantiate Base)robject__new__clsargskwdsrrrr1 z Base.__new__cCs|j|jurtS||S)zW Compare two nodes for equality. This calls the method _eq(). ) __class__NotImplemented_eqselfotherrrr__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. NotImplementedErrorrrrrrBs zBase._eqcCr")zr Return a cloned (deep) copy of self. This must be implemented by the concrete subclass. r#rrrrcloneMz Base.clonecCr")zx Return a post-order iterator for the tree. This must be implemented by the concrete subclass. r#r%rrr post_orderUr'zBase.post_ordercCr")zw Return a pre-order iterator for the tree. This must be implemented by the concrete subclass. r#r%rrr 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)rnew l_childrenfoundchxrrrreplacees&        z Base.replacecCs2|}t|ts|js dS|jd}t|tr|jS)z9Return the line number which generated the invocant node.Nr)r,Leafr.linenornoderrr get_lineno|s   zBase.get_linenocCs|jr|jd|_dS)NT)r*r1 was_changedr%rrrr1s  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.r1)rir;rrrremoves  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?childrrr 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.rBrrr prev_siblings zBase.prev_siblingccs |jD] }|EdHqdSN)r.leavesrrCrrrrGs z Base.leavescCs|jdurdSd|jS)Nrr)r*depthr%rrrrIs 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)rDprefix)rnext_sibrrr get_suffixszBase.get_suffixrcCst|dS)Nascii)r+encoder%rrr__str__sz Base.__str__)__name__ __module__ __qualname____doc__r r*r.r= was_checkedrr!__hash__rr&r(r)r7r<r1r@propertyrDrErGrIrMsys version_inforRrrrrrs8       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)r r-r.r*reprrKfixers_applied)rr r.contextrKr_r5rrr__init__s    z Node.__init__cCsd|jjt|j|jfS))Return a canonical string representation.z %s(%s, %r))rrSrr r.r%rrr__repr__sz Node.__repr__cCsdtt|jS)k Return a pretty string representation. This reproduces the input source exactly. rJ)joinmapr+r.r%rrr __unicode__szNode.__unicode__rNcC|j|jf|j|jfkSzCompare two nodes for equality.)r r.rrrrrzNode._eqcCst|jdd|jD|jdS)$Return a cloned (deep) copy of self.cSsg|]}|qSr)r&).0r5rrr szNode.clone..r_)r\r r.r_r%rrrr&sz Node.cloneccs&|jD] }|EdHq|VdSz*Return a post-order iterator for the tree.N)r.r(rHrrrr(s  zNode.post_orderccs&|V|jD] }|EdHqdSz)Return a pre-order iterator for the tree.N)r.r)rHrrrr) s  zNode.pre_ordercCs|jsdS|jdjS)zO The whitespace and comments preceding this node in the input. rJrr.rKr%rrrrKs z Node.prefixcCs|jr ||jd_dSdSNrrqrrKrrrrKscCs(||_d|j|_||j|<|dS)z Equivalent to 'node.children[i] = child'. This method also sets the child's parent attribute appropriately. N)r*r.r1rBrrr 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.insertr1rBrrr 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.r0r1rHrrr append_child3s  zNode.append_childNNN)rSrTrUrVrarcrgrZr[rRrr&r(r)rYrKsetterrtrvrwrrrrr\s*     r\c@seZdZdZdZdZdZddgfddZddZd d Z e j d kr#e Z d d Z ddZddZddZddZeddZejddZdS)r8z'Concrete implementation for leaf nodes.rJrNcCsjd|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. rr]N)_prefixr9columnr valuer_)rr r|r`rKr_rrrraFs$ z Leaf.__init__cCsd|jj|j|jfS)rbz %s(%r, %r))rrSr r|r%rrrrcYsz Leaf.__repr__cCs|jt|jS)rd)rKr+r|r%rrrrg_szLeaf.__unicode__rNcCrhri)r r|rrrrrjrjzLeaf._eqcCs$t|j|j|j|j|jff|jdS)rkrn)r8r r|rKr9r{r_r%rrrr&ns z Leaf.cloneccs |VdSrFrr%rrrrGts z Leaf.leavescc |VdSrorr%rrrr(w zLeaf.post_orderccr}rprr%rrrr){r~zLeaf.pre_ordercCs|jS)zP The whitespace and comments preceding this token in the input. )rzr%rrrrKsz Leaf.prefixcCs|||_dSrF)r1rzrsrrrrKs )rSrTrUrVrzr9r{rarcrgrZr[rRrr&rGr(r)rYrKryrrrrr8=s,   r8cCsJ|\}}}}|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`) number2symbollenr\r8)grraw_noder r|r`r.rrrconverts  rc@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)rrrrrrrrrzBasePattern.__new__cCsVt|j|j|jg}|r|ddur|d=|r|ddusd|jjdtt|fS)Nz%s(%s)z, ) rr contentr rrSrerfr^)rrrrrrcs 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. rr%rrroptimizer'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)r r _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)rr)rnodesrrrr 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)rrrrrrgenerate_matchess zBasePattern.generate_matchesrF) rSrTrUrVr rr rrcrrrrrrrrrs   rc@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. Nrr])r,r+r^r rr )rr rr rrrras $ zLeafPattern.__init__cCst|tsdSt|||S)z*Override match() to insist on a leaf node.F)r,r8rrrr;rrrrr 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. )rr|rrrrrs zLeafPattern._submatchrxrF)rSrTrUrarrrrrrrs  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. Nr]T) r,r+r^r-r>rWildcardPattern wildcardsr rr )rr rr r?itemrrrra$s  zNodePattern.__init__cCs|jr$t|j|jD]\}}|t|jkr!|dur||dSq dSt|jt|jkr0dSt|j|jD] \}}|||sDdSq7dS)rNTF)rrrr.rrzipr)rr;rcr subpatternrCrrrrAs   zNodePattern._submatchrxrF)rSrTrUrrarrrrrr 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) HUGEtuplerfrr^rminmaxr )rrrrr altrrrraks, 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 ) rrrrrr rr,r)rrrrrrs"      zWildcardPattern.optimizecCs||g|S)z'Does this pattern exactly match a node?)rrrrrrszWildcardPattern.matchcCsP||D] \}}|t|kr%|dur"|||jr"t|||j<dSqdS)z4Does this pattern exactly match a sequence of nodes?NTF)rrrr r-)rrrrrrrrrs  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. Nr bare_name getrefcountr)rrangerrrr _bare_name_matcheshasattrrZstderrr_recursive_matches RuntimeError_iterative_matches)rrcountr save_stderrrrrrs>         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)rrrrr0rr) rrnodelenrrrr new_resultsc0r0c1r1rrrrs6         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)rrrr )rrrrdonerleafrrrrs   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)rrrrrr) rrrrrrrrrrrrr s        z"WildcardPattern._recursive_matchesrF) rSrTrUrVrrarrrrrrrrrrrr]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,rr^r)rrrrrras  zNegatedPattern.__init__cCsdS)NFrr:rrrr(szNegatedPattern.matchcCs t|dkSrr)r)rrrrrr,s zNegatedPattern.match_seqccsR|jdurt|dkrdifVdSdS|j|D]\}}dSdifVdSrr)rrr)rrrrrrrr0s  zNegatedPattern.generate_matchesrF)rSrTrUrarrrrrrrrs    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) patternsrprestrrrrrrrrr<s    r)rV __author__rZiorrrrrrr\r8rrrrrrrrrrrs&   1nNV,== #