From 575b81411907191ce13a6f78a4b23b78263625df Mon Sep 17 00:00:00 2001 From: Akim Demaille Date: Sat, 23 Feb 2019 11:35:26 +0100 Subject: [PATCH] d: improve the example * examples/d/calc.y: Exit with failure on errors. Remove useless operators (=, !) meant for the test suite. Add unary + for symmetry. * examples/d/calc.test: Adjust expectations. --- examples/d/calc.test | 2 +- examples/d/calc.y | 37 ++++++++++++++----------------------- 2 files changed, 15 insertions(+), 24 deletions(-) diff --git a/examples/d/calc.test b/examples/d/calc.test index e2bfceeb..30736097 100644 --- a/examples/d/calc.test +++ b/examples/d/calc.test @@ -23,4 +23,4 @@ run 0 7 cat >input < NUM "number" %type exp -%nonassoc "=" /* comparison */ %left "-" "+" %left "*" "/" -%precedence NEG /* negation--unary minus */ +%precedence UNARY /* unary operators */ /* Grammar follows */ %% @@ -44,29 +42,21 @@ line: ; exp: - NUM { $$ = $1; } -| exp "=" exp - { - if ($1 != $3) - yyerror (format ("calc: error: %d != %d", $1, $3)); - } -| exp "+" exp { $$ = $1 + $3; } -| exp "-" exp { $$ = $1 - $3; } -| exp "*" exp { $$ = $1 * $3; } -| exp "/" exp { $$ = $1 / $3; } -| "-" exp %prec NEG { $$ = -$2; } -| "(" exp ")" { $$ = $2; } -| "(" error ")" { $$ = 1111; } -| "!" { $$ = 0; return YYERROR; } -| "-" error { $$ = 0; return YYERROR; } + NUM { $$ = $1; } +| exp "+" exp { $$ = $1 + $3; } +| exp "-" exp { $$ = $1 - $3; } +| exp "*" exp { $$ = $1 * $3; } +| exp "/" exp { $$ = $1 / $3; } +| "+" exp %prec UNARY { $$ = -$2; } +| "-" exp %prec UNARY { $$ = -$2; } +| "(" exp ")" { $$ = $2; } ; - %% class CalcLexer : Lexer { - this () - {} + // Should be a local in main, shared with %parse-param. + int exit_status = 0; int get_char () @@ -84,6 +74,7 @@ class CalcLexer : Lexer { public void yyerror (string s) { + exit_status = 1; stderr.writeln (s); } @@ -141,7 +132,6 @@ class CalcLexer : Lexer { case '-': return YYTokenType.MINUS; case '*': return YYTokenType.STAR; case '/': return YYTokenType.SLASH; - case '!': return YYTokenType.BANG; case '(': return YYTokenType.LPAR; case ')': return YYTokenType.RPAR; case '\n': return YYTokenType.EOL; @@ -150,9 +140,10 @@ class CalcLexer : Lexer { } } -void main () +int main () { CalcLexer l = new CalcLexer (); Calc p = new Calc (l); p.parse (); + return l.exit_status; }