[docs]classIfElseFlattener(SequenceWalker):""" Remove unnecessary else branches and make the else node a direct successor of the previous If node if the If node always returns. """
def_handle_Condition(self,node:ConditionNode,parent=None,index=None,**kwargs):ifnode.true_nodeisnotNone:self._handle(node.true_node,parent=node,index=0)ifnode.false_nodeisnotNone:self._handle(node.false_node,parent=node,index=1)ifnode.true_nodeisnotNoneandnode.false_nodeisnotNone:try:true_last_stmts=ConditionProcessor.get_last_statements(node.true_node)exceptEmptyBlockNotice:true_last_stmts=Noneif(true_last_stmtsisnotNoneandNonenotintrue_last_stmtsandall(is_statement_terminating(stmt,self.functions)forstmtintrue_last_stmts)):# all end points in the true node are returningtry:false_last_stmts=ConditionProcessor.get_last_statements(node.false_node)exceptEmptyBlockNotice:false_last_stmts=Noneif(false_last_stmtsisnotNoneandNonenotinfalse_last_stmtsandnotall(is_statement_terminating(stmt,self.functions)forstmtinfalse_last_stmts)):# not all end points in the false node are returning. in this case, we remove the else node and# make it a new node following nodeelse_node=node.false_nodenode.false_node=Noneinsert_node(parent,"after",else_node,index,**kwargs)def_handle_CascadingCondition(self,node:CascadingConditionNode,parent=None,index=None,**kwargs):super()._handle_CascadingCondition(node,parent=parent,index=index,**kwargs)ifnode.else_nodeisnotNone:last_stmts=[]for_,subnodeinnode.condition_and_nodes:try:last_stmts.extend(ConditionProcessor.get_last_statements(subnode))exceptEmptyBlockNotice:last_stmts.append(None)if(last_stmtsandNonenotinlast_stmtsandall(is_statement_terminating(stmt,self.functions)forstmtinlast_stmts)):# all end points in the true node are returning# remove the else node and make it a new node following nodeelse_node=node.else_nodenode.else_node=Noneinsert_node(parent,"after",else_node,index,**kwargs)