rust-lang / rust-lang/rust-clippy

mixed numeric and data operations (`restriction` group)

Open
#17,649 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

It triggers when treating a number (float, int, complex, ...) as both raw-data and as a mathematical value, or when operating two or more numeric-values in such a way that some are treated as data and others as numbers (with exceptions, such as x << y, because LHS must be data and RHS must be num, so this won't fire the lint)

Note that "raw data operation" isn't just "bitwise operators", it can be (safe) type-casts and (unsafe) transmute

Advantage

Type safety: it forces the user to think about which values should be actual numbers and which are "just bits". This is so that there's no accidental misuse.

Drawbacks

In some cases, too many false-positives. Hence restriction

Example
let mut a: u16 = 0xaa55;
a >>= 1;
a += 1;

Perhaps the user meant:

let mut a: u16 = 0xaa55;
a >>= 1;
a |= 1;
Comparison with existing lints
  • *_endian_bytes is just a niche subset of this concept, but it's not really a "mixed operation" IMO
  • precedence is purely local, it looks at individual expressions. My proposal takes into account a bigger context: from the var declaration to every expression that references it.
Additional Context

This is somewhat related to #16213. That was part of the inspiration, but I've always wanted Rust to have an opt-in "mode" that distinguished between opaque mathematical ints and bit-sequences.

Allowing mixed operations is very convenient for a low-level lang such as Rust, but this can be bad in some safety-critical situations.

An alternative to this lint would be for the user to define opaque newtypes that only expose the desired operations, and use macros for syntax-sugar. I'm unsure if this would be better or worse

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the existing *_endian_bytes and precedence lints, then read issue #16213 for related context. The proposal still needs decisions about scope and false positives; done would mean an agreed restriction lint that detects the described mixed numeric and raw-data operations with appropriate coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.