Skip to content

Commit 5af110d

Browse files
sakupan102philberty
authored andcommitted
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 <[email protected]>
1 parent 165d7c6 commit 5af110d

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
lines changed

gcc/rust/checks/errors/rust-readonly-check2.cc

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,11 @@ ReadonlyChecker::check_variable (IdentifierPattern *pattern,
110110
{
111111
if (!mutable_context.is_in_context ())
112112
return;
113+
114+
TyTy::BaseType *type;
115+
if (context.lookup_type (pattern->get_mappings ().get_hirid (), &type)
116+
&& is_mutable_type (type))
117+
return;
113118
if (pattern->is_mut ())
114119
return;
115120

@@ -236,18 +241,18 @@ ReadonlyChecker::visit (DereferenceExpr &expr)
236241
auto to_deref = expr.get_expr ().get_mappings ().get_hirid ();
237242
if (!context.lookup_type (to_deref, &to_deref_type))
238243
return;
239-
if (to_deref_type->get_kind () == TyTy::TypeKind::REF)
240-
{
241-
auto ref_type = static_cast<TyTy::ReferenceType *> (to_deref_type);
242-
if (!ref_type->is_mutable ())
243-
rust_error_at (expr.get_locus (), "assignment of read-only location");
244-
}
245-
if (to_deref_type->get_kind () == TyTy::TypeKind::POINTER)
246-
{
247-
auto ptr_type = static_cast<TyTy::PointerType *> (to_deref_type);
248-
if (!ptr_type->is_mutable ())
249-
rust_error_at (expr.get_locus (), "assignment of read-only location");
250-
}
244+
if (!is_mutable_type (to_deref_type))
245+
rust_error_at (expr.get_locus (), "assignment of read-only location");
246+
}
247+
248+
bool
249+
ReadonlyChecker::is_mutable_type (TyTy::BaseType *type)
250+
{
251+
if (type->get_kind () == TyTy::TypeKind::REF)
252+
return static_cast<TyTy::ReferenceType *> (type)->is_mutable ();
253+
if (type->get_kind () == TyTy::TypeKind::POINTER)
254+
return static_cast<TyTy::PointerType *> (type)->is_mutable ();
255+
return false;
251256
}
252257
} // namespace HIR
253258
} // namespace Rust

gcc/rust/checks/errors/rust-readonly-check2.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ class ReadonlyChecker : public DefaultHIRVisitor
6161
void collect_assignment_tuple (TuplePattern &pattern, bool has_init_expr);
6262

6363
void check_variable (IdentifierPattern *pattern, location_t assigned_loc);
64+
65+
bool is_mutable_type (TyTy::BaseType *type);
6466
};
6567

6668
} // namespace HIR

0 commit comments

Comments
 (0)