/**
  * Flatten an expression with respect to an associative operator: for example the expression (a+b)
  * + (c+d) becomes list(a,b,c,d), with the list in canonical order (sorted by hashCode)
  *
  * @param list a list provided by the caller to contain the result
  * @return the list of expressions
  */
 private List flattenExpression(List list) {
   if (operand0 instanceof BinaryExpression
       && ((BinaryExpression) operand0).operator == operator) {
     ((BinaryExpression) operand0).flattenExpression(list);
   } else {
     int h = operand0.hashCode();
     list.add(operand0);
     int i = list.size() - 1;
     while (i > 0 && h > list.get(i - 1).hashCode()) {
       list.set(i, list.get(i - 1));
       list.set(i - 1, operand0);
       i--;
     }
   }
   if (operand1 instanceof BinaryExpression
       && ((BinaryExpression) operand1).operator == operator) {
     ((BinaryExpression) operand1).flattenExpression(list);
   } else {
     int h = operand1.hashCode();
     list.add(operand1);
     int i = list.size() - 1;
     while (i > 0 && h > list.get(i - 1).hashCode()) {
       list.set(i, list.get(i - 1));
       list.set(i - 1, operand1);
       i--;
     }
   }
   return list;
 }
 /** Is this expression the same as another expression? */
 public boolean equals(Object other) {
   if (other instanceof BinaryExpression) {
     BinaryExpression b = (BinaryExpression) other;
     if (operator == b.operator) {
       if (operand0.equals(b.operand0) && operand1.equals(b.operand1)) {
         return true;
       }
       if (isCommutative(operator) && operand0.equals(b.operand1) && operand1.equals(b.operand0)) {
         return true;
       }
       if (isAssociative(operator)
           && pairwiseEqual(
               flattenExpression(new ArrayList(4)), b.flattenExpression(new ArrayList(4)))) {
         return true;
       }
     }
     if (isInverse(operator, b.operator)
         && operand0.equals(b.operand1)
         && operand1.equals(b.operand0)) {
       return true;
     }
   }
   return false;
 }
  /**
   * @param result
   * @param expr
   */
  private static void serialize(
      FastStringBuffer result, Expression expr, Map reversePrefixMapping) {
    if (expr instanceof Assignation) {
      // XXX not yet supported
    } else if (expr instanceof AxisExpression) {
      AxisExpression axisExpression = (AxisExpression) expr;
      result.append(Axis.axisName[axisExpression.getAxis()]);
      result.append("::");

      final NodeTest nodeTest = axisExpression.getNodeTest();
      if (nodeTest == null) {
        result.append("node()");
      } else {
        result.append(fixPreFixes(nodeTest.toString(), reversePrefixMapping));
      }
    } else if (expr instanceof BinaryExpression) {
      BinaryExpression binaryExpression = (BinaryExpression) expr;
      result.append('(');
      serialize(result, binaryExpression.getOperands()[0], reversePrefixMapping);
      result.append(Token.tokens[binaryExpression.getOperator()]);
      serialize(result, binaryExpression.getOperands()[1], reversePrefixMapping);
      result.append(')');
    } else if (expr instanceof CompareToIntegerConstant) {
      CompareToIntegerConstant compareToIntegerConstant = (CompareToIntegerConstant) expr;
      result.append('(');
      serialize(result, compareToIntegerConstant.getOperand(), reversePrefixMapping);
      result.append(Token.tokens[compareToIntegerConstant.getComparisonOperator()]);
      result.append(Long.toString(compareToIntegerConstant.getComparand()));
      result.append(')');
    } else if (expr instanceof ConditionalSorter) {
      // XXX not yet supported
    } else if (expr instanceof ContextItemExpression) {
      result.append('.');
    } else if (expr instanceof ErrorExpression) {
      // Error do nothing
    } else if (expr instanceof FilterExpression) {
      FilterExpression filterExpression = (FilterExpression) expr;
      result.append('(');
      serialize(result, filterExpression.getControllingExpression(), reversePrefixMapping);
      result.append('[');
      serialize(result, filterExpression.getFilter(), reversePrefixMapping);
      result.append("])");

    } else if (expr instanceof FunctionCall) {
      FunctionCall functionCall = (FunctionCall) expr;
      StructuredQName name = functionCall.getFunctionName();
      if (name.getPrefix() != null && name.getPrefix().length() > 0) {
        result.append(name.getPrefix());
        result.append(":");
      }
      result.append(name.getLocalName());
      result.append("(");

      Iterator iter = functionCall.iterateSubExpressions();
      boolean first = true;
      while (iter.hasNext()) {
        result.append(first ? "" : ", ");
        SaxonXPathExpressionSerializer.serialize(
            result, (Expression) iter.next(), reversePrefixMapping);
        first = false;
      }

      result.append(")");
    } else if (expr instanceof Instruction) {
      // This is not an XPath expression
    } else if (expr instanceof IntegerRangeTest) {
      // XXX not yet supported
    } else if (expr instanceof IsLastExpression) {
      result.append("position() eq last()");
    } else if (expr instanceof Literal) {
      Literal literal = (Literal) expr;
      result.append(literal.getValue().toString());
    } else if (expr instanceof NumberInstruction) {
      // This is not an XPath expression
    } else if (expr instanceof PathExpression) {
      PathExpression pathExpression = (PathExpression) expr;
      result.append('(');
      serialize(result, pathExpression.getControllingExpression(), reversePrefixMapping);
      result.append('/');
      serialize(result, pathExpression.getControlledExpression(), reversePrefixMapping);
      result.append(')');
    } else if (expr instanceof PatternMatchExpression) {
      // XXX not yet supported
    } else if (expr instanceof PatternSponsor) {
      // XXX not yet supported
    } else if (expr instanceof SimpleContentConstructor) {
      // This is not an XPath expression
    } else if (expr instanceof SimpleExpression) {
      // This is not an XPath expression
    }
    /*
        else if (expr instanceof SimpleMappingExpression) {
    	    // XXX not yet supported
    	}
    */
    else if (expr instanceof ParentNodeExpression) {
      result.append("..");
    } else if (expr instanceof RootExpression) {
      // do nothing
    } else if (expr instanceof SortExpression) {
      // XXX not yet supported
    } else if (expr instanceof TailExpression) {
      // XXX not yet supported
    } else if (expr instanceof TupleExpression) {
      // This is not an XPath expression
    } else if (expr instanceof TupleSorter) {
      // This is not an XPath expression
    } else if (expr instanceof UnaryExpression) {
      UnaryExpression unaryExpression = (UnaryExpression) expr;
      serialize(
          result,
          unaryExpression.getBaseExpression(),
          reversePrefixMapping); // Not sure if this is correct in all cases
    } else if (expr instanceof VariableReference) {
      VariableReference variableReference = (VariableReference) expr;
      String d = variableReference.getDisplayName();
      result.append("$");
      result.append(d == null ? "$" : d);
    }
  }