Skip to main content

rustc_attr_parsing/attributes/
cfg_select.rs

1use rustc_ast::token::Token;
2use rustc_ast::tokenstream::TokenStream;
3use rustc_ast::{AttrStyle, NodeId, token};
4use rustc_data_structures::fx::FxHashMap;
5use rustc_errors::Diagnostic;
6use rustc_feature::{AttributeTemplate, Features};
7use rustc_hir::attrs::CfgEntry;
8use rustc_hir::{AttrPath, Target};
9use rustc_parse::exp;
10use rustc_parse::parser::{Parser, Recovery};
11use rustc_session::Session;
12use rustc_session::lint::builtin::UNREACHABLE_CFG_SELECT_PREDICATES;
13use rustc_span::{ErrorGuaranteed, Span, Symbol, sym};
14
15use crate::parser::{AllowExprMetavar, MetaItemOrLitParser};
16use crate::{AttributeParser, ParsedDescription, ShouldEmit, errors, parse_cfg_entry};
17
18#[derive(#[automatically_derived]
impl ::core::clone::Clone for CfgSelectPredicate {
    #[inline]
    fn clone(&self) -> CfgSelectPredicate {
        match self {
            CfgSelectPredicate::Cfg(__self_0) =>
                CfgSelectPredicate::Cfg(::core::clone::Clone::clone(__self_0)),
            CfgSelectPredicate::Wildcard(__self_0) =>
                CfgSelectPredicate::Wildcard(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
19pub enum CfgSelectPredicate {
20    Cfg(CfgEntry),
21    Wildcard(Token),
22}
23
24impl CfgSelectPredicate {
25    fn span(&self) -> Span {
26        match self {
27            CfgSelectPredicate::Cfg(cfg_entry) => cfg_entry.span(),
28            CfgSelectPredicate::Wildcard(token) => token.span,
29        }
30    }
31}
32
33#[derive(#[automatically_derived]
impl ::core::default::Default for CfgSelectBranches {
    #[inline]
    fn default() -> CfgSelectBranches {
        CfgSelectBranches {
            reachable: ::core::default::Default::default(),
            wildcard: ::core::default::Default::default(),
            unreachable: ::core::default::Default::default(),
        }
    }
}Default)]
34pub struct CfgSelectBranches {
35    /// All the conditional branches.
36    pub reachable: Vec<(CfgEntry, TokenStream, Span)>,
37    /// The first wildcard `_ => { ... }` branch.
38    pub wildcard: Option<(Token, TokenStream, Span)>,
39    /// All branches after the first wildcard, including further wildcards.
40    /// These branches are kept for formatting.
41    pub unreachable: Vec<(CfgSelectPredicate, TokenStream, Span)>,
42}
43
44impl CfgSelectBranches {
45    /// Removes the top-most branch for which `predicate` returns `true`,
46    /// or the wildcard if none of the reachable branches satisfied the predicate.
47    pub fn pop_first_match<F>(&mut self, predicate: F) -> Option<(TokenStream, Span)>
48    where
49        F: Fn(&CfgEntry) -> bool,
50    {
51        for (index, (cfg, _, _)) in self.reachable.iter().enumerate() {
52            if predicate(cfg) {
53                let matched = self.reachable.remove(index);
54                return Some((matched.1, matched.2));
55            }
56        }
57
58        self.wildcard.take().map(|(_, tts, span)| (tts, span))
59    }
60
61    /// Consume this value and iterate over all the `TokenStream`s that it stores.
62    pub fn into_iter_tts(self) -> impl Iterator<Item = (TokenStream, Span)> {
63        let it1 = self.reachable.into_iter().map(|(_, tts, span)| (tts, span));
64        let it2 = self.wildcard.into_iter().map(|(_, tts, span)| (tts, span));
65        let it3 = self.unreachable.into_iter().map(|(_, tts, span)| (tts, span));
66
67        it1.chain(it2).chain(it3)
68    }
69}
70
71pub fn parse_cfg_select(
72    p: &mut Parser<'_>,
73    sess: &Session,
74    features: Option<&Features>,
75    lint_node_id: NodeId,
76) -> Result<CfgSelectBranches, ErrorGuaranteed> {
77    let mut branches = CfgSelectBranches::default();
78
79    while p.token != token::Eof {
80        if p.eat_keyword(::rustc_parse::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Underscore,
    token_type: ::rustc_parse::parser::token_type::TokenType::KwUnderscore,
}exp!(Underscore)) {
81            let underscore = p.prev_token;
82            p.expect(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::FatArrow,
    token_type: ::rustc_parse::parser::token_type::TokenType::FatArrow,
}exp!(FatArrow)).map_err(|e| e.emit())?;
83
84            let tts = p.parse_delimited_token_tree().map_err(|e| e.emit())?;
85            let span = underscore.span.to(p.token.span);
86
87            match branches.wildcard {
88                None => branches.wildcard = Some((underscore, tts, span)),
89                Some(_) => {
90                    branches.unreachable.push((CfgSelectPredicate::Wildcard(underscore), tts, span))
91                }
92            }
93        } else {
94            let meta = MetaItemOrLitParser::parse_single(
95                p,
96                ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
97                AllowExprMetavar::Yes,
98            )
99            .map_err(|diag| diag.emit())?;
100            let cfg_span = meta.span();
101            let cfg = AttributeParser::parse_single_args(
102                sess,
103                cfg_span,
104                cfg_span,
105                AttrStyle::Inner,
106                AttrPath { segments: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::cfg_select]))vec![sym::cfg_select].into_boxed_slice(), span: cfg_span },
107                None,
108                ParsedDescription::Macro,
109                cfg_span,
110                lint_node_id,
111                // Doesn't matter what the target actually is here.
112                Target::Crate,
113                features,
114                ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
115                &meta,
116                parse_cfg_entry,
117                &AttributeTemplate::default(),
118            )?;
119
120            p.expect(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::FatArrow,
    token_type: ::rustc_parse::parser::token_type::TokenType::FatArrow,
}exp!(FatArrow)).map_err(|e| e.emit())?;
121
122            let tts = p.parse_delimited_token_tree().map_err(|e| e.emit())?;
123            let span = cfg_span.to(p.token.span);
124
125            match branches.wildcard {
126                None => branches.reachable.push((cfg, tts, span)),
127                Some(_) => branches.unreachable.push((CfgSelectPredicate::Cfg(cfg), tts, span)),
128            }
129        }
130    }
131
132    let it = branches
133        .reachable
134        .iter()
135        .map(|(entry, _, _)| CfgSelectPredicate::Cfg(entry.clone()))
136        .chain(branches.wildcard.as_ref().map(|(t, _, _)| CfgSelectPredicate::Wildcard(*t)))
137        .chain(branches.unreachable.iter().map(|(entry, _, _)| CfgSelectPredicate::clone(entry)));
138
139    lint_unreachable(p, it, lint_node_id);
140
141    Ok(branches)
142}
143
144fn lint_unreachable(
145    p: &mut Parser<'_>,
146    predicates: impl Iterator<Item = CfgSelectPredicate>,
147    lint_node_id: NodeId,
148) {
149    // Symbols that have a known value.
150    let mut known = FxHashMap::<Symbol, bool>::default();
151    let mut wildcard_span = None;
152    let mut it = predicates;
153
154    let branch_is_unreachable = |predicate: CfgSelectPredicate, wildcard_span| {
155        let span = predicate.span();
156        p.psess.dyn_buffer_lint(
157            UNREACHABLE_CFG_SELECT_PREDICATES,
158            span,
159            lint_node_id,
160            move |dcx, level| match wildcard_span {
161                Some(wildcard_span) => {
162                    errors::UnreachableCfgSelectPredicateWildcard { span, wildcard_span }
163                        .into_diag(dcx, level)
164                }
165                None => errors::UnreachableCfgSelectPredicate { span }.into_diag(dcx, level),
166            },
167        );
168    };
169
170    for predicate in &mut it {
171        let CfgSelectPredicate::Cfg(ref cfg_entry) = predicate else {
172            wildcard_span = Some(predicate.span());
173            break;
174        };
175
176        match cfg_entry {
177            CfgEntry::Bool(true, _) => {
178                wildcard_span = Some(predicate.span());
179                break;
180            }
181            CfgEntry::Bool(false, _) => continue,
182            CfgEntry::NameValue { name, value, .. } => match value {
183                None => {
184                    // `name` will be false in all subsequent branches.
185                    let current = known.insert(*name, false);
186
187                    match current {
188                        None => continue,
189                        Some(false) => {
190                            branch_is_unreachable(predicate, None);
191                            break;
192                        }
193                        Some(true) => {
194                            // this branch will be taken, so all subsequent branches are unreachable.
195                            break;
196                        }
197                    }
198                }
199                Some(_) => { /* for now we don't bother solving these */ }
200            },
201            CfgEntry::Not(inner, _) => match &**inner {
202                CfgEntry::NameValue { name, value: None, .. } => {
203                    // `name` will be true in all subsequent branches.
204                    let current = known.insert(*name, true);
205
206                    match current {
207                        None => continue,
208                        Some(true) => {
209                            branch_is_unreachable(predicate, None);
210                            break;
211                        }
212                        Some(false) => {
213                            // this branch will be taken, so all subsequent branches are unreachable.
214                            break;
215                        }
216                    }
217                }
218                _ => { /* for now we don't bother solving these */ }
219            },
220            CfgEntry::All(_, _) | CfgEntry::Any(_, _) => {
221                /* for now we don't bother solving these */
222            }
223            CfgEntry::Version(..) => { /* don't bother solving these */ }
224        }
225    }
226
227    for predicate in it {
228        branch_is_unreachable(predicate, wildcard_span)
229    }
230}