Skip to content

Tidy up const_ops, rename to const_arith_ops #143949

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

clarfonthey
Copy link
Contributor

@clarfonthey clarfonthey commented Jul 15, 2025

Tracking issue: #143802

This is split into three commits for ease of reviewability:

  1. Updates the forward_ref_* macros to accept multiple attributes (in anticipation of needing rust_const_unstable attributes) and also require attributes in these macros. Since the default attribute only helps for the initial implementations, it means it's easy to get wrong for future implementations, as shown for the saturating implementations which were incorrect before.
  2. Renames const_ops feature to const_arith_ops and adds constness and trivial implementations to the remaining traits in core::ops::arith.
  3. Constifies the rest of the reasonable implementations.

A few random other notes on the implementation specifically:

  • Unfortunately, without Tracking Issue for macro_named_capture_groups #142999 implemented, we can't make the constness in the forward_ref_* macros work nicely without copy-pasting the macro body. Instead of doing that, I decided to go for a cursed extra const argument, which is then used for the actual const keyword. I explicitly mention named macro capture groups as a way of doing this better in the comments.
  • I unindented the attributes that were passed to the forward_ref_* macro calls because in some places rustfmt wanted them to be unindented, and in others it was allowed because they were themselves inside of macro bodies. I chose the consistent indenting even though I (personally) think it looks worse.

As far as the actual changes go, this renames the const_ops feature to const_arith_ops (anticipating, e.g., const_bit_ops) and constifies the following additional traits:

  • Neg
  • AddAssign
  • SubAssign
  • MulAssign
  • DivAssign
  • RemAssign

In terms of constified implementations of these traits, it adds the reference-forwarded versions of all the arithmetic operators, which are defined by the macros in library/core/src/internal_macros.rs. I'm not going to fully enumerate these because we'd be here all day, but sufficed to say, it effectively allows adding an & to one or both sides of an operator for primitives.

Additionally, I constified the implementations for Wrapping, Saturating, and Duration as well, since all of them forward to already-const-stable methods. Specifically for Duration, the ref-forwarding is not present.

Note

Concerns (0 active)

Managed by @rustbot—see help for details.

@rustbot
Copy link
Collaborator

rustbot commented Jul 15, 2025

r? @ibraheemdev

rustbot has assigned @ibraheemdev.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-clippy Relevant to the Clippy team. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Jul 15, 2025
@rustbot
Copy link
Collaborator

rustbot commented Jul 15, 2025

Some changes occurred in src/tools/clippy

cc @rust-lang/clippy

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@@ -75,6 +76,7 @@ impl MulAssign<i64> for Wrap {
}
}

#[clippy::msrv = "1.88.0"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this for?

Copy link
Member

@samueltardieu samueltardieu Jul 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This hides a real issue: to know whether it can replace "a = a OP b" by "a OP= b" (where OP is, for example, "+"), Clippy looks for the const-stability of the sole associated item of the trait corresponding to "OP=". Here, AddAssign is now identified as const-stable, and Clippy attempts to replace a = a + b; by a += b; in a const context, when a is of a generic type implementing AddAssign.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes: I'm not quite sure whether this code should even remain on Clippy's side after this PR, since I'm pretty sure that "MSRV" doesn't account for nightly compilers, and we definitely won't want to ever stabilise an operator without its corresponding assign version. I chose the easiest approach to get it to pass without making too much of a modification, since it makes more sense to edit this in the clippy repo directly instead of via the subtree.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed rust-lang/rust-clippy#15285 to keep track of this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the meantime, you could go with https://rfc1149.pastes.sh/patch-assign-op-pattern.diff and remove the msrv attribute, and we'll take care of reintroducing the proper code in Clippy.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the test, res = res + Self::ONE; cannot be replaced by res += Self::ONE in a const context because T (the type of res and Self::ONE) implements AddAssign, not [const] AddAssign (and it implements [const] Add, hence the valid + operation in the const context). But Clippy, if it stays unpatched, will suggest it because it only checks the constness of the AddAssign trait declaration, not its implementation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I am mistaken and this suggestion is valid, then instead of commenting the test, just add a //~^ assign_op_pattern below the res = res + Self::ONE; line and bless the results, but I think you'll get an invalid .fixed file.

Copy link
Contributor Author

@clarfonthey clarfonthey Jul 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, you're totally correct here; I was mistaken. So, this is a genuine bug, but it's unrelated to the actual issue at hand, IMHO: it should also suggest to replace [const] Add with [const] AddAssign, or add it. Or at least make it not an automatically applicable thing. It has nothing to do with the const stability of the trait, but the const bound on the trait.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, this is a genuine bug in Clippy, but it activates only when your PR goes in, unless you apply something similar to the patch at https://rfc1149.pastes.sh/patch-assign-op-pattern.diff which neutralizes the bug.

If you prefer, I can submit this patch as a PR to the current repository to neutralize the bug before the current PR gets merged, but this will be no better than integrating it as part of this PR. I don't suggest to submit it to the Clippy repo, as it won't get merged into the compiler repo before the next sync on July 24.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's fair, and now that I understand, I'll go with your patch instead.

@rustbot
Copy link
Collaborator

rustbot commented Jul 16, 2025

Only organization members can add or resolve concerns.

@rust-log-analyzer

This comment has been minimized.

@samueltardieu
Copy link
Member

@rustbot concern May break Clippy

(checking if concerns work as top-level comments only, real concern was written here, and discussion about the error message is on Zulip)

@rustbot rustbot added the S-waiting-on-concerns Status: Awaiting concerns to be addressed by the author label Jul 16, 2025
@samueltardieu
Copy link
Member

@rustbot resolve May break Clippy

We cleared up the misunderstanding of what the problem was.

@rustbot rustbot removed the S-waiting-on-concerns Status: Awaiting concerns to be addressed by the author label Jul 17, 2025
@rust-log-analyzer
Copy link
Collaborator

The job aarch64-gnu-llvm-19-2 failed! Check out the build log: (web) (plain enhanced) (plain)

Click to see the possible cause of the failure (guessed by this bot)
[RUSTC-TIMING] corebenches test:true 8.697
error: `std::ops::Add` is not yet stable as a const trait
##[error]   --> coretests/tests/floats/mod.rs:260:23
    |
260 |         assert_biteq!(ten.add(two), ten + two);
    |                       ^^^^^^^^^^^^
    |
help: add `#![feature(const_arith_ops)]` to the crate attributes to enable
   --> coretests/tests/lib.rs:109:1
    |
109 + #![feature(const_arith_ops)]
    |

error: `std::ops::Sub` is not yet stable as a const trait
##[error]   --> coretests/tests/floats/mod.rs:261:23
    |
261 |         assert_biteq!(ten.sub(two), ten - two);
    |                       ^^^^^^^^^^^^
    |
help: add `#![feature(const_arith_ops)]` to the crate attributes to enable
   --> coretests/tests/lib.rs:109:1
    |
109 + #![feature(const_arith_ops)]
    |

error: `std::ops::Mul` is not yet stable as a const trait
##[error]   --> coretests/tests/floats/mod.rs:262:23
    |
262 |         assert_biteq!(ten.mul(two), ten * two);
    |                       ^^^^^^^^^^^^
    |
help: add `#![feature(const_arith_ops)]` to the crate attributes to enable
   --> coretests/tests/lib.rs:109:1
    |
109 + #![feature(const_arith_ops)]
    |

error: `std::ops::Div` is not yet stable as a const trait
##[error]   --> coretests/tests/floats/mod.rs:263:23
    |
263 |         assert_biteq!(ten.div(two), ten / two);
    |                       ^^^^^^^^^^^^
    |
help: add `#![feature(const_arith_ops)]` to the crate attributes to enable
   --> coretests/tests/lib.rs:109:1
    |
109 + #![feature(const_arith_ops)]
    |

