rustc_attr_parsing/attributes/
cfg.rs

1use rustc_ast::token::Delimiter;
2use rustc_ast::tokenstream::DelimSpan;
3use rustc_ast::{AttrItem, Attribute, CRATE_NODE_ID, LitKind, NodeId, ast, token};
4use rustc_errors::{Applicability, PResult};
5use rustc_feature::{AttributeTemplate, Features, template};
6use rustc_hir::attrs::CfgEntry;
7use rustc_hir::{AttrPath, RustcVersion};
8use rustc_parse::parser::{ForceCollect, Parser};
9use rustc_parse::{exp, parse_in};
10use rustc_session::Session;
11use rustc_session::config::ExpectedValues;
12use rustc_session::lint::BuiltinLintDiag;
13use rustc_session::lint::builtin::UNEXPECTED_CFGS;
14use rustc_session::parse::{ParseSess, feature_err};
15use rustc_span::{Span, Symbol, sym};
16use thin_vec::ThinVec;
17
18use crate::context::{AcceptContext, ShouldEmit, Stage};
19use crate::parser::{ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser};
20use crate::session_diagnostics::{
21    AttributeParseError, AttributeParseErrorReason, CfgAttrBadDelim, MetaBadDelimSugg,
22};
23use crate::{
24    AttributeParser, CfgMatchesLintEmitter, fluent_generated, parse_version, session_diagnostics,
25    try_gate_cfg,
26};
27
28pub const CFG_TEMPLATE: AttributeTemplate = template!(
29    List: &["predicate"],
30    "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute"
31);
32
33const CFG_ATTR_TEMPLATE: AttributeTemplate = template!(
34    List: &["predicate, attr1, attr2, ..."],
35    "https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute"
36);
37
38pub fn parse_cfg<'c, S: Stage>(
39    cx: &'c mut AcceptContext<'_, '_, S>,
40    args: &'c ArgParser<'_>,
41) -> Option<CfgEntry> {
42    let ArgParser::List(list) = args else {
43        cx.expected_list(cx.attr_span);
44        return None;
45    };
46    let Some(single) = list.single() else {
47        cx.expected_single_argument(list.span);
48        return None;
49    };
50    parse_cfg_entry(cx, single)
51}
52
53pub(crate) fn parse_cfg_entry<S: Stage>(
54    cx: &mut AcceptContext<'_, '_, S>,
55    item: &MetaItemOrLitParser<'_>,
56) -> Option<CfgEntry> {
57    Some(match item {
58        MetaItemOrLitParser::MetaItemParser(meta) => match meta.args() {
59            ArgParser::List(list) => match meta.path().word_sym() {
60                Some(sym::not) => {
61                    let Some(single) = list.single() else {
62                        cx.expected_single_argument(list.span);
63                        return None;
64                    };
65                    CfgEntry::Not(Box::new(parse_cfg_entry(cx, single)?), list.span)
66                }
67                Some(sym::any) => CfgEntry::Any(
68                    list.mixed().flat_map(|sub_item| parse_cfg_entry(cx, sub_item)).collect(),
69                    list.span,
70                ),
71                Some(sym::all) => CfgEntry::All(
72                    list.mixed().flat_map(|sub_item| parse_cfg_entry(cx, sub_item)).collect(),
73                    list.span,
74                ),
75                Some(sym::target) => parse_cfg_entry_target(cx, list, meta.span())?,
76                Some(sym::version) => parse_cfg_entry_version(cx, list, meta.span())?,
77                _ => {
78                    cx.emit_err(session_diagnostics::InvalidPredicate {
79                        span: meta.span(),
80                        predicate: meta.path().to_string(),
81                    });
82                    return None;
83                }
84            },
85            a @ (ArgParser::NoArgs | ArgParser::NameValue(_)) => {
86                let Some(name) = meta.path().word_sym() else {
87                    cx.expected_identifier(meta.path().span());
88                    return None;
89                };
90                parse_name_value(name, meta.path().span(), a.name_value(), meta.span(), cx)?
91            }
92        },
93        MetaItemOrLitParser::Lit(lit) => match lit.kind {
94            LitKind::Bool(b) => CfgEntry::Bool(b, lit.span),
95            _ => {
96                cx.expected_identifier(lit.span);
97                return None;
98            }
99        },
100        MetaItemOrLitParser::Err(_, _) => return None,
101    })
102}
103
104fn parse_cfg_entry_version<S: Stage>(
105    cx: &mut AcceptContext<'_, '_, S>,
106    list: &MetaItemListParser<'_>,
107    meta_span: Span,
108) -> Option<CfgEntry> {
109    try_gate_cfg(sym::version, meta_span, cx.sess(), cx.features_option());
110    let Some(version) = list.single() else {
111        cx.emit_err(session_diagnostics::ExpectedSingleVersionLiteral { span: list.span });
112        return None;
113    };
114    let Some(version_lit) = version.lit() else {
115        cx.emit_err(session_diagnostics::ExpectedVersionLiteral { span: version.span() });
116        return None;
117    };
118    let Some(version_str) = version_lit.value_str() else {
119        cx.emit_err(session_diagnostics::ExpectedVersionLiteral { span: version_lit.span });
120        return None;
121    };
122
123    let min_version = parse_version(version_str).or_else(|| {
124        cx.sess()
125            .dcx()
126            .emit_warn(session_diagnostics::UnknownVersionLiteral { span: version_lit.span });
127        None
128    });
129
130    Some(CfgEntry::Version(min_version, list.span))
131}
132
133fn parse_cfg_entry_target<S: Stage>(
134    cx: &mut AcceptContext<'_, '_, S>,
135    list: &MetaItemListParser<'_>,
136    meta_span: Span,
137) -> Option<CfgEntry> {
138    if let Some(features) = cx.features_option()
139        && !features.cfg_target_compact()
140    {
141        feature_err(
142            cx.sess(),
143            sym::cfg_target_compact,
144            meta_span,
145            fluent_generated::attr_parsing_unstable_cfg_target_compact,
146        )
147        .emit();
148    }
149
150    let mut result = ThinVec::new();
151    for sub_item in list.mixed() {
152        // First, validate that this is a NameValue item
153        let Some(sub_item) = sub_item.meta_item() else {
154            cx.expected_name_value(sub_item.span(), None);
155            continue;
156        };
157        let Some(nv) = sub_item.args().name_value() else {
158            cx.expected_name_value(sub_item.span(), None);
159            continue;
160        };
161
162        // Then, parse it as a name-value item
163        let Some(name) = sub_item.path().word_sym() else {
164            cx.expected_identifier(sub_item.path().span());
165            return None;
166        };
167        let name = Symbol::intern(&format!("target_{name}"));
168        if let Some(cfg) =
169            parse_name_value(name, sub_item.path().span(), Some(nv), sub_item.span(), cx)
170        {
171            result.push(cfg);
172        }
173    }
174    Some(CfgEntry::All(result, list.span))
175}
176
177fn parse_name_value<S: Stage>(
178    name: Symbol,
179    name_span: Span,
180    value: Option<&NameValueParser>,
181    span: Span,
182    cx: &mut AcceptContext<'_, '_, S>,
183) -> Option<CfgEntry> {
184    try_gate_cfg(name, span, cx.sess(), cx.features_option());
185
186    let value = match value {
187        None => None,
188        Some(value) => {
189            let Some(value_str) = value.value_as_str() else {
190                cx.expected_string_literal(value.value_span, Some(value.value_as_lit()));
191                return None;
192            };
193            Some((value_str, value.value_span))
194        }
195    };
196
197    Some(CfgEntry::NameValue { name, name_span, value, span })
198}
199
200pub fn eval_config_entry(
201    sess: &Session,
202    cfg_entry: &CfgEntry,
203    id: NodeId,
204    features: Option<&Features>,
205    emit_lints: ShouldEmit,
206) -> EvalConfigResult {
207    match cfg_entry {
208        CfgEntry::All(subs, ..) => {
209            let mut all = None;
210            for sub in subs {
211                let res = eval_config_entry(sess, sub, id, features, emit_lints);
212                // We cannot short-circuit because `eval_config_entry` emits some lints
213                if !res.as_bool() {
214                    all.get_or_insert(res);
215                }
216            }
217            all.unwrap_or_else(|| EvalConfigResult::True)
218        }
219        CfgEntry::Any(subs, span) => {
220            let mut any = None;
221            for sub in subs {
222                let res = eval_config_entry(sess, sub, id, features, emit_lints);
223                // We cannot short-circuit because `eval_config_entry` emits some lints
224                if res.as_bool() {
225                    any.get_or_insert(res);
226                }
227            }
228            any.unwrap_or_else(|| EvalConfigResult::False {
229                reason: cfg_entry.clone(),
230                reason_span: *span,
231            })
232        }
233        CfgEntry::Not(sub, span) => {
234            if eval_config_entry(sess, sub, id, features, emit_lints).as_bool() {
235                EvalConfigResult::False { reason: cfg_entry.clone(), reason_span: *span }
236            } else {
237                EvalConfigResult::True
238            }
239        }
240        CfgEntry::Bool(b, span) => {
241            if *b {
242                EvalConfigResult::True
243            } else {
244                EvalConfigResult::False { reason: cfg_entry.clone(), reason_span: *span }
245            }
246        }
247        CfgEntry::NameValue { name, name_span, value, span } => {
248            if let ShouldEmit::ErrorsAndLints = emit_lints {
249                match sess.psess.check_config.expecteds.get(name) {
250                    Some(ExpectedValues::Some(values))
251                        if !values.contains(&value.map(|(v, _)| v)) =>
252                    {
253                        id.emit_span_lint(
254                            sess,
255                            UNEXPECTED_CFGS,
256                            *span,
257                            BuiltinLintDiag::UnexpectedCfgValue((*name, *name_span), *value),
258                        );
259                    }
260                    None if sess.psess.check_config.exhaustive_names => {
261                        id.emit_span_lint(
262                            sess,
263                            UNEXPECTED_CFGS,
264                            *span,
265                            BuiltinLintDiag::UnexpectedCfgName((*name, *name_span), *value),
266                        );
267                    }
268                    _ => { /* not unexpected */ }
269                }
270            }
271
272            if sess.psess.config.contains(&(*name, value.map(|(v, _)| v))) {
273                EvalConfigResult::True
274            } else {
275                EvalConfigResult::False { reason: cfg_entry.clone(), reason_span: *span }
276            }
277        }
278        CfgEntry::Version(min_version, version_span) => {
279            let Some(min_version) = min_version else {
280                return EvalConfigResult::False {
281                    reason: cfg_entry.clone(),
282                    reason_span: *version_span,
283                };
284            };
285            // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details
286            let min_version_ok = if sess.psess.assume_incomplete_release {
287                RustcVersion::current_overridable() > *min_version
288            } else {
289                RustcVersion::current_overridable() >= *min_version
290            };
291            if min_version_ok {
292                EvalConfigResult::True
293            } else {
294                EvalConfigResult::False { reason: cfg_entry.clone(), reason_span: *version_span }
295            }
296        }
297    }
298}
299
300pub enum EvalConfigResult {
301    True,
302    False { reason: CfgEntry, reason_span: Span },
303}
304
305impl EvalConfigResult {
306    pub fn as_bool(&self) -> bool {
307        match self {
308            EvalConfigResult::True => true,
309            EvalConfigResult::False { .. } => false,
310        }
311    }
312}
313
314pub fn parse_cfg_attr(
315    cfg_attr: &Attribute,
316    sess: &Session,
317    features: Option<&Features>,
318) -> Option<(CfgEntry, Vec<(AttrItem, Span)>)> {
319    match cfg_attr.get_normal_item().args {
320        ast::AttrArgs::Delimited(ast::DelimArgs { dspan, delim, ref tokens })
321            if !tokens.is_empty() =>
322        {
323            check_cfg_attr_bad_delim(&sess.psess, dspan, delim);
324            match parse_in(&sess.psess, tokens.clone(), "`cfg_attr` input", |p| {
325                parse_cfg_attr_internal(p, sess, features, cfg_attr)
326            }) {
327                Ok(r) => return Some(r),
328                Err(e) => {
329                    let suggestions = CFG_ATTR_TEMPLATE.suggestions(cfg_attr.style, sym::cfg_attr);
330                    e.with_span_suggestions(
331                        cfg_attr.span,
332                        "must be of the form",
333                        suggestions,
334                        Applicability::HasPlaceholders,
335                    )
336                    .with_note(format!(
337                        "for more information, visit <{}>",
338                        CFG_ATTR_TEMPLATE.docs.expect("cfg_attr has docs")
339                    ))
340                    .emit();
341                }
342            }
343        }
344        _ => {
345            let (span, reason) = if let ast::AttrArgs::Delimited(ast::DelimArgs { dspan, .. }) =
346                cfg_attr.get_normal_item().args
347            {
348                (dspan.entire(), AttributeParseErrorReason::ExpectedAtLeastOneArgument)
349            } else {
350                (cfg_attr.span, AttributeParseErrorReason::ExpectedList)
351            };
352
353            sess.dcx().emit_err(AttributeParseError {
354                span,
355                attr_span: cfg_attr.span,
356                template: CFG_ATTR_TEMPLATE,
357                attribute: AttrPath::from_ast(&cfg_attr.get_normal_item().path),
358                reason,
359                attr_style: cfg_attr.style,
360            });
361        }
362    }
363    None
364}
365
366fn check_cfg_attr_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
367    if let Delimiter::Parenthesis = delim {
368        return;
369    }
370    psess.dcx().emit_err(CfgAttrBadDelim {
371        span: span.entire(),
372        sugg: MetaBadDelimSugg { open: span.open, close: span.close },
373    });
374}
375
376/// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
377fn parse_cfg_attr_internal<'a>(
378    parser: &mut Parser<'a>,
379    sess: &'a Session,
380    features: Option<&Features>,
381    attribute: &Attribute,
382) -> PResult<'a, (CfgEntry, Vec<(ast::AttrItem, Span)>)> {
383    // Parse cfg predicate
384    let pred_start = parser.token.span;
385    let meta = MetaItemOrLitParser::parse_single(parser, ShouldEmit::ErrorsAndLints)?;
386    let pred_span = pred_start.with_hi(parser.token.span.hi());
387
388    let cfg_predicate = AttributeParser::parse_single_args(
389        sess,
390        attribute.span,
391        attribute.style,
392        AttrPath {
393            segments: attribute
394                .ident_path()
395                .expect("cfg_attr is not a doc comment")
396                .into_boxed_slice(),
397            span: attribute.span,
398        },
399        pred_span,
400        CRATE_NODE_ID,
401        features,
402        ShouldEmit::ErrorsAndLints,
403        &meta,
404        parse_cfg_entry,
405        &CFG_ATTR_TEMPLATE,
406    )
407    .ok_or_else(|| {
408        let mut diag = sess.dcx().struct_err(
409            "cfg_entry parsing failing with `ShouldEmit::ErrorsAndLints` should emit a error.",
410        );
411        diag.downgrade_to_delayed_bug();
412        diag
413    })?;
414
415    parser.expect(exp!(Comma))?;
416
417    // Presumably, the majority of the time there will only be one attr.
418    let mut expanded_attrs = Vec::with_capacity(1);
419    while parser.token != token::Eof {
420        let lo = parser.token.span;
421        let item = parser.parse_attr_item(ForceCollect::Yes)?;
422        expanded_attrs.push((item, lo.to(parser.prev_token.span)));
423        if !parser.eat(exp!(Comma)) {
424            break;
425        }
426    }
427
428    Ok((cfg_predicate, expanded_attrs))
429}