CIT 594 Code Updates for Parser Assignment
Spring 2007, David Matuszek


I have added the following convenience method to my Tree class:

     * Returns the index-th child of this node (zero based), or
     * <code>null</code> if index is too large or too small.
     * @param index The index of a child to retrieve.
     * @return The index-th child of this node, counting from zero.
    public Tree<V> child(int index) {
        if (index < 0 || index >= children.size()) return null;
        else return children.get(index);

And, of course, a corresponding test method in TreeTest:

    public final void testChild() {
        Tree<String> x = new Tree<String>("x");
        Tree<String> y = new Tree<String>("y");
        assertEquals(b1, a1.child(0));
        assertEquals(c1, a1.child(1));
        assertEquals(x, a1.child(2));
        assertEquals(y, a1.child(3));

You can add these to your code, or simply download new copies of and


My isFactor() method did not handle unary plus or minus. Here is an updated version that does.

     * Tries to recognize a &lt;factor&gt;.
     * <pre>&lt;factor&gt; ::= &lt;name&gt;
     *           | &lt;number&gt;
     *           | "(" &lt;expression&gt; ")"</pre>
     * A <code>SyntaxException</code> will be thrown if the opening
     * parenthesis is present but not followed by a valid
     * &lt;expression&gt; and a closing parenthesis.
     * @return <code>true</code> if a factor is recognized.
    public boolean isFactor() {
        boolean startsWithUnary = symbol("+") || symbol("-");
        if(keyword("distance")) return true;
        if (isVariable()) {
            if (symbol("(")) {
                return isAssignOrCallExtender();
            else return true;
        if (number()) return true;
        if (symbol("(")) {
            if (!isExpression()) error("Error in parenthesized expression");
            if (!symbol(")")) error("Unclosed parenthetical expression");
            return true;
       if (startsWithUnary) error("Error in factor");
       return false;

And, of course, a corresponding test method in RecognizerTest:

    public void testUnary() {
        assertTrue(use("3 * (-5 + 8)").isExpression());
        assertTrue(use("-(-5 + 8)").isExpression());
        assertTrue(use("3 * (+5 + 8)").isExpression());
        assertTrue(use("+(+5 + 8)").isExpression()); 
        try { assertFalse(use("- if").isExpression()); }
        catch (SyntaxException e) {}

Please add these manually to your code.