]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
gccrs: Improve type checking for if expressions
authorOwen Avery <powerboat9.gamer@gmail.com>
Sat, 2 Sep 2023 02:07:30 +0000 (22:07 -0400)
committerArthur Cohen <arthur.cohen@embecosm.com>
Tue, 16 Jan 2024 18:04:31 +0000 (19:04 +0100)
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 <powerboat9.gamer@gmail.com>
gcc/rust/typecheck/rust-hir-type-check-expr.cc
gcc/testsuite/rust/compile/type-if.rs [new file with mode: 0644]

index f4ffc40fe09942df707eaeb596397b17dc3f3930..898ea11733334f60ec7f563c309edcf1d04bf46e 100644 (file)
@@ -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 (file)
index 0000000..f3d0eb6
--- /dev/null
@@ -0,0 +1,5 @@
+pub fn main() -> i32 {
+    if 12 {} // { dg-error "mismatched types" }
+    if 12 {} else {} // { dg-error "mismatched types" }
+    0
+}