From d64ba3eaacfc75bcdf91bca939ebb2ac125cbaf4 Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Sat, 16 May 2020 02:59:03 +0200 Subject: [PATCH] If/then/else clauses --- syntaxique/lang.y | 12 +++++++++++- syntaxique/langlex.l | 4 ++++ syntaxique/test.my | 29 ++++++++++++++++++++++++----- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/syntaxique/lang.y b/syntaxique/lang.y index c6b9dfc..386fde6 100644 --- a/syntaxique/lang.y +++ b/syntaxique/lang.y @@ -122,7 +122,7 @@ stmt* make_stmt (int type, var *var, expr *expr, %type expr %type 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 IDENT %left ';' @@ -146,6 +146,10 @@ stmt : assign { $$ = make_stmt(';',NULL,NULL,$1,$3,NULL); } | WHILE expr DO stmt OD { $$ = 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 { $$ = make_stmt(PRINT,NULL,NULL,NULL,NULL,$2); } @@ -216,6 +220,12 @@ void execute (stmt *s) case WHILE: while (eval(s->expr)) execute(s->left); break; + case IF: + if (eval(s->expr)) + execute(s->left); + else if (s->right != NULL) + execute(s->right); + break; case PRINT: print_vars(s->list); puts(""); diff --git a/syntaxique/langlex.l b/syntaxique/langlex.l index bcea3eb..09a51bc 100644 --- a/syntaxique/langlex.l +++ b/syntaxique/langlex.l @@ -8,6 +8,10 @@ DIG [0-9] "while" { return WHILE; } "do" { return DO; } "od" { return OD; } +"if" { return IF; } +"then" { return THEN; } +"fi" { return FI; } +"else" { return ELSE; } "print" { return PRINT; } "true" { return TRUE; } "false" { return FALSE; } diff --git a/syntaxique/test.my b/syntaxique/test.my index 0f41a24..e19b089 100644 --- a/syntaxique/test.my +++ b/syntaxique/test.my @@ -2,20 +2,39 @@ bool x,y,z; x := true; y := true; -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 := true; y := false; 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; y := true; 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; y := false; z := x <=> y; -print x,y,z +if x <=> y then + z := x && y; + print x,y,z +else + print y,x,z +fi