rustc_attr_parsing/attributes/
stability.rs

1use std::num::NonZero;
2
3use rustc_errors::ErrorGuaranteed;
4use rustc_feature::template;
5use rustc_hir::attrs::AttributeKind;
6use rustc_hir::{
7    DefaultBodyStability, PartialConstStability, Stability, StabilityLevel, StableSince,
8    UnstableReason, VERSION_PLACEHOLDER,
9};
10use rustc_span::{Ident, Span, Symbol, sym};
11
12use super::util::parse_version;
13use super::{AcceptMapping, AttributeParser, OnDuplicate};
14use crate::attributes::NoArgsAttributeParser;
15use crate::context::{AcceptContext, FinalizeContext, Stage};
16use crate::parser::{ArgParser, MetaItemParser};
17use crate::session_diagnostics::{self, UnsupportedLiteralReason};
18
19macro_rules! reject_outside_std {
20    ($cx: ident) => {
21        // Emit errors for non-staged-api crates.
22        if !$cx.features().staged_api() {
23            $cx.emit_err(session_diagnostics::StabilityOutsideStd { span: $cx.attr_span });
24            return;
25        }
26    };
27}
28
29#[derive(Default)]
30pub(crate) struct StabilityParser {
31    allowed_through_unstable_modules: Option<Symbol>,
32    stability: Option<(Stability, Span)>,
33}
34
35impl StabilityParser {
36    /// Checks, and emits an error when a stability (or unstability) was already set, which would be a duplicate.
37    fn check_duplicate<S: Stage>(&self, cx: &AcceptContext<'_, '_, S>) -> bool {
38        if let Some((_, _)) = self.stability {
39            cx.emit_err(session_diagnostics::MultipleStabilityLevels { span: cx.attr_span });
40            true
41        } else {
42            false
43        }
44    }
45}
46
47impl<S: Stage> AttributeParser<S> for StabilityParser {
48    const ATTRIBUTES: AcceptMapping<Self, S> = &[
49        (
50            &[sym::stable],
51            template!(List: r#"feature = "name", since = "version""#),
52            |this, cx, args| {
53                reject_outside_std!(cx);
54                if !this.check_duplicate(cx)
55                    && let Some((feature, level)) = parse_stability(cx, args)
56                {
57                    this.stability = Some((Stability { level, feature }, cx.attr_span));
58                }
59            },
60        ),
61        (
62            &[sym::unstable],
63            template!(List: r#"feature = "name", reason = "...", issue = "N""#),
64            |this, cx, args| {
65                reject_outside_std!(cx);
66                if !this.check_duplicate(cx)
67                    && let Some((feature, level)) = parse_unstability(cx, args)
68                {
69                    this.stability = Some((Stability { level, feature }, cx.attr_span));
70                }
71            },
72        ),
73        (
74            &[sym::rustc_allowed_through_unstable_modules],
75            template!(NameValueStr: "deprecation message"),
76            |this, cx, args| {
77                reject_outside_std!(cx);
78                let Some(nv) = args.name_value() else {
79                    cx.expected_name_value(cx.attr_span, None);
80                    return;
81                };
82                let Some(value_str) = nv.value_as_str() else {
83                    cx.expected_string_literal(nv.value_span, Some(nv.value_as_lit()));
84                    return;
85                };
86                this.allowed_through_unstable_modules = Some(value_str);
87            },
88        ),
89    ];
90
91    fn finalize(mut self, cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
92        if let Some(atum) = self.allowed_through_unstable_modules {
93            if let Some((
94                Stability {
95                    level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
96                    ..
97                },
98                _,
99            )) = self.stability
100            {
101                *allowed_through_unstable_modules = Some(atum);
102            } else {
103                cx.dcx().emit_err(session_diagnostics::RustcAllowedUnstablePairing {
104                    span: cx.target_span,
105                });
106            }
107        }
108
109        if let Some((Stability { level: StabilityLevel::Stable { .. }, .. }, _)) = self.stability {
110            for other_attr in cx.all_attrs {
111                if other_attr.word_is(sym::unstable_feature_bound) {
112                    cx.emit_err(session_diagnostics::UnstableFeatureBoundIncompatibleStability {
113                        span: cx.target_span,
114                    });
115                }
116            }
117        }
118
119        let (stability, span) = self.stability?;
120
121        Some(AttributeKind::Stability { stability, span })
122    }
123}
124
125// FIXME(jdonszelmann) change to Single
126#[derive(Default)]
127pub(crate) struct BodyStabilityParser {
128    stability: Option<(DefaultBodyStability, Span)>,
129}
130
131impl<S: Stage> AttributeParser<S> for BodyStabilityParser {
132    const ATTRIBUTES: AcceptMapping<Self, S> = &[(
133        &[sym::rustc_default_body_unstable],
134        template!(List: r#"feature = "name", reason = "...", issue = "N""#),
135        |this, cx, args| {
136            reject_outside_std!(cx);
137            if this.stability.is_some() {
138                cx.dcx()
139                    .emit_err(session_diagnostics::MultipleStabilityLevels { span: cx.attr_span });
140            } else if let Some((feature, level)) = parse_unstability(cx, args) {
141                this.stability = Some((DefaultBodyStability { level, feature }, cx.attr_span));
142            }
143        },
144    )];
145
146    fn finalize(self, _cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
147        let (stability, span) = self.stability?;
148
149        Some(AttributeKind::BodyStability { stability, span })
150    }
151}
152
153pub(crate) struct ConstStabilityIndirectParser;
154impl<S: Stage> NoArgsAttributeParser<S> for ConstStabilityIndirectParser {
155    const PATH: &[Symbol] = &[sym::rustc_const_stable_indirect];
156    const ON_DUPLICATE: OnDuplicate<S> = OnDuplicate::Ignore;
157    const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::ConstStabilityIndirect;
158}
159
160#[derive(Default)]
161pub(crate) struct ConstStabilityParser {
162    promotable: bool,
163    stability: Option<(PartialConstStability, Span)>,
164}
165
166impl ConstStabilityParser {
167    /// Checks, and emits an error when a stability (or unstability) was already set, which would be a duplicate.
168    fn check_duplicate<S: Stage>(&self, cx: &AcceptContext<'_, '_, S>) -> bool {
169        if let Some((_, _)) = self.stability {
170            cx.emit_err(session_diagnostics::MultipleStabilityLevels { span: cx.attr_span });
171            true
172        } else {
173            false
174        }
175    }
176}
177
178impl<S: Stage> AttributeParser<S> for ConstStabilityParser {
179    const ATTRIBUTES: AcceptMapping<Self, S> = &[
180        (&[sym::rustc_const_stable], template!(List: r#"feature = "name""#), |this, cx, args| {
181            reject_outside_std!(cx);
182
183            if !this.check_duplicate(cx)
184                && let Some((feature, level)) = parse_stability(cx, args)
185            {
186                this.stability = Some((
187                    PartialConstStability { level, feature, promotable: false },
188                    cx.attr_span,
189                ));
190            }
191        }),
192        (&[sym::rustc_const_unstable], template!(List: r#"feature = "name""#), |this, cx, args| {
193            reject_outside_std!(cx);
194            if !this.check_duplicate(cx)
195                && let Some((feature, level)) = parse_unstability(cx, args)
196            {
197                this.stability = Some((
198                    PartialConstStability { level, feature, promotable: false },
199                    cx.attr_span,
200                ));
201            }
202        }),
203        (&[sym::rustc_promotable], template!(Word), |this, cx, _| {
204            reject_outside_std!(cx);
205            this.promotable = true;
206        }),
207    ];
208
209    fn finalize(mut self, cx: &FinalizeContext<'_, '_, S>) -> Option<AttributeKind> {
210        if self.promotable {
211            if let Some((ref mut stab, _)) = self.stability {
212                stab.promotable = true;
213            } else {
214                cx.dcx()
215                    .emit_err(session_diagnostics::RustcPromotablePairing { span: cx.target_span });
216            }
217        }
218
219        let (stability, span) = self.stability?;
220
221        Some(AttributeKind::ConstStability { stability, span })
222    }
223}
224
225/// Tries to insert the value of a `key = value` meta item into an option.
226///
227/// Emits an error when either the option was already Some, or the arguments weren't of form
228/// `name = value`
229fn insert_value_into_option_or_error<S: Stage>(
230    cx: &AcceptContext<'_, '_, S>,
231    param: &MetaItemParser<'_>,
232    item: &mut Option<Symbol>,
233    name: Ident,
234) -> Option<()> {
235    if item.is_some() {
236        cx.duplicate_key(name.span, name.name);
237        None
238    } else if let Some(v) = param.args().name_value()
239        && let Some(s) = v.value_as_str()
240    {
241        *item = Some(s);
242        Some(())
243    } else {
244        cx.expected_name_value(param.span(), Some(name.name));
245        None
246    }
247}
248
249/// Read the content of a `stable`/`rustc_const_stable` attribute, and return the feature name and
250/// its stability information.
251pub(crate) fn parse_stability<S: Stage>(
252    cx: &AcceptContext<'_, '_, S>,
253    args: &ArgParser<'_>,
254) -> Option<(Symbol, StabilityLevel)> {
255    let mut feature = None;
256    let mut since = None;
257
258    let ArgParser::List(list) = args else {
259        cx.expected_list(cx.attr_span);
260        return None;
261    };
262
263    for param in list.mixed() {
264        let param_span = param.span();
265        let Some(param) = param.meta_item() else {
266            cx.emit_err(session_diagnostics::UnsupportedLiteral {
267                span: param_span,
268                reason: UnsupportedLiteralReason::Generic,
269                is_bytestr: false,
270                start_point_span: cx.sess().source_map().start_point(param_span),
271            });
272            return None;
273        };
274
275        let word = param.path().word();
276        match word.map(|i| i.name) {
277            Some(sym::feature) => {
278                insert_value_into_option_or_error(cx, &param, &mut feature, word.unwrap())?
279            }
280            Some(sym::since) => {
281                insert_value_into_option_or_error(cx, &param, &mut since, word.unwrap())?
282            }
283            _ => {
284                cx.emit_err(session_diagnostics::UnknownMetaItem {
285                    span: param_span,
286                    item: param.path().to_string(),
287                    expected: &["feature", "since"],
288                });
289                return None;
290            }
291        }
292    }
293
294    let feature = match feature {
295        Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
296        Some(_bad_feature) => {
297            Err(cx.emit_err(session_diagnostics::NonIdentFeature { span: cx.attr_span }))
298        }
299        None => Err(cx.emit_err(session_diagnostics::MissingFeature { span: cx.attr_span })),
300    };
301
302    let since = if let Some(since) = since {
303        if since.as_str() == VERSION_PLACEHOLDER {
304            StableSince::Current
305        } else if let Some(version) = parse_version(since) {
306            StableSince::Version(version)
307        } else {
308            let err = cx.emit_err(session_diagnostics::InvalidSince { span: cx.attr_span });
309            StableSince::Err(err)
310        }
311    } else {
312        let err = cx.emit_err(session_diagnostics::MissingSince { span: cx.attr_span });
313        StableSince::Err(err)
314    };
315
316    match feature {
317        Ok(feature) => {
318            let level = StabilityLevel::Stable { since, allowed_through_unstable_modules: None };
319            Some((feature, level))
320        }
321        Err(ErrorGuaranteed { .. }) => None,
322    }
323}
324
325// Read the content of a `unstable`/`rustc_const_unstable`/`rustc_default_body_unstable`
326/// attribute, and return the feature name and its stability information.
327pub(crate) fn parse_unstability<S: Stage>(
328    cx: &AcceptContext<'_, '_, S>,
329    args: &ArgParser<'_>,
330) -> Option<(Symbol, StabilityLevel)> {
331    let mut feature = None;
332    let mut reason = None;
333    let mut issue = None;
334    let mut issue_num = None;
335    let mut is_soft = false;
336    let mut implied_by = None;
337    let mut old_name = None;
338
339    let ArgParser::List(list) = args else {
340        cx.expected_list(cx.attr_span);
341        return None;
342    };
343
344    for param in list.mixed() {
345        let Some(param) = param.meta_item() else {
346            cx.emit_err(session_diagnostics::UnsupportedLiteral {
347                span: param.span(),
348                reason: UnsupportedLiteralReason::Generic,
349                is_bytestr: false,
350                start_point_span: cx.sess().source_map().start_point(param.span()),
351            });
352            return None;
353        };
354
355        let word = param.path().word();
356        match word.map(|i| i.name) {
357            Some(sym::feature) => {
358                insert_value_into_option_or_error(cx, &param, &mut feature, word.unwrap())?
359            }
360            Some(sym::reason) => {
361                insert_value_into_option_or_error(cx, &param, &mut reason, word.unwrap())?
362            }
363            Some(sym::issue) => {
364                insert_value_into_option_or_error(cx, &param, &mut issue, word.unwrap())?;
365
366                // These unwraps are safe because `insert_value_into_option_or_error` ensures the meta item
367                // is a name/value pair string literal.
368                issue_num = match issue.unwrap().as_str() {
369                    "none" => None,
370                    issue_str => match issue_str.parse::<NonZero<u32>>() {
371                        Ok(num) => Some(num),
372                        Err(err) => {
373                            cx.emit_err(
374                                session_diagnostics::InvalidIssueString {
375                                    span: param.span(),
376                                    cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind(
377                                        param.args().name_value().unwrap().value_span,
378                                        err.kind(),
379                                    ),
380                                },
381                            );
382                            return None;
383                        }
384                    },
385                };
386            }
387            Some(sym::soft) => {
388                if let Err(span) = args.no_args() {
389                    cx.emit_err(session_diagnostics::SoftNoArgs { span });
390                }
391                is_soft = true;
392            }
393            Some(sym::implied_by) => {
394                insert_value_into_option_or_error(cx, &param, &mut implied_by, word.unwrap())?
395            }
396            Some(sym::old_name) => {
397                insert_value_into_option_or_error(cx, &param, &mut old_name, word.unwrap())?
398            }
399            _ => {
400                cx.emit_err(session_diagnostics::UnknownMetaItem {
401                    span: param.span(),
402                    item: param.path().to_string(),
403                    expected: &["feature", "reason", "issue", "soft", "implied_by", "old_name"],
404                });
405                return None;
406            }
407        }
408    }
409
410    let feature = match feature {
411        Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
412        Some(_bad_feature) => {
413            Err(cx.emit_err(session_diagnostics::NonIdentFeature { span: cx.attr_span }))
414        }
415        None => Err(cx.emit_err(session_diagnostics::MissingFeature { span: cx.attr_span })),
416    };
417
418    let issue =
419        issue.ok_or_else(|| cx.emit_err(session_diagnostics::MissingIssue { span: cx.attr_span }));
420
421    match (feature, issue) {
422        (Ok(feature), Ok(_)) => {
423            let level = StabilityLevel::Unstable {
424                reason: UnstableReason::from_opt_reason(reason),
425                issue: issue_num,
426                is_soft,
427                implied_by,
428                old_name,
429            };
430            Some((feature, level))
431        }
432        (Err(ErrorGuaranteed { .. }), _) | (_, Err(ErrorGuaranteed { .. })) => None,
433    }
434}