Skip to content

Allow passing expr metavariable as cfg predicate#146961

Merged
rust-bors[bot] merged 2 commits intorust-lang:mainfrom
Jules-Bertholet:expr-cfg
Mar 21, 2026
Merged

Allow passing expr metavariable as cfg predicate#146961
rust-bors[bot] merged 2 commits intorust-lang:mainfrom
Jules-Bertholet:expr-cfg

Conversation

@Jules-Bertholet
Copy link
Contributor

@Jules-Bertholet Jules-Bertholet commented Sep 24, 2025

View all comments

This PR allows expanding expr metavariables inside the configuration predicates of cfg and cfg_attr invocations.
For example, the following code will now compile:

macro_rules! mac {
    ($e:expr) => {
        #[cfg_attr($e, inline)]
        #[cfg($e)]
        fn func() {}

        #[cfg(not($e))]
        fn func() {
            panic!()
        }
    }
}


mac!(any(unix, feature = "foo"));

There is currently no macro_rules fragment specifier that can represent all valid cfg predicates. meta comes closest, but excludes true and false. By fixing that, this change makes it easier to write declarative macros that parse cfg or cfg_attr invocations, for example #146281.

@rustbot label T-lang needs-fcp A-attributes A-cfg A-macros

@rustbot
Copy link
Collaborator

rustbot commented Sep 24, 2025

Some changes occurred in compiler/rustc_attr_parsing

cc @jdonszelmann

@rustbot rustbot added A-attributes Area: Attributes (`#[…]`, `#![…]`) 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 Sep 24, 2025
@rustbot
Copy link
Collaborator

rustbot commented Sep 24, 2025

r? @fee1-dead

rustbot has assigned @fee1-dead.
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

@rustbot rustbot added A-cfg Area: `cfg` conditional compilation A-macros Area: All kinds of macros (custom derive, macro_rules!, proc macros, ..) needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. T-lang Relevant to the language team labels Sep 24, 2025
@fmease fmease added I-lang-nominated Nominated for discussion during a lang team meeting. S-waiting-on-team and removed T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Sep 24, 2025
@rust-log-analyzer

This comment has been minimized.

@petrochenkov petrochenkov self-assigned this Sep 24, 2025
@traviscross traviscross added the P-lang-drag-1 Lang team prioritization drag level 1. https://rust-lang.zulipchat.com/#narrow/channel/410516-t-lang label Sep 24, 2025
@petrochenkov
Copy link
Contributor

petrochenkov commented Sep 26, 2025

Just as an update, after #124141 we effectively no longer have nonterminal tokens in the grammar (*).
At parsing time a pasted expr metavariable is not some NtExpr token, it's just a token stream in invisible parentheses.
If that token stream from expr parses as a cfg predicate then it can be used as a cfg predicate, if it parses as a type or pattern, then it can be used as a pattern as well.
And on the other hand, if a token stream from some other matcher like ty or pat parses as a cfg predicate, then it can be used as a cfg predicate.
In general, the matcher kind is only relevant during macro LHS matching, not during RHS parsing (**).

I hoped that some time after #124141 either @nnethercote or me relax these rules in many cases, when there are no backward compatibility concerns at least, and pass the change through lang team, but it didn't happen yet.
(In particular, tokens from any matchers should be parse-able in expr, ty and pat positions, there should be no compatibility issues there.)

A number of current hacks like accepting impl $ty for Type, or what this PR suggests, are just special cases of that strategy.

@Jules-Bertholet You could very well start the same process, just from a different point and accept any token streams that look like cfg predicates as cfg predicates, from any matchers, not just expr.

(*) Or we technically have, but only for compatibility and to avoid extending the language without the lang team process.
(**) Again, unless there are backward compatibility issues.

@petrochenkov
Copy link
Contributor

As for the current implementation, the new expr-accepting logic is used in parse_meta_item and the new attr parsing infra, so it seems more than just cfg predicates specifically, but I'm not sure what else exactly is affected.

@petrochenkov petrochenkov removed the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Sep 26, 2025
@Urgau Urgau added S-waiting-on-t-lang Status: Awaiting decision from T-lang and removed S-waiting-on-team labels Oct 6, 2025
@joshtriplett
Copy link
Member

This seems reasonable to me. It allows all :expr fragments here, and not all of those will subsequently parse, but that seems okay.

@rfcbot merge

@rust-rfcbot
Copy link
Collaborator

rust-rfcbot commented Oct 8, 2025

Team member @joshtriplett has proposed to merge this. The next step is review by the rest of the tagged team members:

No concerns currently listed.

Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!

cc @rust-lang/lang-advisors: FCP proposed for lang, please feel free to register concerns.
See this document for info about what commands tagged team members can give me.

