Subversion Repositories programming

Rev

Rev 230 | Rev 244 | 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
%token RESET

/* Robot Grammar */
%%

program : program line
    | ;

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

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;
static boolean interactive = false;

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 ("Specify the file to use as the first command-line");
        System.out.println ("option. (EX: java Parser filename.txt)");
        System.exit (1);
        */
        System.out.println("[Quit with CTRL-D]");
        System.out.print("Expression: ");
        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();