import java.util.List;
import java.util.LinkedList;
import java.io.IOException;

/**
 * This class provides a parser for paren-terminated lists of integers.
 * Specifically, this implements the BNF rule:
 * <pre>
 * 	INTLIST := "(" INT ( "," INT )* ")"
 * </pre>
 *
 * @author Terran Lane
 * @version 1.0
 */

public class IntListParser {

  /**
   * This parses the int list from the token stream and returns the compiled
   * list.
   *
   * @param l The token stream
   * @return The resuling list of <code>Integer</code>s, or <code>null</code>
   * if the token stream is at EOF at the start of this call.
   * @exception ParseException If an error occurs during parsing.
   */
  public static List parseIntList(Lexer lex)
    throws ParseException, IOException {
    Token t=lex.next();
    List ll=new LinkedList();
    if (t==null) {
      // legitimate EOF
      return null;
    }
    if (!t.getTokStr().equals("(")) {
      throw new ParseException("Unexpected token '" + t + "'; expected '('");
    }
    // discard open paren
    // get the first int from the stream
    ll.add(ParserSupport.parseInt(lex.next()));
    ParserSupport.checkEOF(t=lex.next());
    while (t.getTokStr().equals(",")) {
      // list is still going -- drop comma and look for next int
      ll.add(ParserSupport.parseInt(lex.next()));
      ParserSupport.checkEOF(t=lex.next());
    }
    // didn't see another comma -- next thing should be the close paren
    if (!t.getTokStr().equals(")")) {
      throw new ParseException("Unexpected token '" + t + "'; expected ')'");
    }
    // drop the close paren, return the completed list
    return ll;
  }

  // this prevents this class from being instantiated by any other object
  private IntListParser() {}
}
