/* Expression.java */

import java.io.*;

/** Implements simple expressions. */
public abstract class Expression {
  /** Finds the ith operand of this Expression.
   * @param i is indicates the operand to be returned (numbering from 0). 
   * @return the ith operand.
   * Throws Error() if the ith operand does not exist.
   */
  public Expression operand(int i) { 
    throw new Error(); 
  }

  /** Computes the number of operands.
   * @return the number of operands in this Expression. */
  abstract public int arity();

  /** Evaluates this expression in the current environment of variable 
   * bindings to values.
   * @return the Value of this expression.
   */
  abstract public Value eval();

  /** The name of the operator associated with this node (e.g., +,
   *  -, etc.) 
   * @return the operator name for this expression
   */
  public String oper() { 
    return "?"; 
  }

  /** Set the value of this Expression (if it is a variable) to V. 
   * Throws an Error if this is not a variable.
   */
  public void set(Value v) { 
    throw new Error(); 
  }

  /** By default, the string (OP OPND0 ... OPNDK), where OP is 
   *  oper(), and OPND0...OPNDK are the toString equivalents 
   *  of the operands. (There must be exactly one space between
   *  the operator and each of the operands, and none before
   *  or after either of the parentheses.)
   * @return a string representation of this Expression.
   */
  public String toString() {    
    /* Fill in for part 1. */
  }

  /** Parse the next Expression in s and remove it from s.
   * @param r is the input for parsing an expression
   * @return the Expression that is found in r.
   * @exception BadExpressionException if r does not contain a valid 
   *   expression.
   */
  public static Expression parse(Reader r) throws
    BadExpressionException {
    /* Fill in for part 3. */
  }

  /** Parse one Expression.
   * @param s is an input string from which to parse an expression.
   * @exception BadExpressionException in case of bad syntax. 
   * @return the parsed Expression.
   */
  public static Expression parse(String s)
    throws BadExpressionException { 
    /* Fill in for part 3.  Hint: a one-line solution exists. */
  } 
}