examples: java: use explicit token identifiers

* examples/java/calc/Calc.y: Declare all the tokens, so that we are
compatibile with api.token.raw.
* examples/java/calc/Calc.test: Adjust.
This commit is contained in:
Akim Demaille
2020-04-04 08:43:28 +02:00
parent fd98afaf10
commit 7fa23136ca
2 changed files with 50 additions and 23 deletions

View File

@@ -30,9 +30,9 @@ run 0 '7
cat >input <<EOF
1 + 2 * * 3
EOF
run 0 "err: 1.9-1.10: syntax error: expected number or '-' or '(' or '!' before '*'"
run 0 "err: 1.9-1.10: syntax error: expected ! or - or ( or number before *"
cat >input <<EOF
12 222
EOF
run 0 "err: 1.6-1.9: syntax error: expected end of line or '=' or '-' or '+' or '*' or '/' or '^' before number"
run 0 "err: 1.6-1.9: syntax error: expected + or - or * or / or ^ or = or end of line before number"

View File

@@ -38,16 +38,25 @@
/* Bison Declarations */
%token
'\n' _("end of line")
BANG "!"
PLUS "+"
MINUS "-"
STAR "*"
SLASH "/"
CARET "^"
LPAREN "("
RPAREN ")"
EQUAL "="
EOL _("end of line")
<Integer>
NUM _("number")
%type <Integer> exp
%nonassoc '=' /* comparison */
%left '-' '+'
%left '*' '/'
%nonassoc "=" /* comparison */
%left "-" "+"
%left "*" "/"
%precedence NEG /* negation--unary minus */
%right '^' /* exponentiation */
%right "^" /* exponentiation */
/* Grammar follows */
%%
@@ -57,28 +66,28 @@ input:
;
line:
'\n'
| exp '\n' { System.out.println ($exp); }
| error '\n'
EOL
| exp EOL { System.out.println ($exp); }
| error EOL
;
exp:
NUM { $$ = $1; }
| exp '=' exp
| exp "=" exp
{
if ($1.intValue () != $3.intValue ())
yyerror (@$, "calc: error: " + $1 + " != " + $3);
}
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '-' exp %prec NEG { $$ = -$2; }
| exp '^' exp { $$ = (int) Math.pow ($1, $3); }
| '(' exp ')' { $$ = $2; }
| '(' error ')' { $$ = 1111; }
| '!' { $$ = 0; return YYERROR; }
| '-' error { $$ = 0; return YYERROR; }
| exp "+" exp { $$ = $1 + $3; }
| exp "-" exp { $$ = $1 - $3; }
| exp "*" exp { $$ = $1 * $3; }
| exp "/" exp { $$ = $1 / $3; }
| "-" exp %prec NEG { $$ = -$2; }
| exp "^" exp { $$ = (int) Math.pow ($1, $3); }
| "(" exp ")" { $$ = $2; }
| "(" error ")" { $$ = 1111; }
| "!" { $$ = 0; return YYERROR; }
| "-" error { $$ = 0; return YYERROR; }
;
%%
@@ -151,15 +160,33 @@ class CalcLexer implements Calc.Lexer {
case StreamTokenizer.TT_EOL:
end.line += 1;
end.column = 0;
return (int) '\n';
return EOL;
case StreamTokenizer.TT_WORD:
yylval = new Integer (st.sval);
end.set (reader.getPreviousPosition ());
return NUM;
case ' ': case '\t':
return yylex ();
case '!':
return BANG;
case '+':
return PLUS;
case '-':
return MINUS;
case '*':
return STAR;
case '/':
return SLASH;
case '^':
return CARET;
case '(':
return LPAREN;
case ')':
return RPAREN;
case '=':
return EQUAL;
default:
return ttype;
throw new AssertionError ("invalid character: " + ttype);
}
}
}