Rust-clippy: new lint: find functions that can be "const fn"

Created on 6 Feb 2018  路  6Comments  路  Source: rust-lang/rust-clippy

Maybe we can automatically find simple functions that can be const fn

This was suggested during FOSDEM talk on rusts const evaluation: https://youtu.be/Zz863ksXRhA?t=1102
I didn't see a ticket about this yet so here we go.

A-suggestion E-medium L-lint T-MIR

Most helpful comment

Going to give this a try over the next couple of days. First step is getting https://github.com/rust-lang/rust/pull/57342 merged.

All 6 comments

Yes! This would be great! I would be happy with it even if it just started as a simple lint that encouraged people to make code like this const:

impl Game {
    // Could be const
    pub fn new() -> Self {
        Self {
            tiles: Default::default(),
            current_piece: Piece::X,
            winner: None,
        }
    }
}

Of course, it could always grow from there to become more complete. This would just give people a start into using const. Not having const on simple associated functions like this makes it really hard to use these in const declarations in your code. If a library you use doesn't have this, you get completely stuck.

That's why I think it's really important to start getting people in the habit of putting const on functions when they can. I think a clippy lint will go a long way.

So... implementing this lint has become significantly easier lately: Just call https://github.com/rust-lang/rust/blob/master/src/librustc_mir/transform/qualify_min_const_fn.rs#L11 and check the result. There are some false positives, but we can't check them right now outside the compiler (because the check emits errors immediately instead of reporting a Result, so if we run it on normal functions we get loads of errors emitted).

Going to give this a try over the next couple of days. First step is getting https://github.com/rust-lang/rust/pull/57342 merged.

With @phansch's PR merged is this issue completely implemented?

@sunjay Yeah, I guess we can handle bugs and further improvements via new issues, so I'm going to close this one, thanks!

Awesome! Thank you for your work 馃榿馃帀

Was this page helpful?
0 / 5 - 0 ratings