From: Owen Avery Date: Sat, 2 Sep 2023 02:07:30 +0000 (-0400) Subject: gccrs: Improve type checking for if expressions X-Git-Tag: basepoints/gcc-15~2177 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6e7ed4bad9656e8b5c5996396ed29ca5f06d3808;p=thirdparty%2Fgcc.git 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 --- diff --git a/gcc/rust/typecheck/rust-hir-type-check-expr.cc b/gcc/rust/typecheck/rust-hir-type-check-expr.cc index f4ffc40fe099..898ea1173333 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 000000000000..f3d0eb6ca671 --- /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 +}