Related articles |
---|
possible bug in JLex/cup ? thibault.langlois@di.fc.ul.pt (2003-02-21) |
From: | thibault.langlois@di.fc.ul.pt (Thibault Langlois) |
Newsgroups: | comp.compilers |
Date: | 21 Feb 2003 01:19:52 -0500 |
Organization: | http://groups.google.com/ |
Keywords: | parse, Java, question |
Posted-Date: | 21 Feb 2003 01:19:52 EST |
Hello,
I've sent this message to comp.lang.java a couple of days ago and
someone suggested that it would be more apropriated to send it to
comp.compilers.
---------------------
I get a strange behavior for the following test program. It is the
traditional calc program that evaluates arithmetic expressions.
The program should print the value of the expression after the user
press enter but this does not happen. I have to press several times
enter or enter another expression to see the result:
$ java Calc_parser
5 +3
5+7
=> 8;
5+12
=> 12;
59+8
=> 17;
=> 67;
---------------------------------
What surprise me is that the equivalent grammar (taken from the bison
manual) just works fine with flex/bison:
%token NUM
%left '+'
%%
input: /* empty string */
| input line
;
line: '\n'
| exp '\n' { printf ("=> %d\n", $1); }
;
exp: NUM { $$ = $1; }
| exp '+' exp { $$ = $1 + $3; }
;
$ calc
5+5
=> 10
8+98+6
=> 112
---------------------------------------
Here is the code:
The JLex file (in order to shorten the example I have only a plus
operator):
import java_cup.runtime.Symbol;
%%
%cup
%line
%%
"+" { return new Symbol(Calc_sym.PLUS); }
(\n|\r) { return new Symbol(Calc_sym.EOL); }
[0-9]+ { return new Symbol(Calc_sym.NUMBER, new Integer(yytext())); }
[ \t] { /* ignore white space. */ }
. { System.err.println("Illegal character: "+yytext()); }
The cup file:
import java_cup.runtime.*;
parser code {:
public static void main(String args[]) throws Exception {
new Calc_parser(new Yylex(System.in)).parse();
}
:}
terminal EOL, PLUS;
terminal Integer NUMBER;
non terminal line, lines;
non terminal Integer expr;
precedence left PLUS;
lines ::= | lines line ;
line ::= EOL | expr:e EOL {: System.out.println(" => "+e+";"); :}
;
expr ::= NUMBER:n
{: RESULT = n; :}
| expr:l PLUS expr:r
{: RESULT = new Integer(l.intValue() + r.intValue()); :}
;
Any suggestion is much apreciated.
Return to the
comp.compilers page.
Search the
comp.compilers archives again.