]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
gccrs: Add size checking to SlicePattern
authorYap Zhi Heng <yapzhhg@gmail.com>
Fri, 11 Jul 2025 14:29:31 +0000 (22:29 +0800)
committerArthur Cohen <arthur.cohen@embecosm.com>
Tue, 5 Aug 2025 14:36:55 +0000 (16:36 +0200)
gcc/rust/ChangeLog:

* typecheck/rust-hir-type-check-pattern.cc(TypeCheckPattern::visit(SlicePattern)):
Implement size checking for SlicePattern when type checking against array parent

Signed-off-by: Yap Zhi Heng <yapzhhg@gmail.com>
gcc/rust/typecheck/rust-hir-type-check-pattern.cc
gcc/testsuite/rust/compile/slicepattern-size-mismatch.rs [new file with mode: 0644]

index 5608030db72c641a0afc0f4d9ccdaa3fae7b616e..bb0e27bb2a6c06b6e0b44c4e8232de8c192901cb 100644 (file)
@@ -652,11 +652,25 @@ TypeCheckPattern::visit (HIR::SlicePattern &pattern)
     {
     case TyTy::ARRAY:
       {
-       // FIXME: implement compile-time size checks when ArrayType's capacity
-       // is updated to be evaluated in compile-time
-       // https://github.com/Rust-GCC/gccrs/issues/3882
        auto &array_ty_ty = static_cast<TyTy::ArrayType &> (*parent);
        parent_element_ty = array_ty_ty.get_element_type ();
+       tree cap = array_ty_ty.get_capacity ();
+       if (error_operand_p (cap))
+         {
+           rust_error_at (parent->get_locus (),
+                          "capacity of array %qs is not known at compile time",
+                          array_ty_ty.get_name ().c_str ());
+           break;
+         }
+       auto cap_wi = wi::to_wide (cap).to_uhwi ();
+       if (cap_wi != pattern.get_items ().size ())
+         {
+           rust_error_at (pattern.get_locus (), ErrorCode::E0527,
+                          "pattern requires %lu elements but array has %lu",
+                          (unsigned long) pattern.get_items ().size (),
+                          (unsigned long) cap_wi);
+           break;
+         }
        break;
       }
     case TyTy::SLICE:
diff --git a/gcc/testsuite/rust/compile/slicepattern-size-mismatch.rs b/gcc/testsuite/rust/compile/slicepattern-size-mismatch.rs
new file mode 100644 (file)
index 0000000..b54b532
--- /dev/null
@@ -0,0 +1,8 @@
+fn main() {
+    let arr = [0, 1];
+
+    match arr {
+        [0, 1, 2] => {} // { dg-error "pattern requires 3 elements but array has 2 .E0527." }
+        _ => {}
+    }
+}
\ No newline at end of file