rust-lang / rust-lang/rust-clippy

macro should be const fn

Open
#9,153 0 comments 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

Checks macros which should instead be const fns.

Lint Name

declarative_macro_should_be_const_fn

Category

correctness

Advantage

A significant improvement to code readability & documentation.

I do not believe there are performance differences when compiled with optimizations although I think it may be worth evaluating.

Drawbacks

It makes the typing more explicit, requiring more changes if the developer later wanted to change types.

Example

Where:

mod ioc {
    use std::os::raw::c_uint;
    pub const _IOC_NRSHIFT: c_uint = 0;
    pub const _IOC_TYPESHIFT: c_uint = 8;
    pub const _IOC_SIZESHIFT: c_uint = 16;
    pub const _IOC_DIRSHIFT: c_uint = 30;
}

this:

#[macro_export]
macro_rules! ioctl_expr {
    ($dir:expr, $ty:expr, $nr:expr, $size:expr) => {
        (($dir << $crate::ioctl::_IOC_DIRSHIFT)
            | ($ty << $crate::ioctl::_IOC_TYPESHIFT)
            | ($nr << $crate::ioctl::_IOC_NRSHIFT)
            | ($size << $crate::ioctl::_IOC_SIZESHIFT)) as ::std::os::raw::c_ulong
    };
}

should be this:

const fn ioctl_expr(dir: c_uint, ty: c_uint, nr: c_uint, size: c_uint) -> ::std::os::raw::c_ulong {
    (
        dir << crate::ioctl::_IOC_DIRSHIFT |
        ty << crate::ioctl::_IOC_TYPESHIFT |
        nr << crate::ioctl::_IOC_NRSHIFT |
        size << crate::ioctl::_IOC_SIZESHIFT
    ) as ::std::os::raw::c_ulong
}

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 locating the declarative_macro_should_be_const_fn lint entry point in rust-clippy and review how existing correctness lints identify applicable macros. Define the cases covered by the example and evaluate whether optimization affects the proposed change. Done means the lint reliably identifies eligible macros and has coverage for its behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.