Subversion Repositories programming

Rev

Rev 258 | Rev 261 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*******************************************************************************
 * File: robot.y
 *
 * Copyright (c) 2006, Ira W. Snyder (devel@irasnyder.com)
 * License: GNU General Public License v2
 *
 * This file implements the grammar that controls our fictional apple-bag
 * robot from Project #3, Question #2.
 ******************************************************************************/

%{
    import java.lang.*;
    import java.io.*;
    import java.util.StringTokenizer;
%}

/* Token Declarations */
%token PUT
%token TAKE
%token NL

/* Robot Grammar */
%%

program : program line
    | ;

line: NL            { if (interactive) System.out.print (input_str); r.reset(); }
    | S NL          { System.out.println ("There are: " + r.getVal() + " apples in the bag!");
                      if (interactive) System.out.print (input_str); r.reset(); };

S : P S T S         { }
    | P S           { }
    |               { };

P : PUT             { System.out.println ("PUT  an apple in the bag"); r.incVal(); };

T : TAKE            { System.out.println ("TAKE an apple out of the bag"); r.decVal(); };

%%

private Yylex lexer;
static boolean interactive = false;
static String input_str = "Input: ";

public void yyerror (String error)
{
    //System.out.println ("Parse Error: " + error);
}

int yylex ()
{
    int lex_return = -1;

    try
    {
        lex_return = lexer.yylex();
    }
    catch (IOException e)
    {
        System.out.println ("IO Error: " + e);
    }

    return lex_return;
}

public Parser (Reader r)
{
    lexer = new Yylex (r, this);
}

public static void main (String[] args) throws Exception
{
    Parser yyparser = null;

    if (args.length > 0)
    {
        // read via file argument
        yyparser = new Parser (new FileReader (args[0]));
    }
    else
    {
        // interactive mode
        yyparser = new Parser (new InputStreamReader (System.in));
        System.out.println("[Quit with CTRL-D]");
        System.out.print(input_str);
        interactive = true;
    }

    try
    {
        yyparser.yyparse();
    }
    catch (Exception e)
    {
        System.out.println ("Tried to take too many apples out of the bag!");
    }

    if (interactive)
    {
        System.out.println();
        System.out.println("Have a nice day");
    }
}

public class Robot
{
    int val = 0;

    void incVal () { val++; }
    void decVal () { val--; }
    int  getVal () { return val; }
    void reset  () { val = 0; }
}

Robot r = new Robot();