Skip to content

Reject cfg on expressions that cannot be safely removed - #159580

Open
Unique-Usman wants to merge 1 commit into
rust-lang:mainfrom
Unique-Usman:ua/cfg
Open

Reject cfg on expressions that cannot be safely removed#159580
Unique-Usman wants to merge 1 commit into
rust-lang:mainfrom
Unique-Usman:ua/cfg

Conversation

@Unique-Usman

@Unique-Usman Unique-Usman commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

View all comments

Change description

This PR changes how #[cfg] behaves in expression positions where removing the expression would result in invalid syntax.

For example:

let _ = 1 + #[cfg(unix)] 2;

This currently works on Unix because the condition is true, but becomes invalid on non-Unix targets when the expression is removed.

The proposed change rejects cfg in these positions regardless of whether the condition is true or false. The goal is to avoid code whose validity depends on the target and to make the behavior more predictable as stmt_expr_attributes is stabilized.

Summary of the discussion

@petrochenkov pointed out that this differs from the usual token-based model for macros: #[cfg(true)] expr produces expr, while #[cfg(false)] expr produces no tokens. From that perspective, only the latter naturally results in an error.

On the other hand, @estebank pointed out that these cases are easy to introduce accidentally and may only be discovered when the code is compiled for another target. This becomes more important with the stabilization of expression attributes.

We also discussed that this is technically a breaking change, since some currently accepted code such as #[cfg(true)] inside a macro invocation would stop compiling. The conclusion was that this is effectively closing a stability hole, and the amount of affected code is expected to be very small.

The current implementation also uses RemoveNodeNotSupported for these cases and adds coverage for both #[cfg(true)] and #[cfg(false)].

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jul 19, 2026
@rustbot

rustbot commented Jul 19, 2026

Copy link
Copy Markdown
Collaborator

r? @petrochenkov

rustbot has assigned @petrochenkov.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler
  • compiler expanded to 74 candidates
  • Random selection from 16 candidates

@Unique-Usman
Unique-Usman marked this pull request as draft July 19, 2026 21:30
@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 19, 2026
@Unique-Usman
Unique-Usman marked this pull request as ready for review July 19, 2026 22:49
@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 19, 2026
@Unique-Usman

Copy link
Copy Markdown
Contributor Author

@estebank

Comment on lines 2412 to 2420
if self.expand_cfg_true(node, attr, pos).as_bool() {
if matches!(
Node::KIND,
AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr
) {
self.cx.dcx().emit_err(RemoveExprNotSupported { span });
}
continue;
}

@mejrs mejrs Jul 20, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What this code does it emits this error if the cfg predicate is true, then if it's false we call expand_cfg_false and (if it's not the crate root) that emits the same error. Not only isn't that immediately obvious, it also suggests that there are still places where #[cfg(true)] is allowed but #[cfg(false)] is not.

Can you change it so there's only one place we emit this error (whether the predicate is true or not)?

Can you also change the error name and message to say that cfg is not supported in these positions?

View changes since the review

