Skip to content

Commit cc42db3

Browse files
powerboat9philberty
authored andcommitted
Improve type checking for if expressions
gcc/rust/ChangeLog: * typecheck/rust-hir-type-check-expr.cc (TypeCheckExpr::visit): Expect if conditions to have type bool. gcc/testsuite/ChangeLog: * rust/compile/type-if.rs: New test. Signed-off-by: Owen Avery <[email protected]>
1 parent abf727d commit cc42db3

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

gcc/rust/typecheck/rust-hir-type-check-expr.cc

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -444,7 +444,18 @@ TypeCheckExpr::visit (HIR::NegationExpr &expr)
444444
void
445445
TypeCheckExpr::visit (HIR::IfExpr &expr)
446446
{
447-
TypeCheckExpr::Resolve (expr.get_if_condition ().get ());
447+
TyTy::BaseType *bool_ty = nullptr;
448+
bool ok = context->lookup_builtin ("bool", &bool_ty);
449+
rust_assert (ok);
450+
451+
TyTy::BaseType *cond_type
452+
= TypeCheckExpr::Resolve (expr.get_if_condition ().get ());
453+
454+
unify_site (expr.get_mappings ().get_hirid (), TyTy::TyWithLocation (bool_ty),
455+
TyTy::TyWithLocation (cond_type,
456+
expr.get_if_condition ()->get_locus ()),
457+
expr.get_locus ());
458+
448459
TypeCheckExpr::Resolve (expr.get_if_block ().get ());
449460

450461
infered = TyTy::TupleType::get_unit_type (expr.get_mappings ().get_hirid ());
@@ -453,7 +464,18 @@ TypeCheckExpr::visit (HIR::IfExpr &expr)
453464
void
454465
TypeCheckExpr::visit (HIR::IfExprConseqElse &expr)
455466
{
456-
TypeCheckExpr::Resolve (expr.get_if_condition ().get ());
467+
TyTy::BaseType *bool_ty = nullptr;
468+
bool ok = context->lookup_builtin ("bool", &bool_ty);
469+
rust_assert (ok);
470+
471+
TyTy::BaseType *cond_type
472+
= TypeCheckExpr::Resolve (expr.get_if_condition ().get ());
473+
474+
unify_site (expr.get_mappings ().get_hirid (), TyTy::TyWithLocation (bool_ty),
475+
TyTy::TyWithLocation (cond_type,
476+
expr.get_if_condition ()->get_locus ()),
477+
expr.get_locus ());
478+
457479
auto if_blk_resolved = TypeCheckExpr::Resolve (expr.get_if_block ().get ());
458480
auto else_blk_resolved
459481
= TypeCheckExpr::Resolve (expr.get_else_block ().get ());
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
pub fn main() -> i32 {
2+
if 12 {} // { dg-error "mismatched types" }
3+
if 12 {} else {} // { dg-error "mismatched types" }
4+
0
5+
}

0 commit comments

Comments
 (0)