From: Ryutaro Okada <[email protected]>

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 <[email protected]>
---
 .../checks/errors/rust-readonly-check2.cc     | 29 +++++++++++--------
 gcc/rust/checks/errors/rust-readonly-check2.h |  2 ++
 2 files changed, 19 insertions(+), 12 deletions(-)

diff --git a/gcc/rust/checks/errors/rust-readonly-check2.cc 
b/gcc/rust/checks/errors/rust-readonly-check2.cc
index 9ff09a96702..c39da76aac5 100644
--- a/gcc/rust/checks/errors/rust-readonly-check2.cc
+++ b/gcc/rust/checks/errors/rust-readonly-check2.cc
@@ -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
diff --git a/gcc/rust/checks/errors/rust-readonly-check2.h 
b/gcc/rust/checks/errors/rust-readonly-check2.h
index 06af9dbd17c..3525620c800 100644
--- a/gcc/rust/checks/errors/rust-readonly-check2.h
+++ b/gcc/rust/checks/errors/rust-readonly-check2.h
@@ -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
-- 
2.50.1

Reply via email to