Skip to content

Commit

Permalink
Fix ternary operator bug
Browse files Browse the repository at this point in the history
  • Loading branch information
maximecb committed Oct 9, 2023
1 parent 71f61d9 commit bc56b01
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
10 changes: 10 additions & 0 deletions ncc/src/casts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,16 @@ impl Expr
test_expr.as_mut().insert_casts()?;
then_expr.as_mut().insert_casts()?;
else_expr.as_mut().insert_casts()?;

let then_t = then_expr.eval_type()?;
let else_t = else_expr.eval_type()?;

if !then_t.eq(&else_t) {
*else_expr = Box::new(Expr::Cast {
new_type: then_t.clone(),
child: else_expr.clone()
});
}
}

Expr::Call { callee, args } => {
Expand Down
2 changes: 1 addition & 1 deletion ncc/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ impl Unit
out.push_str("\n");

out.push_str("# Reserve the first heap word so we can use address 0 as null\n");
out.push_str(".u64 0;\n");
out.push_str(".u64 0xBADADD5EFEFEFEFE;\n");
out.push_str("\n");

out.push_str("__EVENT_LOOP_ENABLED__:\n");
Expand Down
4 changes: 2 additions & 2 deletions ncc/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,8 +410,8 @@ impl Expr
let then_type = then_expr.eval_type()?;
let else_type = else_expr.eval_type()?;

if !then_type.eq(&else_type) {
return ParseError::msg_only("mismatched types in ternary (?) expression")
if !assign_compat(&then_type, &else_type) {
return ParseError::msg_only("incompatible types in ternary (?) expression")
}

Ok(then_type)
Expand Down
3 changes: 3 additions & 0 deletions ncc/tests/floats.c
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ int main()
assert(0.0f < 1.0f);
assert(-1.0f < 0.0f);

// Ternary expression with mismatched types
assert((0? 1.5f:2) == 2.0f);

// Arithmetic
assert(1.0f + 2.0f == 3.0f);
assert(2.0f * 3.0f == 6.0f);
Expand Down

0 comments on commit bc56b01

Please sign in to comment.