def exitPlusOp(self, ctx: FoxySheepParser.PlusOpContext): """PlusOp[expr1,expr2] We have to treat PlusOp special, because we have to keep the operators intact, and only plus and minus (not PlusMinus or MinusPlus) are flat. The situation is complicated by the fact that Mathematica parses "a-b" as "Plus[a, Times[-1, b]]". We Rewrite the parse tree, inserting the Times context and changing BINARYMINUS to BINARYPLUS.""" # If the op isn't Plus or Minus, nothing to do. if ctx.BINARYMINUS() is None and ctx.BINARYPLUS() is None: return # Since ANTLR4 parses this operator as left associative, we only # need to check the left hand side expr. rhs = ctx.getChild(2) # If the operator of the PlusOp is BINARYMINUS, we rewrite the tree as # "Plus[lhs, Times[-1, rhs]]". Note that if rhs is TIMES, we have to # keep that TIMES flat. if ctx.BINARYMINUS() is not None: # Construct Times, or obtain it from the rhs. times = None if isinstance(rhs, FoxySheepParser.TimesContext): times = rhs else: # If rhs is already a times, keep it flat. times = FoxySheepParser.TimesContext( None, FoxySheepParser.ExprContext(None)) ctx.children.remove(rhs) adopt(ctx, times) adopt(times, rhs) # Add "-1" as the first child of Times. addChild(times, makeNumber(times, -1), 0) # Finally, we have to change operator to BINARYPLUS. plustoken = CommonToken(type=FoxySheepParser.BINARYPLUS) plustoken.text = '+' plus = TerminalNodeImpl(plustoken) # Replace minus token with plus. ctx.children[1] = plus plus.parentCtx = ctx # Flatten flatten(ctx)
def addTokenNode(self, token: Token): node = TerminalNodeImpl(token) self.addChild(node) node.parentCtx = self return node
def addTokenNode(self, token): node = TerminalNodeImpl(token) self.addChild(node) node.parentCtx = self return node