Subversion Repositories programming

Rev

Rev 243 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
230 ira 1
/*******************************************************************************
2
 * File: robot.y
3
 * 
4
 * Copyright (c) 2006, Ira W. Snyder (devel@irasnyder.com)
5
 * License: GNU General Public License v2
6
 *
7
 * This file implements the grammar that controls our fictional apple-bag
8
 * robot from Project #3, Question #2.
9
 ******************************************************************************/
10
 
11
%{
12
    import java.lang.*;
13
    import java.io.*;
14
    import java.util.StringTokenizer;
15
%}
16
 
17
/* Token Declarations */
18
%token PUT
19
%token TAKE
20
 
21
/* Robot Grammar */
22
%%
23
 
24
program : S         { System.out.println ("There are: " + r.getVal() + " apples in the bag!"); };
25
 
26
S : PUT S TAKE S    { System.out.println ("S -> PUT S TAKE S"); }
27
    | PUT S         { System.out.println ("S -> PUT S"); r.incVal(); }
28
    |               { System.out.println ("S -> epsilon"); };
29
 
30
%%
31
 
32
private Yylex lexer;
33
 
34
public void yyerror (String error)
35
{
36
    System.out.println ("Parse Error: " + error);
37
}
38
 
39
int yylex ()
40
{
41
    int lex_return = -1;
42
 
43
    try
44
    {
45
        lex_return = lexer.yylex();
46
    }
47
    catch (IOException e)
48
    {
49
        System.out.println ("IO Error: " + e);
50
    }
51
 
52
    return lex_return;
53
}
54
 
55
public Parser (Reader r)
56
{
57
    lexer = new Yylex (r, this);
58
}
59
 
60
public static void main (String[] args) throws Exception
61
{
62
    try
63
    {
64
        Parser yyparser = new Parser (new FileReader (args[0]));
65
        yyparser.yyparse();
66
    }
67
    catch (Exception e)
68
    {
69
        System.out.println ("Tried to take too many apples out of the bag!");
70
    }
71
}
72
 
73
public class Robot
74
{
75
    int val = 0;
76
 
77
    void incVal () { val++; }
78
    void decVal () { val--; }
79
    int  getVal () { return val; }
80
}
81
 
82
Robot r = new Robot();
83