rust-lang / rust-lang/rust-clippy

Suggest use of track_caller on assert-like functions

Open
#6,835 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

What it does

Suggest taking advantage of the #[track_caller] feature.

It's a less-known feature of Rust, but quite useful on assert-like functions which want to point out that their caller supplied invalid input. The attribute makes panics point to function's caller, e.g. a unit test, rather than internals of the helper function.

The attribute could be suggested on functions which contain panicking code (panic!, assert!) and are named assert_*. I'm not sure about the function name heuristic. Maybe it could be suggested on any "simple" panicking function, or functions called from any #[test], etc.

Categories (optional)
  • Kind: pedantic, maybe style
Drawbacks

It's difficult to know for certain which functions are appropriate for use with #[track_caller].

Example
fn assert_not_zero(n: u32) {
    assert!(n != 0);
}

Could be written as:

#[track_caller]
fn assert_not_zero(n: u32) {
    assert!(n != 0);
}

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 proposed #[track_caller] use on assert_* functions and the alternatives involving panic!, assert!, or functions called from #[test]. Define a defensible scope and heuristic, then verify that the resulting lint correctly identifies suitable functions without flagging inappropriate cases.

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
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.