/// <summary> /// Determine whether parentheses are needed around the right subtree base on the current operator. /// </summary> /// <param name="currentOperator">The current binary node's operator.</param> /// <param name="rightSubtree">The right binary subtree.</param> /// <returns>True if need parentheses, false if not.</returns> private static bool NeedParenthesesRight(BinaryOperator currentOperator, BinaryOperatorQueryToken rightSubtree) { BinaryOperator rightOperator = BinaryOperator.GetOperator(rightSubtree.OperatorKind); if (currentOperator.Precedence < rightOperator.Precedence) { return(false); } if (currentOperator.Precedence > rightOperator.Precedence) { return(true); } // They are equal in precedence, return(currentOperator.NeedParenEvenWhenTheSame); }
private void Write(bool needParenthesis, BinaryOperatorQueryToken binary) { if (needParenthesis) { this.builder.Append(ExpressionConstants.SymbolOpenParen); } BinaryOperator currentOperator = BinaryOperator.GetOperator(binary.OperatorKind); // Left binary expression may need paren depending on their operator BinaryOperatorQueryToken leftBinaryExpr = binary.Left as BinaryOperatorQueryToken; if (leftBinaryExpr != null) { Write(NeedParenthesesLeft(currentOperator, leftBinaryExpr), leftBinaryExpr); } else { this.builder.WriteQuery(binary.Left); } this.builder.Append(ExpressionConstants.SymbolEscapedSpace); this.builder.Append(currentOperator.Text); this.builder.Append(ExpressionConstants.SymbolEscapedSpace); // Right binary expression may need paren depending on their operator BinaryOperatorQueryToken rightBinaryExpr = binary.Right as BinaryOperatorQueryToken; if (rightBinaryExpr != null) { Write(NeedParenthesesRight(currentOperator, rightBinaryExpr), rightBinaryExpr); } else { this.builder.WriteQuery(binary.Right); } if (needParenthesis) { this.builder.Append(ExpressionConstants.SymbolClosedParen); } }
/// <summary> /// Determine whether parentheses are needed around the left subtree base on the current operator. /// </summary> /// <param name="currentOperator">The current binary node's operator.</param> /// <param name="leftSubtree">The left binary subtree.</param> /// <returns>True if need parenthese, false if not.</returns> private static bool NeedParenthesesLeft(BinaryOperator currentOperator, BinaryOperatorQueryToken leftSubtree) { BinaryOperator leftOperator = BinaryOperator.GetOperator(leftSubtree.OperatorKind); return(leftOperator.Precedence < currentOperator.Precedence); }