From: Ryutaro Okada <1015ryu88@gmail.com> Date: Tue, 12 Aug 2025 05:01:08 +0000 (-0700) Subject: gccrs: Read-only check if the variable is mutable type. X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=21684aca74486b0214f0d053955e9a527f3dfb59;p=thirdparty%2Fgcc.git gccrs: Read-only check if the variable is mutable type. 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> --- 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 (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 (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 (type)->is_mutable (); + if (type->get_kind () == TyTy::TypeKind::POINTER) + return static_cast (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