示例#1
0
 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}";
 }
 /** Simplify (x^a)^b when a and b are both numeric.
  * @param Node $leftOperand
  * @param Node $rightOperand
  * @retval Node|null
  */
 private function doubleExponentiation($leftOperand, $rightOperand)
 {
     // (x^a)^b -> x^(ab) for a, b numbers
     if ($leftOperand instanceof ExpressionNode && $leftOperand->getOperator() == '^') {
         $factory = new MultiplicationNodeFactory();
         $power = $factory->makeNode($leftOperand->getRight(), $rightOperand);
         $base = $leftOperand->getLeft();
         return self::makeNode($base, $power);
     }
     // No simplification found
     return null;
 }