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 =
330                        CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
331                    e.with_span_suggestions(
332                        cfg_attr.span,
333                        "must be of the form",
334                        suggestions,
335                        Applicability::HasPlaceholders,
336                    )
337                    .with_note(format!(
338                        "for more information, visit <{}>",
339                        CFG_ATTR_TEMPLATE.docs.expect("cfg_attr has docs")
340                    ))
341                    .emit();
342                }
343            }
344        }
345        _ => {
346            let (span, reason) = if let ast::AttrArgs::Delimited(ast::DelimArgs { dspan, .. }) =
347                cfg_attr.get_normal_item().args
348            {
349                (dspan.entire(), AttributeParseErrorReason::ExpectedAtLeastOneArgument)
350            } else {
351                (cfg_attr.span, AttributeParseErrorReason::ExpectedList)
352            };
353
354            sess.dcx().emit_err(AttributeParseError {
355                span,
356                attr_span: cfg_attr.span,
357                template: CFG_ATTR_TEMPLATE,
358                attribute: AttrPath::from_ast(&cfg_attr.get_normal_item().path),
359                reason,
360                suggestions: CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
361            });
362        }
363    }
364    None
365}
366
367fn check_cfg_attr_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
368    if let Delimiter::Parenthesis = delim {
369        return;
370    }
371    psess.dcx().emit_err(CfgAttrBadDelim {
372        span: span.entire(),
373        sugg: MetaBadDelimSugg { open: span.open, close: span.close },
374    });
375}
376
377/// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
378fn parse_cfg_attr_internal<'a>(
379    parser: &mut Parser<'a>,
380    sess: &'a Session,
381    features: Option<&Features>,
382    attribute: &Attribute,
383) -> PResult<'a, (CfgEntry, Vec<(ast::AttrItem, Span)>)> {
384    // Parse cfg predicate
385    let pred_start = parser.token.span;
386    let meta = MetaItemOrLitParser::parse_single(parser, ShouldEmit::ErrorsAndLints)?;
387    let pred_span = pred_start.with_hi(parser.token.span.hi());
388
389    let cfg_predicate = AttributeParser::parse_single_args(
390        sess,
391        attribute.span,
392        attribute.get_normal_item().span(),
393        attribute.style,
394        AttrPath {
395            segments: attribute
396                .ident_path()
397                .expect("cfg_attr is not a doc comment")
398                .into_boxed_slice(),
399            span: attribute.span,
400        },
401        pred_span,
402        CRATE_NODE_ID,
403        features,
404        ShouldEmit::ErrorsAndLints,
405        &meta,
406        parse_cfg_entry,
407        &CFG_ATTR_TEMPLATE,
408    )
409    .ok_or_else(|| {
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}