Rev 243 | 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/* Robot Grammar */%%program : S { System.out.println ("There are: " + r.getVal() + " apples in the bag!"); };S : PUT S TAKE S { System.out.println ("S -> PUT S TAKE S"); }| PUT S { System.out.println ("S -> PUT S"); r.incVal(); }| { System.out.println ("S -> epsilon"); };%%private Yylex lexer;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{try{Parser yyparser = new Parser (new FileReader (args[0]));yyparser.yyparse();}catch (Exception e){System.out.println ("Tried to take too many apples out of the bag!");}}public class Robot{int val = 0;void incVal () { val++; }void decVal () { val--; }int getVal () { return val; }}Robot r = new Robot();