package parser;

import java.util.LinkedList;
import java.util.List;

import tree.TreeNode;

public class Parser extends BasicParser {

  public Parser(String r) {
    super(r);
  }

  // On suppose que le caractere courant est le premier qui peut composer la String.
  // Au retour, le caractere courant est END, '(' ou ')'.
  public String readLabel() {
    StringBuilder s = new StringBuilder();
    while (!isAtEnd() && currentChar() != '(' && currentChar() != ')') {
      s.append(currentChar());
      readNext();
    }
    return s.toString();
  }

  // On suppose que le caractere courant est '('.
  // Au retour, le caractere courant est celui qui suit ')'.
  public TreeNode readTree() {
    if (currentChar() != '(')
      throw new RuntimeException("'(' expected");
    readNext();
    // le caractere courant est le premier qui peut composer la String
    String label = readLabel();
    // le caractere courant est END, '(' ou ')'
    List<TreeNode> children = readChildren();
    // le caractere courant doit etre ')'
    if (currentChar() != ')')
      throw new RuntimeException("')' expected");
    readNext();
    return new TreeNode(label, children);
  }

  public List<TreeNode> readChildren() {
    List<TreeNode> children = new LinkedList<TreeNode>();
    while (currentChar() == '(') {
      children.add(readTree());
    }
    return children;
  }

}