@mejrs mejrs Jul 20, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(this check could also be moved elsewhere, I'm not sure what the best place for it is)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you change it so there's only one place we emit this error (whether the predicate is true or not)?

The false version is reported in expand_cfg_false.

This seems like an ok place to do this check for the true case, if it's moved to expand_cfg_true, the match #159580 (comment) will be much larger at least.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not only isn't that immediately obvious, it also suggests that there are still places where #[cfg(true)] is allowed but #[cfg(false)] is not.

If expand_cfg_false is inlined and replaced with a similar match then it will be more clear.

@mejrs mejrs Jul 20, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this file have some #[cfg(true)] as well?

View changes since the review

@petrochenkov

Copy link
Copy Markdown
Contributor

I don't think we should do this.

cfg should ideally behave like a macro, unless necessary for backward compatibility, that also means following the token-based model.

#[my_attr] expr is valid if it expands into tokens that can be parsed as an expression.

  • #[cfg(false)] expr expands into /*empty*/, which cannot be parsed as an expression, so it's an error.
  • #[cfg(true)] expr expands into expr, which can be parsed as an expression, so it's not an error.

@petrochenkov petrochenkov added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 20, 2026
@estebank

estebank commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

@petrochenkov should the toolchain provide guidance for things that are likely to cause trouble because they are always a footgun regardless?

Code like let _ = 1 + #[cfg(unix)] 2; will never make sense, but could easily slip into a codebase without anyone noticing until a downstream tries to build on Windows, and then it becomes a compile error. I 100% agree that the general behavior of cfg attributes should not diverge from macros in general. But I am convinced we should strive to make the toolchain as proactive as possible in avoiding user mistakes. A custom #[my_cfg(..)] wouldn't have the benefit of this proactive, of course, making it slightly worse to use than the built-in. I think having this check is important for the effort to stabilize attributes in expressions, which I think has enough consensus on a subset that can be safely stabilized. If that happens, the prevalence of these kind of attributes might be higher than it is now.

Edit: even if we don't emit an error, shouldn't this case in particular be at least deny-by-default lint, given that it is syntactically correct, but unlikely to be what the user intended?

@mejrs

mejrs commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

cfg should ideally behave like a macro

#159581 won't stabilize attribute macros on expressions, so should we move #[cfg(pred)] expr to be feature gated by proc_macro_hygiene, like attribute macros currently are?

Also if we ever get a way for macros to overload based on what position (type, expr, etc) they're in (perhaps similar to macro_attr and macro_derive), then that would make the proposed behavior feel more natural.

@petrochenkov

Copy link
Copy Markdown
Contributor

should the toolchain provide guidance for things that are likely to cause trouble because they are always a footgun regardless?

Yes, this just looks like a lint material to me.
The compiler knows additional details about some specific macro and can say that using it in some contexts is not a good idea, even if it technically works.

Are you sure cfg in these positions is always unstable?
In that case we can report a hard error just as a conservative measure to avoid stabilizing a questionable case, or keep it feature-gated as @mejrs says.

@mejrs

mejrs commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Code like let _ = 1 + #[cfg(unix)] 2; will never make sense, but could easily slip into a codebase without anyone noticing until a downstream tries to build on Windows, and then it becomes a compile error.

For an example, see https://github.com/PyO3/pyo3/blob/09b8d484b3f79b8519cac63be9d71a107cb14952/pyo3-ffi/examples/string-sum/src/lib.rs#L36 where the value of an array length depends on conditional compilation.

It would be quite tempting to try to write that as...

const SLOTS_LEN: usize = 1 + #[cfg(Py_3_12)] 1 + #[cfg(Py_GIL_DISABLED)] 1 + #[cfg(Py_3_15)] 4);

...and end up in one of those situations where it looks like something that does what you expect, only for it to turn out you're wrong. It would just be another gotcha that most people are going to run into at some point.

Comment thread compiler/rustc_expand/src/expand.rs
@petrochenkov

Copy link
Copy Markdown
Contributor

Are you sure cfg in these positions is always unstable?

This is technically a breaking change, because it closes a stability hole.
This code works now, but will stop working after this change.

macro_rules! mac {
    ($expr:expr) => { $expr.clone() }
}

fn main() {
    let _ = mac!(#[cfg(true)] 10);
}

@petrochenkov

Copy link
Copy Markdown
Contributor

Let's land this, it will simplify the stabilization of stmt_expr_attributes.
The breakage is very unlikely in practice and we'll know whether it happens from beta crater runs, crater is too busy now for a separate run.
@rustbot author

@rustbot

rustbot commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@petrochenkov

Copy link
Copy Markdown
Contributor

Could you also add this as a test case?

#[derive(Clone)]
enum E {
    V1 = #[cfg(true)] 1,
    V2 = #[cfg_attr(true, cfg(true))] 2,
}

Both variants should produce errors.
This executes configure_expr, which is an eager cfg expansion logic performed by derives.

@rustbot

rustbot commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Aug 6, 2026
@rustbot rustbot removed the S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. label Aug 6, 2026
@petrochenkov

Copy link
Copy Markdown
Contributor

Could you also do the changes

@petrochenkov

Copy link
Copy Markdown
Contributor

This is also a language change that needs to go through the language team.
Could you write the change description and summary of the discussion above for them?
I'll nominate this PR after that.
@rustbot author

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Aug 6, 2026
@Unique-Usman

Copy link
Copy Markdown
Contributor Author

@petrochenkov - what changes do you want me to make regarding this ?

@mejrs

mejrs commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

@petrochenkov - what changes do you want me to make regarding this ?

At the time I wrote this, the test was just

fn main() {
    let _ = #[cfg(false)] ();
    //~^ ERROR removing an expression is not supported in this position
    let _ = 1 + 2 + #[cfg(false)] 3;
    //~^ ERROR removing an expression is not supported in this position
    let _ = [1, 2, 3][#[cfg(false)] 1];
    //~^ ERROR removing an expression is not supported in this position
}

i.e. just testing false cfgs, not true ones as well, but it looks like it's partially been addressed already.

Can you update to also include smth like

fn main() {
    let _ = #[cfg(true)] ();
    //~^ ERROR removing an expression is not supported in this position
    let _ = 1 + 2 + #[cfg(true)] 3;
    //~^ ERROR removing an expression is not supported in this position
    let _ = [1, 2, 3][#[cfg(true)] 1];
    //~^ ERROR removing an expression is not supported in this position
}

Previously, expressions behind stmt_expr_attributes were only rejected
when the cfg condition evaluated to false. If the condition was true,
the code compiled successfully.

This meant code like an attributed binary operand could compile on one
platform but fail on another, even though removing the operand would leave
an invalid expression.

This change always rejects cfg in expression positions where removing the
expression would produce invalid code. Expression positions where removal is
safe continue to work as before.

Signed-off-by: Usman Akinyemi <usmanakinyemi202@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants