Skip to content

Commit

Permalink
Support while loops
Browse files Browse the repository at this point in the history
  • Loading branch information
OsamaAhmad00 committed Oct 28, 2023
1 parent 5b3a193 commit c82b80f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/code_generation/llvm/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl<'ctx> LLVMGenerator<'ctx> {
ExpressionNode(expression) => self.generate_expression(expression).as_any_value_enum(),
Scope(..) => self.generate_scope(node).as_any_value_enum(),
If(..) => self.generate_if_statement(node).as_any_value_enum(),
// While(..) => self.generate_while(node),
While(..) => self.generate_while(node).as_any_value_enum(),
// DoWhile(..) => self.generate_do_while(node),
ExpressionStatement(..) => self.generate_expression_statement(node).as_any_value_enum(),
// For(..) => self.generate_for(node),
Expand Down Expand Up @@ -565,16 +565,18 @@ impl<'ctx> LLVMGenerator<'ctx> {
let cond_result = self.generate_expression(condition);

let zero = self.context.i32_type().const_int(0, false);
let i32_value = self.builder.build_int_z_extend(cond_result.into_int_value(), self.context.i32_type(), "extended_condition").unwrap();
let bool_value = self
let i32_value = self
.builder
.build_int_compare(
inkwell::IntPredicate::NE,
i32_value,
zero,
"bool_value",
.build_int_z_extend(
cond_result.into_int_value(),
self.context.i32_type(),
"extended_condition",
)
.unwrap();
let bool_value = self
.builder
.build_int_compare(inkwell::IntPredicate::NE, i32_value, zero, "bool_value")
.unwrap();
self.builder
.build_conditional_branch(bool_value, then_block, else_block)
.unwrap();
Expand Down Expand Up @@ -719,6 +721,11 @@ mod tests {
run_tests_from_file("./src/tests/if.c");
}

#[test]
fn test_while() {
run_tests_from_file("./src/tests/while.c");
}

#[test]
fn test_assignment() {
run_tests_from_file("./src/tests/assignment.c");
Expand Down
29 changes: 29 additions & 0 deletions src/tests/while.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// CASE Basic while loop
// RETURNS 5

int main() {
int x = 0;
int y = 5;
while (y > 0) {
y = y - 1;
x = x + 1;
}
return x;
}

// CASE 45th Fibonacci
// RETURNS 1836311903

int main() {
int x = 45;
int a = 0;
int b = 1;
int c;
while (x) {
c = a + b;
a = b;
b = c;
x = x - 1;
}
return c;
}

0 comments on commit c82b80f

Please sign in to comment.