From c0244b58225de5eb967a9202861bf12c355157c0 Mon Sep 17 00:00:00 2001 From: bronku Date: Sat, 6 Dec 2025 10:25:37 +0100 Subject: [PATCH] elif --- src/parser.y | 20 +++++++++++++++----- test/ruby/25.in | 1 - test/ruby/25.out | 20 ++++++++++++++++++++ 3 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 test/ruby/25.out diff --git a/src/parser.y b/src/parser.y index 494870c..e3cd8c6 100644 --- a/src/parser.y +++ b/src/parser.y @@ -61,6 +61,7 @@ %type >> tuple %type >> stmt_list %type > params +%type >> elif_chain %% @@ -80,11 +81,8 @@ stmt: | expr ASSIGN expr NEWLINE { $$ = std::make_unique(std::move($1), std::move($3)); } - | KW_IF expr COLON NEWLINE INDENT stmt_list DEDENT { - $$ = std::make_unique(std::move($2), std::move($6), std::vector>()); - } - | KW_IF expr COLON NEWLINE INDENT stmt_list DEDENT KW_ELSE COLON NEWLINE INDENT stmt_list DEDENT { - $$ = std::make_unique(std::move($2), std::move($6), std::move($12)); + | KW_IF expr COLON NEWLINE INDENT stmt_list DEDENT elif_chain{ + $$ = std::make_unique(std::move($2), std::move($6), std::move($8)); } | KW_FOR IDENTIFIER KW_IN expr COLON NEWLINE INDENT stmt_list DEDENT { $$ = std::make_unique ($2, std::move($4), std::move($8)); @@ -168,6 +166,18 @@ params: { $$ = std::vector();} | IDENTIFIER { $$ = std::vector(); $$.push_back($1); } | params COMMA IDENTIFIER {$1.push_back($3); $$ = std::move($1);} + +elif_chain: + /* empty */ { $$ = std::vector>(); } + | KW_ELIF expr COLON NEWLINE INDENT stmt_list DEDENT elif_chain { + std::vector> output; + output.push_back(std::make_unique(std::move($2), std::move($6), std::move($8))); + $$ = std::move(output); + } + | KW_ELSE COLON NEWLINE INDENT stmt_list DEDENT { + $$ = std::move($5); + } + ; %% namespace yy { void parser::error(const std::string& msg) diff --git a/test/ruby/25.in b/test/ruby/25.in index b8eb954..3380d85 100644 --- a/test/ruby/25.in +++ b/test/ruby/25.in @@ -1,4 +1,3 @@ -# test_arithmetic.py def calculate_bmi(weight, height): bmi = weight / (height ** 2) diff --git a/test/ruby/25.out b/test/ruby/25.out new file mode 100644 index 0000000..ae8e19f --- /dev/null +++ b/test/ruby/25.out @@ -0,0 +1,20 @@ +def calculate_bmi(weight, height) + bmi = weight / height ** 2 + if bmi < 18.5 + category = "Underweight" + else + if bmi < 25 + category = "Normal" + else + if bmi < 30 + category = "Overweight" + else + category = "Obese" + end + end + end + return "BMI: #{bmi}, Category: #{category}" +end +print(calculate_bmi(70, 1.75), "\n") +print(calculate_bmi(90, 1.80), "\n") +print(calculate_bmi(50, 1.65), "\n")