Skip to main content

rustc_attr_parsing/attributes/
stability.rs

1use std::num::NonZero;
2
3use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target};
4use rustc_attr_ir::{
5    DefaultBodyStability, PartialConstStability, Stability, StabilityLevel, StableSince,
6    UnstableReason, UnstableRemovedFeature, VERSION_PLACEHOLDER,
7};
8use rustc_errors::ErrorGuaranteed;
9use rustc_feature::{ACCEPTED_LANG_FEATURES, AttributeStability};
10
11use super::prelude::*;
12use super::util::parse_version;
13use crate::context::ExpectNameValue;
14use crate::diagnostics;
15
16const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[
17    Allow(Target::Fn),
18    Allow(Target::Struct),
19    Allow(Target::Enum),
20    Allow(Target::Union),
21    Allow(Target::Method(MethodKind::Inherent)),
22    Allow(Target::Method(MethodKind::Trait { body: false })),
23    Allow(Target::Method(MethodKind::Trait { body: true })),
24    Allow(Target::Method(MethodKind::TraitImpl)),
25    Allow(Target::Impl { of_trait: false }),
26    Allow(Target::Impl { of_trait: true }),
27    Allow(Target::MacroDef),
28    Allow(Target::Crate),
29    Allow(Target::Mod),
30    Allow(Target::Use), // FIXME I don't think this does anything?
31    Allow(Target::Const),
32    Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })),
33    Allow(Target::AssocConst(AssocCtxt::Trait)),
34    Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })),
35    Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })),
36    Allow(Target::AssocTy(AssocCtxt::Trait)),
37    Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })),
38    Allow(Target::Trait),
39    Allow(Target::TraitAlias),
40    Allow(Target::TyAlias),
41    Allow(Target::Variant),
42    Allow(Target::Field),
43    Allow(Target::TypeParam),
44    Allow(Target::Static),
45    Allow(Target::ForeignFn),
46    Allow(Target::ForeignStatic),
47    Allow(Target::ForeignTy),
48    Allow(Target::ExternCrate),
49]);
50
51#[derive(#[automatically_derived]impl ::core::default::Default for StabilityParser {
    #[inline]
    fn default() -> Self {
        StabilityParser {
            allowed_through_unstable_modules: ::core::default::Default::default(),
            stability: ::core::default::Default::default(),
        }
    }
}Default)]
52pub(crate) struct StabilityParser {
53    allowed_through_unstable_modules: Option<(Symbol, Symbol)>,
54    stability: Option<(Stability, Span)>,
55}
56
57impl StabilityParser {
58    /// Checks, and emits an error when a stability (or unstability) was already set, which would be a duplicate.
59    fn check_duplicate(&self, cx: &AcceptContext<'_, '_>) -> bool {
60        if let Some((_, _)) = self.stability {
61            cx.emit_err(diagnostics::MultipleStabilityLevels { span: cx.attr_span });
62            true
63        } else {
64            false
65        }
66    }
67}
68
69impl AttributeParser for StabilityParser {
70    const ATTRIBUTES: AcceptMapping<Self> = &[
71        (
72            &[sym::stable],
73            crate::AttributeTemplate {
    word: false,
    list: Some(&[r#"feature = "name", since = "version""#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[r#"feature = "name", since = "version""#]),
74            {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api),
75            |this, cx, args| {
76                if !this.check_duplicate(cx)
77                    && let Some((feature, level)) = parse_stability(cx, args)
78                {
79                    this.stability = Some((Stability { level, feature }, cx.attr_span));
80                }
81            },
82        ),
83        (
84            &[sym::unstable],
85            crate::AttributeTemplate {
    word: false,
    list: Some(&[r#"feature = "name", reason = "...", issue = "N""#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]),
86            {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api),
87            |this, cx, args| {
88                if !this.check_duplicate(cx)
89                    && let Some((feature, level)) = parse_unstability(cx, args)
90                {
91                    this.stability = Some((Stability { level, feature }, cx.attr_span));
92                }
93            },
94        ),
95        (
96            &[sym::rustc_allowed_through_unstable_modules],
97            crate::AttributeTemplate {
    word: false,
    list: Some(&[r#"message = "...", module = "..."#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[r#"message = "...", module = "..."#]),
98            {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api),
99            |this, cx, args| {
100                let Some(list) = cx.expect_list(args, cx.attr_span) else { return };
101                let mut message = None;
102                let mut module = None;
103
104                for item in list.mixed() {
105                    let Some((name, value)) = item.expect_name_value(cx, item.span(), None) else {
106                        return;
107                    };
108                    let Some(value) = cx.expect_string_literal(value) else {
109                        return;
110                    };
111
112                    match name.name {
113                        sym::message => {
114                            if message.is_some() {
115                                cx.adcx().duplicate_key(name.span, name.name);
116                            } else {
117                                message = Some(value)
118                            }
119                        }
120                        sym::module => {
121                            if module.is_some() {
122                                cx.adcx().duplicate_key(name.span, name.name);
123                            } else {
124                                module = Some(value)
125                            }
126                        }
127                        _ => {
128                            cx.adcx().expected_specific_argument(
129                                name.span,
130                                &[sym::message, sym::module],
131                            );
132                        }
133                    }
134                }
135
136                let allowed_through_unstable_modules = try { (message?, module?) };
137                if allowed_through_unstable_modules.is_none() {
138                    cx.emit_err(diagnostics::RustcAtumMissingParams { span: cx.attr_span });
139                }
140
141                this.allowed_through_unstable_modules = allowed_through_unstable_modules;
142            },
143        ),
144    ];
145    const ALLOWED_TARGETS: AllowedTargets<'_> = ALLOWED_TARGETS;
146
147    fn finalize(mut self, cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
148        if let Some(atum) = self.allowed_through_unstable_modules {
149            if let Some((
150                Stability {
151                    level: StabilityLevel::Stable { ref mut allowed_through_unstable_modules, .. },
152                    ..
153                },
154                _,
155            )) = self.stability
156            {
157                *allowed_through_unstable_modules = Some(atum);
158            } else {
159                cx.dcx()
160                    .emit_err(diagnostics::RustcAllowedUnstablePairing { span: cx.target_span });
161            }
162        }
163
164        if let Some((Stability { level: StabilityLevel::Stable { .. }, .. }, _)) = self.stability {
165            for other_attr in cx.all_attrs {
166                if other_attr.word_is(sym::unstable_feature_bound) {
167                    cx.emit_err(diagnostics::UnstableFeatureBoundIncompatibleStability {
168                        span: cx.target_span,
169                    });
170                }
171            }
172        }
173
174        let (stability, span) = self.stability?;
175
176        Some(AttributeKind::Stability { stability, span })
177    }
178}
179
180// FIXME(jdonszelmann) change to Single
181#[derive(#[automatically_derived]impl ::core::default::Default for BodyStabilityParser
    {
    #[inline]
    fn default() -> Self {
        BodyStabilityParser { stability: ::core::default::Default::default() }
    }
}Default)]
182pub(crate) struct BodyStabilityParser {
183    stability: Option<(DefaultBodyStability, Span)>,
184}
185
186impl AttributeParser for BodyStabilityParser {
187    const ATTRIBUTES: AcceptMapping<Self> = &[(
188        &[sym::rustc_default_body_unstable],
189        crate::AttributeTemplate {
    word: false,
    list: Some(&[r#"feature = "name", reason = "...", issue = "N""#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[r#"feature = "name", reason = "...", issue = "N""#]),
190        {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api),
191        |this, cx, args| {
192            if this.stability.is_some() {
193                cx.dcx().emit_err(diagnostics::MultipleStabilityLevels { span: cx.attr_span });
194            } else if let Some((feature, level)) = parse_unstability(cx, args) {
195                this.stability = Some((DefaultBodyStability { level, feature }, cx.attr_span));
196            }
197        },
198    )];
199    const ALLOWED_TARGETS: AllowedTargets<'_> = ALLOWED_TARGETS;
200
201    fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
202        let (stability, span) = self.stability?;
203
204        Some(AttributeKind::RustcBodyStability { stability, span })
205    }
206}
207
208pub(crate) struct RustcConstStableIndirectParser;
209impl NoArgsAttributeParser for RustcConstStableIndirectParser {
210    const PATH: &[Symbol] = &[sym::rustc_const_stable_indirect];
211    const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[
212        Allow(Target::Fn),
213        Allow(Target::Method(MethodKind::Inherent)),
214    ]);
215    const STABILITY: AttributeStability = {
    _ = rustc_feature::Features::rustc_attrs;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::rustc_attrs,
        notes: &[],
    }
}unstable!(rustc_attrs);
216    const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcConstStableIndirect;
217}
218
219#[derive(#[automatically_derived]impl ::core::default::Default for ConstStabilityParser
    {
    #[inline]
    fn default() -> Self {
        ConstStabilityParser {
            promotable: ::core::default::Default::default(),
            stability: ::core::default::Default::default(),
        }
    }
}Default)]
220pub(crate) struct ConstStabilityParser {
221    promotable: bool,
222    stability: Option<(PartialConstStability, Span)>,
223}
224
225impl ConstStabilityParser {
226    /// Checks, and emits an error when a stability (or unstability) was already set, which would be a duplicate.
227    fn check_duplicate(&self, cx: &AcceptContext<'_, '_>) -> bool {
228        if let Some((_, _)) = self.stability {
229            cx.emit_err(diagnostics::MultipleStabilityLevels { span: cx.attr_span });
230            true
231        } else {
232            false
233        }
234    }
235}
236
237impl AttributeParser for ConstStabilityParser {
238    const ATTRIBUTES: AcceptMapping<Self> = &[
239        (
240            &[sym::rustc_const_stable],
241            crate::AttributeTemplate {
    word: false,
    list: Some(&[r#"feature = "name""#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[r#"feature = "name""#]),
242            {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api),
243            |this, cx, args| {
244                if !this.check_duplicate(cx)
245                    && let Some((feature, level)) = parse_stability(cx, args)
246                {
247                    this.stability = Some((
248                        PartialConstStability { level, feature, promotable: false },
249                        cx.attr_path.span,
250                    ));
251                }
252            },
253        ),
254        (
255            &[sym::rustc_const_unstable],
256            crate::AttributeTemplate {
    word: false,
    list: Some(&[r#"feature = "name""#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[r#"feature = "name""#]),
257            {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api),
258            |this, cx, args| {
259                if !this.check_duplicate(cx)
260                    && let Some((feature, level)) = parse_unstability(cx, args)
261                {
262                    this.stability = Some((
263                        PartialConstStability { level, feature, promotable: false },
264                        cx.attr_path.span,
265                    ));
266                }
267            },
268        ),
269        (&[sym::rustc_promotable], crate::AttributeTemplate {
    word: true,
    list: None,
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(Word), {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api), |this, _cx, _| {
270            this.promotable = true;
271        }),
272    ];
273    const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[
274        Allow(Target::Fn),
275        Allow(Target::Method(MethodKind::Inherent)),
276        Allow(Target::Method(MethodKind::TraitImpl)),
277        Allow(Target::Method(MethodKind::Trait { body: true })),
278        Allow(Target::Impl { of_trait: false }),
279        Allow(Target::Impl { of_trait: true }),
280        Allow(Target::Use), // FIXME I don't think this does anything?
281        Allow(Target::Const),
282        Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })),
283        Allow(Target::AssocConst(AssocCtxt::Trait)),
284        Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })),
285        Allow(Target::Trait),
286        Allow(Target::Static),
287        Allow(Target::Crate),
288    ]);
289
290    fn finalize(mut self, cx: &FinalizeContext<'_, '_>) -> Option<AttributeKind> {
291        if self.promotable {
292            if let Some((ref mut stab, _)) = self.stability {
293                stab.promotable = true;
294            } else {
295                cx.dcx().emit_err(diagnostics::RustcPromotablePairing { span: cx.target_span });
296            }
297        }
298
299        let (stability, span) = self.stability?;
300
301        Some(AttributeKind::RustcConstStability { stability, span })
302    }
303}
304
305/// Tries to insert the value of a `key = value` meta item into an option.
306///
307/// Emits an error when either the option was already Some, or the arguments weren't of form
308/// `name = value`
309fn insert_value_into_option_or_error(
310    cx: &mut AcceptContext<'_, '_>,
311    param: &MetaItemParser,
312    item: &mut Option<Symbol>,
313    name: Ident,
314) -> Option<()> {
315    if item.is_some() {
316        cx.adcx().duplicate_key(name.span, name.name);
317        return None;
318    }
319
320    let (_ident, arg) = cx.expect_name_value(param, param.span(), Some(name.name))?;
321    let s = cx.expect_string_literal(arg)?;
322
323    *item = Some(s);
324
325    Some(())
326}
327
328/// Read the content of a `stable`/`rustc_const_stable` attribute, and return the feature name and
329/// its stability information.
330pub(crate) fn parse_stability(
331    cx: &mut AcceptContext<'_, '_>,
332    args: &ArgParser,
333) -> Option<(Symbol, StabilityLevel)> {
334    let mut feature = None;
335    let mut since = None;
336
337    let list = cx.expect_list(args, cx.attr_span)?;
338
339    for param in list.mixed() {
340        let param_span = param.span();
341        let Some(param) = param.meta_item() else {
342            cx.adcx().expected_not_literal(param.span());
343            return None;
344        };
345
346        let word = param.path().word();
347        match word.map(|i| i.name) {
348            Some(sym::feature) => {
349                insert_value_into_option_or_error(cx, param, &mut feature, word.unwrap())?
350            }
351            Some(sym::since) => {
352                insert_value_into_option_or_error(cx, param, &mut since, word.unwrap())?
353            }
354            _ => {
355                cx.adcx().expected_specific_argument(param_span, &[sym::feature, sym::since]);
356                return None;
357            }
358        }
359    }
360
361    let feature = match feature {
362        Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
363        Some(_bad_feature) => Err(cx.emit_err(diagnostics::NonIdentFeature { span: cx.attr_span })),
364        None => Err(cx.emit_err(diagnostics::MissingFeature { span: cx.attr_span })),
365    };
366
367    let since = if let Some(since) = since {
368        if since.as_str() == VERSION_PLACEHOLDER {
369            StableSince::Current
370        } else if let Some(version) = parse_version(since) {
371            StableSince::Version(version)
372        } else {
373            let err = cx.emit_err(diagnostics::InvalidSince { span: cx.attr_span });
374            StableSince::Err(err)
375        }
376    } else {
377        let err = cx.emit_err(diagnostics::MissingSince { span: cx.attr_span });
378        StableSince::Err(err)
379    };
380
381    match feature {
382        Ok(feature) => {
383            let level = StabilityLevel::Stable { since, allowed_through_unstable_modules: None };
384            Some((feature, level))
385        }
386        Err(ErrorGuaranteed { .. }) => None,
387    }
388}
389
390/// Read the content of a `unstable`/`rustc_const_unstable`/`rustc_default_body_unstable`
391/// attribute, and return the feature name and its stability information.
392pub(crate) fn parse_unstability(
393    cx: &mut AcceptContext<'_, '_>,
394    args: &ArgParser,
395) -> Option<(Symbol, StabilityLevel)> {
396    let mut feature = None;
397    let mut reason = None;
398    let mut issue = None;
399    let mut issue_num = None;
400    let mut implied_by = None;
401    let mut old_name = None;
402
403    let list = cx.expect_list(args, cx.attr_span)?;
404
405    for param in list.mixed() {
406        let Some(param) = param.meta_item() else {
407            cx.adcx().expected_not_literal(param.span());
408            return None;
409        };
410
411        let word = param.path().word();
412        match word.map(|i| i.name) {
413            Some(sym::feature) => {
414                insert_value_into_option_or_error(cx, param, &mut feature, word.unwrap())?
415            }
416            Some(sym::reason) => {
417                insert_value_into_option_or_error(cx, param, &mut reason, word.unwrap())?
418            }
419            Some(sym::issue) => {
420                insert_value_into_option_or_error(cx, param, &mut issue, word.unwrap())?;
421
422                // These unwraps are safe because `insert_value_into_option_or_error` ensures the meta item
423                // is a name/value pair string literal.
424                issue_num = match issue.unwrap().as_str() {
425                    "none" => None,
426                    issue_str => match issue_str.parse::<NonZero<u32>>() {
427                        Ok(num) => Some(num),
428                        Err(err) => {
429                            cx.emit_err(diagnostics::InvalidIssueString {
430                                span: param.span(),
431                                cause: diagnostics::InvalidIssueStringCause::from_int_error_kind(
432                                    param.args().as_name_value().unwrap().value_span,
433                                    err.kind(),
434                                ),
435                            });
436                            return None;
437                        }
438                    },
439                };
440            }
441            Some(sym::implied_by) => {
442                insert_value_into_option_or_error(cx, param, &mut implied_by, word.unwrap())?
443            }
444            Some(sym::old_name) => {
445                insert_value_into_option_or_error(cx, param, &mut old_name, word.unwrap())?
446            }
447            _ => {
448                cx.adcx().expected_specific_argument(
449                    param.span(),
450                    &[sym::feature, sym::reason, sym::issue, sym::implied_by, sym::old_name],
451                );
452                return None;
453            }
454        }
455    }
456
457    let feature = match feature {
458        Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
459        Some(_bad_feature) => Err(cx.emit_err(diagnostics::NonIdentFeature { span: cx.attr_span })),
460        None => Err(cx.emit_err(diagnostics::MissingFeature { span: cx.attr_span })),
461    };
462
463    let issue = issue.ok_or_else(|| cx.emit_err(diagnostics::MissingIssue { span: cx.attr_span }));
464
465    match (feature, issue) {
466        (Ok(feature), Ok(_)) => {
467            // Stable *language* features shouldn't be used as unstable library features.
468            // (Not doing this for stable library features is checked by tidy.)
469            if ACCEPTED_LANG_FEATURES.iter().any(|f| f.name == feature) {
470                cx.emit_err(diagnostics::UnstableAttrForAlreadyStableFeature {
471                    attr_span: cx.attr_span,
472                    item_span: cx.target_span,
473                });
474                return None;
475            }
476
477            let level = StabilityLevel::Unstable {
478                reason: UnstableReason::from_opt_reason(reason),
479                issue: issue_num,
480                implied_by,
481                old_name,
482            };
483            Some((feature, level))
484        }
485        (Err(ErrorGuaranteed { .. }), _) | (_, Err(ErrorGuaranteed { .. })) => None,
486    }
487}
488
489pub(crate) struct UnstableRemovedParser;
490
491impl CombineAttributeParser for UnstableRemovedParser {
492    type Item = UnstableRemovedFeature;
493    const PATH: &[Symbol] = &[sym::unstable_removed];
494    const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Crate)]);
495    const TEMPLATE: AttributeTemplate =
496        crate::AttributeTemplate {
    word: false,
    list: Some(&[r#"feature = "name", reason = "...", link = "...", since = "version""#]),
    one_of: &[],
    name_value_str: None,
    docs: None,
}template!(List: &[r#"feature = "name", reason = "...", link = "...", since = "version""#]);
497    const STABILITY: AttributeStability = {
    _ = rustc_feature::Features::staged_api;
    AttributeStability::Unstable {
        gate_name: rustc_span::sym::staged_api,
        notes: &[],
    }
}unstable!(staged_api);
498
499    const CONVERT: ConvertFn<Self::Item> = |items, _| AttributeKind::UnstableRemoved(items);
500
501    fn extend(
502        cx: &mut AcceptContext<'_, '_>,
503        args: &ArgParser,
504    ) -> impl IntoIterator<Item = Self::Item> {
505        let mut feature = None;
506        let mut reason = None;
507        let mut link = None;
508        let mut since = None;
509
510        let list = cx.expect_list(args, cx.attr_span)?;
511
512        for param in list.mixed() {
513            let Some(param) = param.meta_item() else {
514                cx.adcx().expected_not_literal(param.span());
515                return None;
516            };
517
518            let Some(word) = param.path().word() else {
519                cx.adcx().expected_specific_argument(
520                    param.span(),
521                    &[sym::feature, sym::reason, sym::link, sym::since],
522                );
523                return None;
524            };
525            match word.name {
526                sym::feature => insert_value_into_option_or_error(cx, param, &mut feature, word)?,
527                sym::since => insert_value_into_option_or_error(cx, param, &mut since, word)?,
528                sym::reason => insert_value_into_option_or_error(cx, param, &mut reason, word)?,
529                sym::link => insert_value_into_option_or_error(cx, param, &mut link, word)?,
530                _ => {
531                    cx.adcx().expected_specific_argument(
532                        param.span(),
533                        &[sym::feature, sym::reason, sym::link, sym::since],
534                    );
535                    return None;
536                }
537            }
538        }
539
540        // Check all the arguments are present
541        let Some(feature) = feature else {
542            cx.adcx().missing_name_value(list.span, sym::feature);
543            return None;
544        };
545        let Some(reason) = reason else {
546            cx.adcx().missing_name_value(list.span, sym::reason);
547            return None;
548        };
549        let Some(link) = link else {
550            cx.adcx().missing_name_value(list.span, sym::link);
551            return None;
552        };
553        let Some(since) = since else {
554            cx.adcx().missing_name_value(list.span, sym::since);
555            return None;
556        };
557
558        let Some(version) = parse_version(since) else {
559            cx.emit_err(diagnostics::InvalidSince { span: cx.attr_span });
560            return None;
561        };
562
563        Some(UnstableRemovedFeature { feature, reason, link, since: version })
564    }
565}