summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--expr.y46
1 files changed, 32 insertions, 14 deletions
diff --git a/expr.y b/expr.y
index 9b28faf..ae422f7 100644
--- a/expr.y
+++ b/expr.y
@@ -17,12 +17,15 @@ typedef struct {
static char **expr_args;
+static int expr_end = 0;
+
#define YYSTYPE expr_yystype
static int yylex(void);
static int yyerror(const char *s);
static void expr_only_integers(YYSTYPE *y1, YYSTYPE *y2);
static int expr_compare(YYSTYPE *y1, YYSTYPE *y2);
+static void expr_print(YYSTYPE *y1);
%}
@@ -41,11 +44,11 @@ static int expr_compare(YYSTYPE *y1, YYSTYPE *y2);
%%
expr : STRING {
- printf("%s\n", $1.u.s);
+ expr_print(&$1);
}
| INTEGER {
- printf("%jd\n", $1.u.i);
+ expr_print(&$1);
}
| '(' expr ')' {
@@ -61,77 +64,77 @@ expr : STRING {
| expr '*' expr {
expr_only_integers(&$1, &$3);
$$.u.i = $1.u.i * $3.u.i;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr '/' expr {
expr_only_integers(&$1, &$3);
$$.u.i = $1.u.i / $3.u.i;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr '%' expr {
expr_only_integers(&$1, &$3);
$$.u.i = $1.u.i % $3.u.i;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr '+' expr {
expr_only_integers(&$1, &$3);
$$.u.i = $1.u.i + $3.u.i;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr '-' expr {
expr_only_integers(&$1, &$3);
$$.u.i = $1.u.i - $3.u.i;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr '=' expr {
$$.type = INTEGER;
$$.u.i = expr_compare(&$1, &$3) == 0;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr NE expr {
$$.type = INTEGER;
$$.u.i = expr_compare(&$1, &$3) != 0;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr '<' expr {
$$.type = INTEGER;
$$.u.i = expr_compare(&$1, &$3) < 0;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr LE expr {
$$.type = INTEGER;
$$.u.i = expr_compare(&$1, &$3) <= 0;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr '>' expr {
$$.type = INTEGER;
$$.u.i = expr_compare(&$1, &$3) > 0;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
| expr GE expr {
$$.type = INTEGER;
$$.u.i = expr_compare(&$1, &$3) >= 0;
- printf("%jd\n", $$.u.i);
+ expr_print(&$$);
return $$.type;
}
@@ -146,6 +149,19 @@ expr : STRING {
%%
+static void expr_print(YYSTYPE *y1)
+{
+ if (!expr_end) {
+ return;
+ }
+
+ if (y1->type == INTEGER) {
+ printf("%jd\n", y1->u.i);
+ } else {
+ printf("%s\n", y1->u.s);
+ }
+}
+
static void expr_only_integers(YYSTYPE *y1, YYSTYPE *y2)
{
if (y1->type == STRING) {
@@ -182,7 +198,8 @@ static int expr_compare(YYSTYPE *y1, YYSTYPE *y2)
static int yylex(void)
{
if (expr_args[optind] == NULL) {
- return YYEOF;
+ expr_end = 1;
+ return 0;
}
char *s = expr_args[optind];
@@ -225,6 +242,7 @@ static int yylex(void)
static int yyerror(const char *s)
{
fprintf(stderr, "expr: %s\n", s);
+ return 0;
}
int main(int argc, char *argv[])