If/then/else clauses

This commit is contained in:
Yohann D'ANELLO 2020-05-16 02:59:03 +02:00
parent c78a047ec3
commit d64ba3eaac
3 changed files with 39 additions and 6 deletions

View File

@ -122,7 +122,7 @@ stmt* make_stmt (int type, var *var, expr *expr,
%type <e> expr %type <e> expr
%type <s> stmt assign %type <s> stmt assign
%token BOOL WHILE DO OD ASSIGN PRINT OR AND XOR NOT TRUE FALSE %token BOOL WHILE DO OD IF THEN ELSE FI ASSIGN PRINT OR AND XOR NOT TRUE FALSE
%token <i> IDENT %token <i> IDENT
%left ';' %left ';'
@ -146,6 +146,10 @@ stmt : assign
{ $$ = make_stmt(';',NULL,NULL,$1,$3,NULL); } { $$ = make_stmt(';',NULL,NULL,$1,$3,NULL); }
| WHILE expr DO stmt OD | WHILE expr DO stmt OD
{ $$ = make_stmt(WHILE,NULL,$2,$4,NULL,NULL); } { $$ = make_stmt(WHILE,NULL,$2,$4,NULL,NULL); }
| IF expr THEN stmt ELSE stmt FI
{ $$ = make_stmt(IF,NULL,$2,$4,$6,NULL); }
| IF expr THEN stmt FI
{ $$ = make_stmt(IF,NULL,$2,$4,NULL,NULL); }
| PRINT varlist | PRINT varlist
{ $$ = make_stmt(PRINT,NULL,NULL,NULL,NULL,$2); } { $$ = make_stmt(PRINT,NULL,NULL,NULL,NULL,$2); }
@ -216,6 +220,12 @@ void execute (stmt *s)
case WHILE: case WHILE:
while (eval(s->expr)) execute(s->left); while (eval(s->expr)) execute(s->left);
break; break;
case IF:
if (eval(s->expr))
execute(s->left);
else if (s->right != NULL)
execute(s->right);
break;
case PRINT: case PRINT:
print_vars(s->list); print_vars(s->list);
puts(""); puts("");

View File

@ -8,6 +8,10 @@ DIG [0-9]
"while" { return WHILE; } "while" { return WHILE; }
"do" { return DO; } "do" { return DO; }
"od" { return OD; } "od" { return OD; }
"if" { return IF; }
"then" { return THEN; }
"fi" { return FI; }
"else" { return ELSE; }
"print" { return PRINT; } "print" { return PRINT; }
"true" { return TRUE; } "true" { return TRUE; }
"false" { return FALSE; } "false" { return FALSE; }

View File

@ -2,20 +2,39 @@ bool x,y,z;
x := true; x := true;
y := true; y := true;
z := x <=> y; if x <=> y then
print x,y,z; z := x && y;
print x,y,z
else
print y,x,z
fi;
x := true; x := true;
y := false; y := false;
z := x <=> y; z := x <=> y;
print x,y,z; if x <=> y then
z := x && y;
print x,y,z
else
print y,x,z
fi;
x := false; x := false;
y := true; y := true;
z := x <=> y; z := x <=> y;
print x,y,z; if x <=> y then
z := x && y;
print x,y,z
else
print y,x,z
fi;
x := false; x := false;
y := false; y := false;
z := x <=> y; z := x <=> y;
if x <=> y then
z := x && y;
print x,y,z print x,y,z
else
print y,x,z
fi