dtolnay / rustversion

Conditional compilation according to rustc compiler version
Apache License 2.0
334 stars 15 forks source link

Support for enum variants #10

Closed jhpratt closed 6 months ago

jhpratt commented 4 years ago

Is it possible to have something like the following?

#[rustversion::attr(since(1.40), non_exhaustive)]
pub enum Error {
    // other items

    #[rustversion::before(1.40.0)]
    #[doc(hidden)]
    __nonexhaustive,
}

I'm trying to give some support to older versions of rustc for the time crate, and am running into this issue when working around #[non_exhaustive]. If not, it's not the end of the world.

CreepySkeleton commented 4 years ago

From reference:

Attribute macros define new outer attributes which can be attached to items, including items in extern blocks, inherent and trait implementations, and trait definitions.

That's all. Attribute macros cannot be used with enum variants, as far as I figured. And also this is not something that can be fixed in rustversion since the Rust compiler is the one setting this policy.

You can work it around by using a build script:

// build.rs

#[rustversion::before(1.40.0)]
fn do_check() {
    println!("cargo:rustc-cfg=artificial_nonexhaustive");
}

#[rustversion::since(1.40.0)]
fn do_check() {}

fn main() {
    do_check()
}

// lib.rs

#[cfg_attr(not(artificial_nonexhaustive), non_exhaustive)]
pub enum Error {
    // other items

    #[cfg(artificial_nonexhaustive)]
    #[doc(hidden)]
    __nonexhaustive,
}
jhpratt commented 4 years ago

Ok, that's pretty much what I knew was possible. Just wasn't sure if it was actionable here. Closing as inactionable, let's look forward to rustc integration!

dtolnay commented 4 years ago

That's fine, we would have an attribute on the item to process attributes on the variants. Similar to https://docs.rs/remain/0.2.1/remain/#compiler-support.

I would accept a PR to implement this.

dtolnay commented 6 months ago

Since rustversion no longer depends on a Rust parser since #24, this is probably no longer feasible in this crate. But someone should make a more fully featured version selection crate that could work on enum variants.