gFmdZdZddlZddlmZdZiadZGddeZ Gd d e Z Gd d e Z d Z GddeZ Gdde ZGdde ZGdde ZGdde ZdZy)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)StringIOictsDddlm}|jj D]!\}}t |t k(s|t|<#tj||S)N)python_symbols) _type_reprspygramr__dict__itemstypeint setdefault)type_numrnamevals 5/opt/alt/python312/lib64/python3.12/lib2to3/pytree.py type_reprrsO *(00668ID#CyCDS!19  ! !(H 55ceZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZdZedZedZdZdZdZej6dkrdZyy)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. NFc,tj|S)z7Constructor that prevents Base from being instantiated.object__new__clsargskwdss rrz Base.__new__1~~c""rc`|j|jurtS|j|S)zW Compare two nodes for equality. This calls the method _eq(). ) __class__NotImplemented_eqselfothers r__eq__z Base.__eq__6s( >> 0! !xxrct)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. NotImplementedErrorr$s rr#zBase._eqBs "!rct)zr Return a cloned (deep) copy of self. This must be implemented by the concrete subclass. r)r%s rclonez Base.cloneM "!rct)zx Return a post-order iterator for the tree. This must be implemented by the concrete subclass. r)r,s r post_orderzBase.post_orderUr.rct)zw Return a pre-order iterator for the tree. This must be implemented by the concrete subclass. r)r,s r pre_orderzBase.pre_order]r.rcRt|ts|g}g}d}|jjD]-}||ur||j |d}|j |/|jj ||j_|D]}|j|_d|_y)z/Replace this node with a new one in the parent.FNT) isinstancelistparentchildrenextendappendchanged)r%new l_childrenfoundchxs rreplacez Base.replacees#t$%C ++&&BTz?%%c*!!"%' ) A{{AH rc|}t|ts-|jsy|jd}t|ts-|jS)z9Return the line number which generated the invocant node.Nr)r4Leafr7linenor%nodes r get_linenozBase.get_lineno|sAT4(====#DT4({{rc^|jr|jjd|_y)NT)r6r: was_changedr,s rr:z Base.changeds! ;; KK   !rc|jrht|jjD]E\}}||us |jj|jj|=d|_|cSyy)z Remove the node from the tree. Returns the position of the node in its parent's children before it was removed. N)r6 enumerater7r:)r%irEs rremovez Base.removesb ;;$T[[%9%9:44<KK'') ,,Q/"&DKH ; rc|jyt|jjD](\}}||us |jj|dzcSy#t$rYywxYw)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)r6rJr7 IndexErrorr%rKchilds r next_siblingzBase.next_siblingsi ;; "$++"6"67HAu} ;;//!448"  sA A&%A&c|jyt|jjD].\}}||us |dk(ry|jj|dz cSy)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)r6rJr7rOs r prev_siblingzBase.prev_siblingsZ ;; "$++"6"67HAu}6{{++AaC00 8rc#bK|jD]}|jEd{y7wN)r7leavesr%rPs rrVz Base.leavess&]]E||~ % %# %s #/-/cV|jyd|jjzS)Nrr)r6depthr,s rrYz Base.depths' ;; 4;;$$&&&rc8|j}|y|jS)z Return the string immediately following the invocant node. This is effectively equivalent to node.next_sibling.prefix )rQprefix)r%next_sibs r get_suffixzBase.get_suffixs" $$  rrc6t|jdS)Nascii)strencoder,s r__str__z Base.__str__st9##G, ,r)__name__ __module__ __qualname____doc__r r6r7rH was_checkedrr'__hash__r#r-r0r2r@rFr:rLpropertyrQrSrVrYr^sys version_inforerrrrrs D FHKK# H """".    1 1&'  &  -!rrceZdZdZ ddZdZdZejdkDreZ dZ dZ d Z d Z ed Zej d Zd ZdZdZy)Nodez+Concrete implementation for interior nodes.Nc||_t||_|jD] }||_ |||_|r |dd|_yd|_y)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 r5r7r6r\fixers_applied)r%r r7contextr\rrr>s r__init__z Node.__init__sR X --BBI    DK "0"3D "&D rcz|jjdt|jd|jdSz)Return a canonical string representation.(, ))r!rfrr r7r,s r__repr__z Node.__repr__s,#~~66(3#}}. .rcTdjtt|jS)k Return a pretty string representation. This reproduces the input source exactly. r[)joinmaprcr7r,s r __unicode__zNode.__unicode__s wws3 .//rr_cd|j|jf|j|jfk(SzCompare two nodes for equality.)r r7r$s rr#zNode._eqs' 4==)ejj%..-IIIrct|j|jDcgc]}|jc}|jScc}wz$Return a cloned (deep) copy of self.)rr)rpr r7r-rr)r%r>s rr-z Node.clones<DIIT]]C]r ]C#'#6#68 8CsA c#jK|jD]}|jEd{|y7 wz*Return a post-order iterator for the tree.N)r7r0rWs rr0zNode.post_orders0]]E'') ) )#  *s #31 3c#jK||jD]}|jEd{y7wz)Return a pre-order iterator for the tree.N)r7r2rWs rr2zNode.pre_order s, ]]E( ( (# (s '313cN|jsy|jdjS)zO The whitespace and comments preceding this node in the input. r[rr7r\r,s rr\z Node.prefixs# }}}}Q&&&rcF|jr||jd_yyNrrr%r\s rr\z Node.prefixs ==&,DMM!  # rcx||_d|j|_||j|<|jy)z Equivalent to 'node.children[i] = child'. This method also sets the child's parent attribute appropriately. N)r6r7r:rOs r set_childzNode.set_child s3  "& a  a rcj||_|jj|||jy)z Equivalent to 'node.children.insert(i, child)'. This method also sets the child's parent attribute appropriately. N)r6r7insertr:rOs r insert_childzNode.insert_child*s(   Q& rch||_|jj||jy)z Equivalent to 'node.children.append(child)'. This method also sets the child's parent attribute appropriately. N)r6r7r9r:rWs r append_childzNode.append_child3s&   U# rNNN)rfrgrhrirtrzrrmrnrer#r-r0r2rlr\setterrrrrrrrprps5 $'2. 0 & J8  ) '' ]]--rrpceZdZdZdZdZdZddgfdZdZdZ e jdkDre Z d Z d Zd Zd Zd ZedZej(dZy)rBz'Concrete implementation for leaf nodes.r[rNcx||\|_\|_|_||_||_|||_|dd|_y)z Initializer. Takes a type constant (a token number < 256), a string value, and an optional context keyword argument. N)_prefixrCcolumnr valuerr)r%r rrsr\rrs rrtz Leaf.__init__FsG  7> 4DL44;    !DL,Q/rch|jjd|jd|jdSrv)r!rfr rr,s rrzz Leaf.__repr__Ys'#~~66#yy#zz+ +rcF|jt|jzS)r|)r\rcrr,s rrzLeaf.__unicode___s {{S_,,rr_cd|j|jf|j|jfk(Sr)r rr$s rr#zLeaf._eqjs' 4::&5::u{{*CCCrct|j|j|j|j|j ff|j Sr)rBr rr\rCrrrr,s rr-z Leaf.clonens=DIItzz[[4;; "<=#'#6#68 8rc#K|ywrUrr,s rrVz Leaf.leavests  c#K|ywrrr,s rr0zLeaf.post_orderw  rc#K|ywrrr,s rr2zLeaf.pre_order{rrc|jS)zP The whitespace and comments preceding this token in the input. )rr,s rr\z Leaf.prefixs ||rc2|j||_yrU)r:rrs rr\z Leaf.prefixs  r)rfrgrhrirrCrrtrzrrmrnrer#r-rVr0r2rlr\rrrrrBrB=s1G F F "0&+ - & D8   ]]rrBc|\}}}}|s||jvr!t|dk(r|dSt|||St|||S)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)rs) number2symbollenrprB)grraw_noder rrsr7s rconvertrsX&."D%(42+++ x=A A; D(G44D%11rcDeZdZdZdZdZdZdZdZdZ d dZ d dZ dZ y) 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. Nc,tj|S)z>Constructor that prevents BasePattern from being instantiated.rrs rrzBasePattern.__new__rrct|j|j|jg}|r|d |d=|r|d |jj ddj tt|dS)Nrwrxry) rr contentrr!rfr}r~repr)r%rs rrzzBasePattern.__repr__sd$))$dllDII>tBx'RtBx'>>22DIIc$o4NOOrc|S)z A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect. rr,s roptimizezBasePattern.optimizes  rc|j|j|jk7ry|j,d}|i}|j||sy|r|j|||jr|||j<y)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)r%rEresultsrs rmatchzBasePattern.matchsw 99 TYY$))%; << #A">>$*q!  499!%GDII rcJt|dk7ry|j|d|S)z Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns. rFr)rr)r%nodesrs r match_seqzBasePattern.match_seqs' u:?zz%(G,,rc#NKi}|r|j|d|rd|fyyyw)z} Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. rrN)r)r%rrs rgenerate_matcheszBasePattern.generate_matchess1  TZZa!,Q$J-5s#%rU) rfrgrhrir rrrrzrrrrrrrrrs7  DG D# P 2-rrc$eZdZddZddZddZy) LeafPatternNc6||||_||_||_y)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. N)r rr)r%r rrs rrtzLeafPattern.__init__s%       rcRt|tsytj|||S)z*Override match() to insist on a leaf node.F)r4rBrrr%rErs rrzLeafPattern.match s$$%  tW55rc4|j|jk(S) 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. )rrrs rrzLeafPattern._submatchs||tzz))rrrU)rfrgrhrtrrrrrrrs(6 *rrc eZdZdZddZddZy) NodePatternFNc||6t|}t|D]\}}t|tsd|_||_||_||_y)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. NT)r5rJr4WildcardPattern wildcardsr rr)r%r rrrKitems rrtzNodePattern.__init__$sT    7mG$W-4dO4%)DN.   rc|jrVt|j|jD]2\}}|t |jk(s||j |yyt |jt |jk7ryt |j|jD]\}}|j||ryy)rTF)rrrr7rrzipr)r%rErcr subpatternrPs rrzNodePattern._submatchAs >>(t}}E1DMM***q) F  t|| DMM 2 2!$T\\4==!A J##E73"BrrrU)rfrgrhrrtrrrrrr sI:rrcNeZdZdZddedfdZdZd dZd dZdZ d Z d Z d Z y) 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. Nrc| ttt|}|D]}||_||_||_||_y)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)* N)tupler~rminmaxr)r%rrrralts rrtzWildcardPattern.__init__ks@0  Cw/0Gw  rcd}|jEt|jdk(r-t|jddk(r|jdd}|jdk(r\|jdk(rM|jt |j S|)|j |j k(r|j S|jdkrt|trx|jdkri|j |j k(rPt|j|j|jz|j|jz|j S|S)z+Optimize certain stacked wildcard patterns.Nrr)r) rrrrrrrr4r)r%rs rrzWildcardPattern.optimizes  LL $   "s4<<?';q'@a+J 88q=TXX]||#" 22%499 +G!**,, HHMj_E NNa DII$@":#5#5#'88JNN#:#'88JNN#:#-??4 4 rc(|j|g|S)z'Does this pattern exactly match a node?)rrs rrzWildcardPattern.matchs~~tfg..rc|j|D]L\}}|t|k(s|5|j||jrt |||j<yy)z4Does this pattern exactly match a sequence of nodes?TF)rrrrr5)r%rrrrs rrzWildcardPattern.match_seqsY))%0DAqCJ&NN1%yy-1%[ * 1rc #&K|jbt|jdtt||jzD](}i}|j r|d|||j <||f*y|j dk(r|j |yttdr#tj}tt_ |j|dD])\}}|j r|d|||j <||f+ ttdr t_ yy#t$r@|j|D])\}}|j r|d|||j <||f+YewxYw#ttdr t_ wwxYww)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_matcheshasattrrmstderrr_recursive_matches RuntimeError_iterative_matches)r%rcountr save_stderrs rrz WildcardPattern.generate_matchessd << txxSUTXX-F)FG99#(%=AdiiLQh H YY+ %))%0 0 sM*!jj %Z  - $ 7 7q AHE1yy',Ve}$)) (N!B3 .!,CJ/  #!% 7 7 >HE1yy',Ve}$)) (N!? #3 .!,CJ/s=CF>D$E0F$AE-*E0,E--E00FFc#Kt|}d|jk\rdifg}|jD]/}t||D]\}}||f|j ||f 1|rg}|D]\}} ||ks ||j ks|jD]b}t|||dD]N\} } | dkDs i}|j | |j | || z|f|j || z|fPd|}|ryyw)z(Helper to iteratively yield the matches.rN)rrrrr9rr) r%rnodelenrrrr new_resultsc0r0c1r1s rrz"WildcardPattern._iterative_matchess e* =R%K<rs3  6n-6n-`k4k\L4L\2&S&Sl)*+)*X:+:zy)ky)x [ F%r