Detecting absence of `cfg` attributes?

I'd like to define a custom cfg attributes which takes the mycfg="value" form, and where it can either be omitted (in which case a default is used), or is one of a set of allowed values, with a compile_error! in the event an invalid value is given.

I can check that the value is within the allowed set with something like:

#[cfg(not(any(mycfg = "foo", mycfg = "bar", mycfg = "baz")))]
compile_error!("mycfg must be one of: foo, bar, baz");

...but the problem is if I do that, it's not possible to omit --cfg mycfg="..." and it's now a hard requirement.

I was hoping I could do something like:

#[cfg(all(mycfg, not(any(mycfg = "foo", mycfg = "bar", mycfg = "baz"))))]
compile_error!("mycfg must be one of: foo, bar, baz");

...but #[cfg(mycfg)] only works for the --cfg mycfg form without =.

Is there any way to make this work?

Note that you also need extra checks for when more than one value is passed: --cfg mycfg=foo --cfg mycfg=bar.

I don't think there's a solution here. You also can't protect against someone making a typo in the attribute: mykfg=foo either.

There's an unstable solution: -Z check-cfg can be used to list valid cfg names and values (including on behalf of individual crates, via their build scripts).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.