Rev 261 | 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!\n");
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;
private static String input_str = "Input: ";
private Robot r = new Robot();
public void yyerror (String error)
{
/* No need to print out anything here, since we'll
* catch all errors later anyway. */
//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;
}
/* If we have had an error parsing, we probably tried to take too many
* apples out of the bag, so print out a nice error message. */
try
{
yyparser.yyparse();
}
catch (Exception e)
{
System.out.println ("Tried to take too many apples out of the bag!");
}
/* Print ending message if we are in interactive mode */
if (interactive)
{
System.out.println();
System.out.println("Have a nice day");
}
}
/**
* Private class, which will be used to keep track of how many apples
* are in the bag. It could possibly be extended later to allow for a
* graphical reprensentation of the robot.
*/
public class Robot
{
private int val = 0;
void incVal () { val++; }
void decVal () { val--; }
int getVal () { return val; }
void reset () { val = 0; }
}