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