]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
gccrs: Read-only check if the variable is mutable type.
authorRyutaro Okada <1015ryu88@gmail.com>
Tue, 12 Aug 2025 05:01:08 +0000 (22:01 -0700)
committerArthur Cohen <arthur.cohen@embecosm.com>
Thu, 30 Oct 2025 19:58:40 +0000 (20:58 +0100)
gcc/rust/ChangeLog:

* checks/errors/rust-readonly-check2.cc (ReadonlyChecker::check_variable):
Read-only check if the variable is mutable type.
(ReadonlyChecker::is_mutable_type): Read-only check if the variable is mutable type.
* checks/errors/rust-readonly-check2.h: Read-only check if the variable is mutable type.

Signed-off-by: Ryutaro Okada <1015ryu88@gmail.com>
gcc/rust/checks/errors/rust-readonly-check2.cc
gcc/rust/checks/errors/rust-readonly-check2.h

index 9ff09a96702a56ec466818deecfb5df5031e076a..c39da76aac52ea5f4ef79b0d74f687cea18cff92 100644 (file)
@@ -110,6 +110,11 @@ ReadonlyChecker::check_variable (IdentifierPattern *pattern,
 {
   if (!mutable_context.is_in_context ())
     return;
+
+  TyTy::BaseType *type;
+  if (context.lookup_type (pattern->get_mappings ().get_hirid (), &type)
+      && is_mutable_type (type))
+    return;
   if (pattern->is_mut ())
     return;
 
@@ -236,18 +241,18 @@ ReadonlyChecker::visit (DereferenceExpr &expr)
   auto to_deref = expr.get_expr ().get_mappings ().get_hirid ();
   if (!context.lookup_type (to_deref, &to_deref_type))
     return;
-  if (to_deref_type->get_kind () == TyTy::TypeKind::REF)
-    {
-      auto ref_type = static_cast<TyTy::ReferenceType *> (to_deref_type);
-      if (!ref_type->is_mutable ())
-       rust_error_at (expr.get_locus (), "assignment of read-only location");
-    }
-  if (to_deref_type->get_kind () == TyTy::TypeKind::POINTER)
-    {
-      auto ptr_type = static_cast<TyTy::PointerType *> (to_deref_type);
-      if (!ptr_type->is_mutable ())
-       rust_error_at (expr.get_locus (), "assignment of read-only location");
-    }
+  if (!is_mutable_type (to_deref_type))
+    rust_error_at (expr.get_locus (), "assignment of read-only location");
+}
+
+bool
+ReadonlyChecker::is_mutable_type (TyTy::BaseType *type)
+{
+  if (type->get_kind () == TyTy::TypeKind::REF)
+    return static_cast<TyTy::ReferenceType *> (type)->is_mutable ();
+  if (type->get_kind () == TyTy::TypeKind::POINTER)
+    return static_cast<TyTy::PointerType *> (type)->is_mutable ();
+  return false;
 }
 } // namespace HIR
 } // namespace Rust
index 06af9dbd17c7bca351d3fca149b9c585615a8ed7..3525620c8002b8502ad892706cc66b1300b7b439 100644 (file)
@@ -61,6 +61,8 @@ private:
   void collect_assignment_tuple (TuplePattern &pattern, bool has_init_expr);
 
   void check_variable (IdentifierPattern *pattern, location_t assigned_loc);
+
+  bool is_mutable_type (TyTy::BaseType *type);
 };
 
 } // namespace HIR