3 \@sldZdZddlZddlZddlmZddlmZddlm Z Gdd d e Z Gd d d e Z ia d d ZdS)aA bottom-up tree matching algorithm implementation meant to speed up 2to3's matching process. After the tree patterns are reduced to their rarest linear path, a linear Aho-Corasick automaton is created. The linear automaton traverses the linear paths from the leaves to the root of the AST and returns a set of nodes for further matching. This reduces significantly the number of candidate nodes.z+George Boutsioukis N) defaultdict)pytree) reduce_treec@s eZdZdZejZddZdS)BMNodez?Class for a node of the Aho-Corasick automaton used in matchingcCs"i|_g|_ttj|_d|_dS)N)transition_tablefixersnextrcountidcontent)selfr#/usr/lib64/python3.6/btm_matcher.py__init__s zBMNode.__init__N)__name__ __module__ __qualname____doc__ itertoolsr rrrrrrsrc@s8eZdZdZddZddZddZdd Zd d Zd S) BottomMatcherzgThe main matcher class. After instantiating the patterns should be added using the add_fixer methodcCs0t|_t|_|jg|_g|_tjd|_dS)NZRefactoringTool) setmatchrrootZnodesr loggingZ getLoggerZlogger)rrrrrs  zBottomMatcher.__init__cCsL|jj|t|j}|j}|j||jd}x|D]}|jj|q4WdS)zReduces a fixer's pattern tree to a linear path and adds it to the matcher(a common Aho-Corasick automaton). The fixer is appended on the matching states and called when they are reached)startN)r appendrZ pattern_treeZget_linear_subpatternaddr)rfixerZtreeZlinear match_nodesZ match_noderrr add_fixer%s    zBottomMatcher.add_fixercCs|s |gSt|dtrhg}xF|dD]:}|j||d}x&|D]}|j|j|dd|q>Wq&W|S|d|jkrt}||j|d<n|j|d}|ddr|j|dd|d}n|g}|SdS)z5Recursively adds a linear pattern to the AC automatonr)rrN) isinstancetuplerextendrr)rpatternrr Z alternativeZ end_nodesendZ next_noderrrr1s" " zBottomMatcher.addc Cs0|j}tt}x|D]}|}x|r&d|_x,|jD]"}t|tjr8|jdkr8d|_Pq8W|j dkrp|j}n|j }||j kr|j |}x|j D]"}||krg||<||j |qWnd|j}|j dk r|j jrP||j kr|j |}x2|j D](}||jkr g||<||j |qW|j }q$WqW|S)auThe main interface with the bottom matcher. The tree is traversed from the bottom using the constructed automaton. Nodes are only checked once as the tree is retraversed. When the automaton fails, we give it one more shot(in case the above tree matches as a whole with the rejected leaf), then we break for the next leaf. There is the special case of multiple arguments(see code comments) where we recheck the nodes Args: The leaves of the AST tree to be matched Returns: A dictionary of node matches with fixers as the keys T;FrN)rrlistZ was_checkedZchildrenr"rZLeafvaluetyperr rparentkeys) rZleavesZcurrent_ac_noderesultsZleafZcurrent_ast_nodeZchildZ node_tokenrrrrrunSs>          zBottomMatcher.runcs*tdfdd|jtddS)z %d [label=%s] //%sr)rr,printr type_reprstrr r )ZnodeZ subnode_keyZsubnode) print_noderrr2s  z*BottomMatcher.print_ac..print_node}N)r/r)rr)r2rprint_acs  zBottomMatcher.print_acN) rrrrrr!rr.r4rrrrrs  "=rcCsHtss