@rust-rfcbot rust-rfcbot added proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. labels Oct 8, 2025
@traviscross
Copy link
Contributor

@rfcbot reviewed

1 similar comment
@tmandry
Copy link
Member

tmandry commented Oct 8, 2025

@rfcbot reviewed

@bors

This comment was marked as resolved.

@rustbot
Copy link
Collaborator

rustbot commented Mar 15, 2026

The parser was modified, potentially altering the grammar of (stable) Rust
which would be a breaking change.

cc @fmease

@rustbot

This comment has been minimized.

@rustbot
Copy link
Collaborator

rustbot commented Mar 15, 2026

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.

@Jules-Bertholet
Copy link
Contributor Author

@rustbot ready

This should now be confined to affecting cfg predicates only.

@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 Mar 15, 2026
@Jules-Bertholet Jules-Bertholet changed the title Allow passing expr metavariable to cfg Allow passing expr metavariable as cfg predicate Mar 15, 2026
@petrochenkov
Copy link
Contributor

r? @JonathanBrouwer
Could you double check this? The new attribute parsing infra is impenetrable.
The expr fragments are now supposed to parsed in cfg predicates, and only in cfg predicates.

(Why does it all converge to parse_attr_item? cfg predicates are not attr items at all...)

@Jules-Bertholet
Copy link
Contributor Author

@rustbot ready

Copy link
Contributor

@JonathanBrouwer JonathanBrouwer left a comment

Choose a reason for hiding this comment

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

@rust-bors
Copy link
Contributor

rust-bors bot commented Mar 20, 2026

📌 Commit ab36d50 has been approved by JonathanBrouwer

It is now in the queue for this repository.

@rust-bors rust-bors bot added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Mar 20, 2026
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Mar 20, 2026
…anBrouwer

Allow passing `expr` metavariable as `cfg` predicate

This PR allows expanding `expr` metavariables inside the configuration predicates of `cfg` and `cfg_attr` invocations.
For example, the following code will now compile:

```rust
macro_rules! mac {
    ($e:expr) => {
        #[cfg_attr($e, inline)]
        #[cfg($e)]
        fn func() {}

        #[cfg(not($e))]
        fn func() {
            panic!()
        }
    }
}

mac!(any(unix, feature = "foo"));
```

There is currently no `macro_rules` fragment specifier that can represent all valid `cfg` predicates. `meta` comes closest, but excludes `true` and `false`. By fixing that, this change makes it easier to write declarative macros that parse `cfg` or `cfg_attr` invocations, for example rust-lang#146281.

@rustbot label T-lang needs-fcp A-attributes A-cfg A-macros
rust-bors bot pushed a commit that referenced this pull request Mar 21, 2026
…uwer

Rollup of 6 pull requests

Successful merges:

 - #154154 (Emit fewer errors for incorrect rtn and `=` -> `:` typos in bindings)
 - #154155 (tests/ui/async-await/drop-option-future.rs: New regression test)
 - #146961 (Allow passing `expr` metavariable as `cfg` predicate)
 - #154118 (don't suggest non-deriveable traits for unions)
 - #154120 (Start migrating `DecorateDiagCompat::Builtin` items to `DecorateDiagCompat::Dynamic`)
 - #154156 (Moving issue-52049 to borrowck)
rust-bors bot pushed a commit that referenced this pull request Mar 21, 2026
…uwer

Rollup of 6 pull requests

Successful merges:

 - #154154 (Emit fewer errors for incorrect rtn and `=` -> `:` typos in bindings)
 - #154155 (tests/ui/async-await/drop-option-future.rs: New regression test)
 - #146961 (Allow passing `expr` metavariable as `cfg` predicate)
 - #154118 (don't suggest non-deriveable traits for unions)
 - #154120 (Start migrating `DecorateDiagCompat::Builtin` items to `DecorateDiagCompat::Dynamic`)
 - #154156 (Moving issue-52049 to borrowck)
@rust-bors rust-bors bot merged commit b9f8e25 into rust-lang:main Mar 21, 2026
11 checks passed
@rustbot rustbot added this to the 1.96.0 milestone Mar 21, 2026
@Jules-Bertholet Jules-Bertholet deleted the expr-cfg branch March 21, 2026 16:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-attributes Area: Attributes (`#[…]`, `#![…]`) A-cfg Area: `cfg` conditional compilation A-macros Area: All kinds of macros (custom derive, macro_rules!, proc macros, ..) disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. finished-final-comment-period The final comment period is finished for this PR / Issue. I-lang-radar Items that are on lang's radar and will need eventual work or consideration. needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-lang Relevant to the language team

Projects

None yet

Development

Successfully merging this pull request may close these issues.