From 78d16c551087e6534fff8382e2d084330e880a39 Mon Sep 17 00:00:00 2001 From: Nathan Braswell Date: Mon, 16 Mar 2015 05:59:56 -0400 Subject: [PATCH] So Chris found that if/else statements using blocks didn't work because they generated C like if(a) {b}; else {c}; -- so that's fixed now, with test :) --- src/CGenerator.cpp | 12 +++++++++++- tests/test_else.expected_results | 2 ++ tests/test_else.krak | 16 ++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 tests/test_else.expected_results create mode 100644 tests/test_else.krak diff --git a/src/CGenerator.cpp b/src/CGenerator.cpp index 17eb9f1..edc8d6e 100644 --- a/src/CGenerator.cpp +++ b/src/CGenerator.cpp @@ -323,7 +323,17 @@ std::string CGenerator::generate(NodeTree* from, NodeTree* enc case statement: return tabs() + generate(children[0], enclosingObject) + ";\n"; case if_statement: - output += "if (" + generate(children[0], enclosingObject) + ")\n\t" + generate(children[1], enclosingObject); + output += "if (" + generate(children[0], enclosingObject) + ")\n\t"; + // We have to see if the then statement is a regular single statement or a block. + // If it's a block, because it's also a statement a semicolon will be emitted even though + // we don't want it to be, as if (a) {b}; else {c}; is not legal C, but if (a) {b} else {c}; is. + if (children[1]->getChildren()[0]->getDataRef()->type == code_block) { + std::cout << "Then statement is a block, emitting the block not the statement so no trailing semicolon" << std::endl; + output += generate(children[1]->getChildren()[0], enclosingObject); + } else { + std::cout << "Then statement is a simple statement, regular emitting the statement so trailing semicolon" << std::endl; + output += generate(children[1], enclosingObject); + } if (children.size() > 2) output += " else " + generate(children[2], enclosingObject); return output; diff --git a/tests/test_else.expected_results b/tests/test_else.expected_results new file mode 100644 index 0000000..87dfef2 --- /dev/null +++ b/tests/test_else.expected_results @@ -0,0 +1,2 @@ +Right +Right diff --git a/tests/test_else.krak b/tests/test_else.krak new file mode 100644 index 0000000..a9dd61e --- /dev/null +++ b/tests/test_else.krak @@ -0,0 +1,16 @@ +import io:*; + + +|int| main() { + if (1>2) { + println("Wrong"); + } else { + println("Right"); + } + if (3>4) + println("Wrong"); + else + println("Right"); +} + +