From 6e7ed4bad9656e8b5c5996396ed29ca5f06d3808 Mon Sep 17 00:00:00 2001 From: Owen Avery Date: Fri, 1 Sep 2023 22:07:30 -0400 Subject: gccrs: 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 --- gcc/rust/typecheck/rust-hir-type-check-expr.cc | 26 ++++++++++++++++++++++++-- gcc/testsuite/rust/compile/type-if.rs | 5 +++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 gcc/testsuite/rust/compile/type-if.rs (limited to 'gcc') diff --git a/gcc/rust/typecheck/rust-hir-type-check-expr.cc b/gcc/rust/typecheck/rust-hir-type-check-expr.cc index f4ffc40..898ea11 100644 --- a/gcc/rust/typecheck/rust-hir-type-check-expr.cc +++ b/gcc/rust/typecheck/rust-hir-type-check-expr.cc @@ -444,7 +444,18 @@ TypeCheckExpr::visit (HIR::NegationExpr &expr) void TypeCheckExpr::visit (HIR::IfExpr &expr) { - TypeCheckExpr::Resolve (expr.get_if_condition ().get ()); + TyTy::BaseType *bool_ty = nullptr; + bool ok = context->lookup_builtin ("bool", &bool_ty); + rust_assert (ok); + + TyTy::BaseType *cond_type + = TypeCheckExpr::Resolve (expr.get_if_condition ().get ()); + + unify_site (expr.get_mappings ().get_hirid (), TyTy::TyWithLocation (bool_ty), + TyTy::TyWithLocation (cond_type, + expr.get_if_condition ()->get_locus ()), + expr.get_locus ()); + TypeCheckExpr::Resolve (expr.get_if_block ().get ()); infered = TyTy::TupleType::get_unit_type (expr.get_mappings ().get_hirid ()); @@ -453,7 +464,18 @@ TypeCheckExpr::visit (HIR::IfExpr &expr) void TypeCheckExpr::visit (HIR::IfExprConseqElse &expr) { - TypeCheckExpr::Resolve (expr.get_if_condition ().get ()); + TyTy::BaseType *bool_ty = nullptr; + bool ok = context->lookup_builtin ("bool", &bool_ty); + rust_assert (ok); + + TyTy::BaseType *cond_type + = TypeCheckExpr::Resolve (expr.get_if_condition ().get ()); + + unify_site (expr.get_mappings ().get_hirid (), TyTy::TyWithLocation (bool_ty), + TyTy::TyWithLocation (cond_type, + expr.get_if_condition ()->get_locus ()), + expr.get_locus ()); + auto if_blk_resolved = TypeCheckExpr::Resolve (expr.get_if_block ().get ()); auto else_blk_resolved = TypeCheckExpr::Resolve (expr.get_else_block ().get ()); diff --git a/gcc/testsuite/rust/compile/type-if.rs b/gcc/testsuite/rust/compile/type-if.rs new file mode 100644 index 0000000..f3d0eb6 --- /dev/null +++ b/gcc/testsuite/rust/compile/type-if.rs @@ -0,0 +1,5 @@ +pub fn main() -> i32 { + if 12 {} // { dg-error "mismatched types" } + if 12 {} else {} // { dg-error "mismatched types" } + 0 +} -- cgit v1.1