Skip to content

Add a lint for attempting to mutate a const item #345

Closed
@Aaron1011

Description

@Aaron1011

Proposal

Add a new lint CONST_ITEM_MUTATION. Given an item const FOO: SomeType = .., this lint fires on:

  • Attempting to write directly to a field (FOO.field = some_val) or
    array entry (FOO.array_field[0] = val)
  • Taking a mutable reference to the const item (&mut FOO), including
    through an autoderef FOO.some_mut_self_method()

The lint message explains that since each use of a constant creates a
new temporary, the original const item will not be modified.

The need for such a lint was brought up in rust-lang/rust#74053, rust-lang/rust#55721, and rust-lang/rust-clippy#829

While this could be a clippy lint, I believe that this is important enough to go in the compiler. Without this lint, users may write useless code which is silent accepted (e.g. FOO[0] = my_val or MY_CONST_VEC.push(val)). Such code may come about as a result of unrelated refactoring (e.g. changing a static to a const, and changing a method to use &mut self instead of interior mutability).

Mentors or Reviewers

I've implemented this lint in rust-lang/rust#75573
cc @oli-obk

Process

The main points of the Major Change Process is as follows:

  • File an issue describing the proposal.
  • A compiler team member or contributor who is knowledgeable in the area can second by writing @rustbot second.
    • Finding a "second" suffices for internal changes. If however you are proposing a new public-facing feature, such as a -C flag, then full team check-off is required.
    • Compiler team members can initiate a check-off via @rfcbot fcp merge on either the MCP or the PR.
  • Once an MCP is seconded, the Final Comment Period begins. If no objections are raised after 10 days, the MCP is considered approved.

You can read more about Major Change Proposals on forge.

Comments

This issue is not meant to be used for technical discussion. There is a Zulip stream for that. Use this issue to leave procedural comments, such as volunteering to review, indicating that you second the proposal (or third, etc), or raising a concern that you would like to be addressed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-compilerAdd this label so rfcbot knows to poll the compiler teammajor-changeA proposal to make a major change to rustcmajor-change-acceptedA major change proposal that was accepted

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions