Add a lint for probable misuse of the ^ operator

It is not uncommon to see people misuse the ^ operator to mean exponentiation rather than bitwise-xor. eg:

fn main() { println!("{}", 2^30); }

prints 28 when the programmer probably meant 1<<30. You can see a lot of discussion of this in (and linked from) this GCC bug:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90885

I do not see a -W option in rustc today which would emit a similar warning. Running clippy-driver against this code is also silent. Would anybody be interested in adding a lint for this pattern?

I don't care for this idea at all. With this, every time I actually mean to do a bit-wise xor I'd need to add an #[allow(clippy::xor-as-pow)] or somesuch to silence the lint. I think this gets into territory of warning about things that are basic knowledge. Should we warn if someone uses * when they meant to use +. The operator ^ has a meaning in the language. That meaning is bit-wise xor. There is no way to tell if someone meant to use x.pow(y) when they wrote x^y. Warning on every use of x^y is just too much noise.

The proposal is not to add a warning for every use of ^. That would be absurd. Please read the GCC bug I linked. It is ONLY for the case where both the LHS and RHS of the ^ operator are plain integers.

1 Like

There are a lot of good heuristics. I expect it's very rare to use decimal literals for both x and y for instance. Improving warnings for educational purposes seems like a noble goal, noisiness-wise I would want this warning to essentially never fire for real code.

4 Likes
5 Likes

To spare others the time searching, it appears that confusing_xor_and_pow was renamed to suspicious_xor_used_as_pow. Despite the naming, it is under the clippy::restriction group and not clippy::suspicious.

4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.