Skip to main content

rustc_attr_parsing/attributes/
cfg.rs

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