public function parenthesize(Node $node, ExpressionNode $cutoff, $prepend = '', $conservative = false) { $text = $node->accept($this); if ($node instanceof ExpressionNode) { // Second term is a unary minus if ($node->getOperator() == '-' && $node->getRight() == null) { return "({$text})"; } if ($cutoff->getOperator() == '-' && $node->lowerPrecedenceThan($cutoff)) { return "({$text})"; } if ($conservative) { // Add parentheses more liberally for / and ^ operators, // so that e.g. x/(y*z) is printed correctly if ($cutoff->getOperator() == '/' && $node->lowerPrecedenceThan($cutoff)) { return "({$text})"; } if ($cutoff->getOperator() == '^' && $node->getOperator() == '^') { return "({$text})"; } } if ($node->strictlyLowerPrecedenceThan($cutoff)) { return "({$text})"; } } if (($node instanceof NumberNode || $node instanceof IntegerNode || $node instanceof RationalNode) && $node->getValue() < 0) { return "({$text})"; } // Treat rational numbers as divisions on printing if ($node instanceof RationalNode && $node->getDenominator() != 1) { $fakeNode = new ExpressionNode($node->getNumerator(), '/', $node->getDenominator()); if ($fakeNode->lowerPrecedenceThan($cutoff)) { return "({$text})"; } } return "{$prepend}{$text}"; }
/** * Add curly braces around the LaTex representation of $node if needed. * * Nodes representing a single ConstantNode, VariableNode or NumberNodes (0--9) * are returned as-is. Other Nodes get curly braces around their LaTeX code. * * @param Node $node AST to parse * @retval string */ public function bracesNeeded(Node $node) { if ($node instanceof VariableNode || $node instanceof ConstantNode) { return $node->accept($this); } elseif ($node instanceof IntegerNode && $node->getValue() >= 0 && $node->getValue() <= 9) { return $node->accept($this); } else { return '{' . $node->accept($this) . '}'; } }