error: `std::ops::Rem` is not yet stable as a const trait
##[error]   --> coretests/tests/floats/mod.rs:278:23
    |
278 |         assert_biteq!(ten.rem(two), ten % two);
    |                       ^^^^^^^^^^^^
    |
help: add `#![feature(const_arith_ops)]` to the crate attributes to enable
   --> coretests/tests/lib.rs:109:1
    |
109 + #![feature(const_arith_ops)]
    |

For more information about this error, try `rustc --explain E0635`.
[RUSTC-TIMING] coretests test:true 47.087
error: could not compile `coretests` (test "coretests") due to 6 previous errors
env -u RUSTC_WRAPPER CARGO_ENCODED_RUSTDOCFLAGS="-Csymbol-mangling-version=v0\u{1f}-Zrandomize-layout\u{1f}-Zunstable-options\u{1f}--check-cfg=cfg(bootstrap)\u{1f}--check-cfg=cfg(llvm_enzyme)\u{1f}-Dwarnings\u{1f}-Wrustdoc::invalid_codeblock_attributes\u{1f}--crate-version\u{1f}1.90.0-nightly\t(4cb8e28f7\t2025-07-17)" CARGO_ENCODED_RUSTFLAGS="-Csymbol-mangling-version=v0\u{1f}-Zrandomize-layout\u{1f}-Zunstable-options\u{1f}--check-cfg=cfg(bootstrap)\u{1f}--check-cfg=cfg(llvm_enzyme)\u{1f}-Zmacro-backtrace\u{1f}-Csplit-debuginfo=off\u{1f}-Clink-arg=-L/usr/lib/llvm-19/lib\u{1f}-Cllvm-args=-import-instr-limit=10\u{1f}-Clink-args=-Wl,-z,origin\u{1f}-Clink-args=-Wl,-rpath,$ORIGIN/../lib\u{1f}-Alinker-messages\u{1f}--cap-lints=allow\u{1f}--cfg\u{1f}randomized_layouts" RUSTC="/checkout/obj/build/aarch64-unknown-linux-gnu/stage1-tools/cg_clif/dist/rustc-clif" RUSTDOC="/checkout/obj/build/aarch64-unknown-linux-gnu/stage1-tools/cg_clif/dist/rustdoc-clif" "/checkout/obj/build/aarch64-unknown-linux-gnu/stage0/bin/cargo" "test" "--manifest-path" "/checkout/obj/build/aarch64-unknown-linux-gnu/stage1-tools/cg_clif/build/sysroot_tests/Cargo.toml" "--target-dir" "/checkout/obj/build/aarch64-unknown-linux-gnu/stage1-tools/cg_clif/build/sysroot_tests_target" "--locked" "--target" "aarch64-unknown-linux-gnu" "-p" "coretests" "-p" "alloctests" "--tests" "--" "-q" exited with status ExitStatus(unix_wait_status(25856))
Command has failed. Rerun with -v to see more details.
Build completed unsuccessfully in 0:12:53
  local time: Thu Jul 17 12:23:04 UTC 2025
  network time: Thu, 17 Jul 2025 12:23:04 GMT
##[error]Process completed with exit code 1.
Post job cleanup.

@clarfonthey
Copy link
Contributor Author

Yeah, I'll be honest, I have genuinely no idea what those tests are doing. I could just add the feature flag, but it wasn't necessary before, and I don't know why.

@samueltardieu
Copy link
Member

Yeah, I'll be honest, I have genuinely no idea what those tests are doing. I could just add the feature flag, but it wasn't necessary before, and I don't know why.

Didn't you just forget to replace #![feature(const_ops)] in library/coretests/tests/lib.rs?

Comment on lines +3 to +4
#![feature(const_arith_ops)]
#![feature(const_trait_impl)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you keep both into a single #![feature] inner attribute, then it won't make a difference in line numbers in the stderr files (after you're reblessed the tests).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-clippy Relevant to the Clippy team. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants