]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/stability.rs
Rollup merge of #99570 - XrXr:box-from-slice-docs, r=thomcc
[rust.git] / compiler / rustc_passes / src / stability.rs
1 //! A pass that annotates every item and method with its stability level,
2 //! propagating default levels lexically from parent to children ast nodes.
3
4 use rustc_attr::{
5     self as attr, ConstStability, Stability, StabilityLevel, Unstable, UnstableReason,
6 };
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
8 use rustc_errors::{struct_span_err, Applicability};
9 use rustc_hir as hir;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
12 use rustc_hir::hir_id::CRATE_HIR_ID;
13 use rustc_hir::intravisit::{self, Visitor};
14 use rustc_hir::{FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant};
15 use rustc_middle::hir::nested_filter;
16 use rustc_middle::middle::privacy::AccessLevels;
17 use rustc_middle::middle::stability::{AllowUnstable, DeprecationEntry, Index};
18 use rustc_middle::ty::{query::Providers, TyCtxt};
19 use rustc_session::lint;
20 use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED};
21 use rustc_session::Session;
22 use rustc_span::symbol::{sym, Symbol};
23 use rustc_span::Span;
24 use rustc_target::spec::abi::Abi;
25
26 use std::cmp::Ordering;
27 use std::iter;
28 use std::mem::replace;
29 use std::num::NonZeroU32;
30
31 #[derive(PartialEq)]
32 enum AnnotationKind {
33     /// Annotation is required if not inherited from unstable parents.
34     Required,
35     /// Annotation is useless, reject it.
36     Prohibited,
37     /// Deprecation annotation is useless, reject it. (Stability attribute is still required.)
38     DeprecationProhibited,
39     /// Annotation itself is useless, but it can be propagated to children.
40     Container,
41 }
42
43 /// Whether to inherit deprecation flags for nested items. In most cases, we do want to inherit
44 /// deprecation, because nested items rarely have individual deprecation attributes, and so
45 /// should be treated as deprecated if their parent is. However, default generic parameters
46 /// have separate deprecation attributes from their parents, so we do not wish to inherit
47 /// deprecation in this case. For example, inheriting deprecation for `T` in `Foo<T>`
48 /// would cause a duplicate warning arising from both `Foo` and `T` being deprecated.
49 #[derive(Clone)]
50 enum InheritDeprecation {
51     Yes,
52     No,
53 }
54
55 impl InheritDeprecation {
56     fn yes(&self) -> bool {
57         matches!(self, InheritDeprecation::Yes)
58     }
59 }
60
61 /// Whether to inherit const stability flags for nested items. In most cases, we do not want to
62 /// inherit const stability: just because an enclosing `fn` is const-stable does not mean
63 /// all `extern` imports declared in it should be const-stable! However, trait methods
64 /// inherit const stability attributes from their parent and do not have their own.
65 enum InheritConstStability {
66     Yes,
67     No,
68 }
69
70 impl InheritConstStability {
71     fn yes(&self) -> bool {
72         matches!(self, InheritConstStability::Yes)
73     }
74 }
75
76 enum InheritStability {
77     Yes,
78     No,
79 }
80
81 impl InheritStability {
82     fn yes(&self) -> bool {
83         matches!(self, InheritStability::Yes)
84     }
85 }
86
87 /// A private tree-walker for producing an `Index`.
88 struct Annotator<'a, 'tcx> {
89     tcx: TyCtxt<'tcx>,
90     index: &'a mut Index,
91     parent_stab: Option<Stability>,
92     parent_const_stab: Option<ConstStability>,
93     parent_depr: Option<DeprecationEntry>,
94     in_trait_impl: bool,
95 }
96
97 impl<'a, 'tcx> Annotator<'a, 'tcx> {
98     /// Determine the stability for a node based on its attributes and inherited stability. The
99     /// stability is recorded in the index and used as the parent. If the node is a function,
100     /// `fn_sig` is its signature.
101     fn annotate<F>(
102         &mut self,
103         def_id: LocalDefId,
104         item_sp: Span,
105         fn_sig: Option<&'tcx hir::FnSig<'tcx>>,
106         kind: AnnotationKind,
107         inherit_deprecation: InheritDeprecation,
108         inherit_const_stability: InheritConstStability,
109         inherit_from_parent: InheritStability,
110         visit_children: F,
111     ) where
112         F: FnOnce(&mut Self),
113     {
114         let attrs = self.tcx.hir().attrs(self.tcx.hir().local_def_id_to_hir_id(def_id));
115         debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs);
116
117         let depr = attr::find_deprecation(&self.tcx.sess, attrs);
118         let mut is_deprecated = false;
119         if let Some((depr, span)) = &depr {
120             is_deprecated = true;
121
122             if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited {
123                 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
124                 self.tcx.struct_span_lint_hir(USELESS_DEPRECATED, hir_id, *span, |lint| {
125                     lint.build("this `#[deprecated]` annotation has no effect")
126                         .span_suggestion_short(
127                             *span,
128                             "remove the unnecessary deprecation attribute",
129                             "",
130                             rustc_errors::Applicability::MachineApplicable,
131                         )
132                         .emit();
133                 });
134             }
135
136             // `Deprecation` is just two pointers, no need to intern it
137             let depr_entry = DeprecationEntry::local(*depr, def_id);
138             self.index.depr_map.insert(def_id, depr_entry);
139         } else if let Some(parent_depr) = self.parent_depr {
140             if inherit_deprecation.yes() {
141                 is_deprecated = true;
142                 info!("tagging child {:?} as deprecated from parent", def_id);
143                 self.index.depr_map.insert(def_id, parent_depr);
144             }
145         }
146
147         if !self.tcx.features().staged_api {
148             // Propagate unstability.  This can happen even for non-staged-api crates in case
149             // -Zforce-unstable-if-unmarked is set.
150             if let Some(stab) = self.parent_stab {
151                 if inherit_deprecation.yes() && stab.is_unstable() {
152                     self.index.stab_map.insert(def_id, stab);
153                 }
154             }
155
156             self.recurse_with_stability_attrs(
157                 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
158                 None,
159                 None,
160                 visit_children,
161             );
162             return;
163         }
164
165         let (stab, const_stab, body_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
166         let mut const_span = None;
167
168         let const_stab = const_stab.map(|(const_stab, const_span_node)| {
169             self.index.const_stab_map.insert(def_id, const_stab);
170             const_span = Some(const_span_node);
171             const_stab
172         });
173
174         // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
175         // check if the function/method is const or the parent impl block is const
176         if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) {
177             if fn_sig.header.abi != Abi::RustIntrinsic
178                 && fn_sig.header.abi != Abi::PlatformIntrinsic
179                 && !fn_sig.header.is_const()
180             {
181                 if !self.in_trait_impl
182                     || (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id()))
183                 {
184                     missing_const_err(&self.tcx.sess, fn_sig.span, const_span);
185                 }
186             }
187         }
188
189         // `impl const Trait for Type` items forward their const stability to their
190         // immediate children.
191         if const_stab.is_none() {
192             debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
193             if let Some(parent) = self.parent_const_stab {
194                 if parent.is_const_unstable() {
195                     self.index.const_stab_map.insert(def_id, parent);
196                 }
197             }
198         }
199
200         if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
201             if stab.is_none() {
202                 struct_span_err!(
203                     self.tcx.sess,
204                     *span,
205                     E0549,
206                     "deprecated attribute must be paired with \
207                     either stable or unstable attribute"
208                 )
209                 .emit();
210             }
211         }
212
213         if let Some((body_stab, _span)) = body_stab {
214             // FIXME: check that this item can have body stability
215
216             self.index.default_body_stab_map.insert(def_id, body_stab);
217             debug!(?self.index.default_body_stab_map);
218         }
219
220         let stab = stab.map(|(stab, span)| {
221             // Error if prohibited, or can't inherit anything from a container.
222             if kind == AnnotationKind::Prohibited
223                 || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated)
224             {
225                 self.tcx.sess.struct_span_err(span,"this stability annotation is useless")
226                     .span_label(span, "useless stability annotation")
227                     .span_label(item_sp, "the stability attribute annotates this item")
228                     .emit();
229             }
230
231             debug!("annotate: found {:?}", stab);
232
233             // Check if deprecated_since < stable_since. If it is,
234             // this is *almost surely* an accident.
235             if let (&Some(dep_since), &attr::Stable { since: stab_since, .. }) =
236                 (&depr.as_ref().and_then(|(d, _)| d.since), &stab.level)
237             {
238                 // Explicit version of iter::order::lt to handle parse errors properly
239                 for (dep_v, stab_v) in
240                     iter::zip(dep_since.as_str().split('.'), stab_since.as_str().split('.'))
241                 {
242                     match stab_v.parse::<u64>() {
243                         Err(_) => {
244                             self.tcx.sess.struct_span_err(span, "invalid stability version found")
245                                 .span_label(span, "invalid stability version")
246                                 .span_label(item_sp, "the stability attribute annotates this item")
247                                 .emit();
248                             break;
249                         }
250                         Ok(stab_vp) => match dep_v.parse::<u64>() {
251                             Ok(dep_vp) => match dep_vp.cmp(&stab_vp) {
252                                 Ordering::Less => {
253                                     self.tcx.sess.struct_span_err(span, "an API can't be stabilized after it is deprecated")
254                                         .span_label(span, "invalid version")
255                                         .span_label(item_sp, "the stability attribute annotates this item")
256                                         .emit();
257                                     break;
258                                 }
259                                 Ordering::Equal => continue,
260                                 Ordering::Greater => break,
261                             },
262                             Err(_) => {
263                                 if dep_v != "TBD" {
264                                     self.tcx.sess.struct_span_err(span, "invalid deprecation version found")
265                                         .span_label(span, "invalid deprecation version")
266                                         .span_label(item_sp, "the stability attribute annotates this item")
267                                         .emit();
268                                 }
269                                 break;
270                             }
271                         },
272                     }
273                 }
274             }
275
276             if let Stability { level: Unstable { implied_by: Some(implied_by), .. }, feature } = stab {
277                 self.index.implications.insert(implied_by, feature);
278             }
279
280             self.index.stab_map.insert(def_id, stab);
281             stab
282         });
283
284         if stab.is_none() {
285             debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
286             if let Some(stab) = self.parent_stab {
287                 if inherit_deprecation.yes() && stab.is_unstable() || inherit_from_parent.yes() {
288                     self.index.stab_map.insert(def_id, stab);
289                 }
290             }
291         }
292
293         self.recurse_with_stability_attrs(
294             depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
295             stab,
296             if inherit_const_stability.yes() { const_stab } else { None },
297             visit_children,
298         );
299     }
300
301     fn recurse_with_stability_attrs(
302         &mut self,
303         depr: Option<DeprecationEntry>,
304         stab: Option<Stability>,
305         const_stab: Option<ConstStability>,
306         f: impl FnOnce(&mut Self),
307     ) {
308         // These will be `Some` if this item changes the corresponding stability attribute.
309         let mut replaced_parent_depr = None;
310         let mut replaced_parent_stab = None;
311         let mut replaced_parent_const_stab = None;
312
313         if let Some(depr) = depr {
314             replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
315         }
316         if let Some(stab) = stab {
317             replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
318         }
319         if let Some(const_stab) = const_stab {
320             replaced_parent_const_stab =
321                 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
322         }
323
324         f(self);
325
326         if let Some(orig_parent_depr) = replaced_parent_depr {
327             self.parent_depr = orig_parent_depr;
328         }
329         if let Some(orig_parent_stab) = replaced_parent_stab {
330             self.parent_stab = orig_parent_stab;
331         }
332         if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
333             self.parent_const_stab = orig_parent_const_stab;
334         }
335     }
336 }
337
338 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
339     /// Because stability levels are scoped lexically, we want to walk
340     /// nested items in the context of the outer item, so enable
341     /// deep-walking.
342     type NestedFilter = nested_filter::All;
343
344     fn nested_visit_map(&mut self) -> Self::Map {
345         self.tcx.hir()
346     }
347
348     fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
349         let orig_in_trait_impl = self.in_trait_impl;
350         let mut kind = AnnotationKind::Required;
351         let mut const_stab_inherit = InheritConstStability::No;
352         let mut fn_sig = None;
353
354         match i.kind {
355             // Inherent impls and foreign modules serve only as containers for other items,
356             // they don't have their own stability. They still can be annotated as unstable
357             // and propagate this instability to children, but this annotation is completely
358             // optional. They inherit stability from their parents when unannotated.
359             hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
360             | hir::ItemKind::ForeignMod { .. } => {
361                 self.in_trait_impl = false;
362                 kind = AnnotationKind::Container;
363             }
364             hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
365                 self.in_trait_impl = true;
366                 kind = AnnotationKind::DeprecationProhibited;
367                 const_stab_inherit = InheritConstStability::Yes;
368             }
369             hir::ItemKind::Struct(ref sd, _) => {
370                 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
371                     self.annotate(
372                         self.tcx.hir().local_def_id(ctor_hir_id),
373                         i.span,
374                         None,
375                         AnnotationKind::Required,
376                         InheritDeprecation::Yes,
377                         InheritConstStability::No,
378                         InheritStability::Yes,
379                         |_| {},
380                     )
381                 }
382             }
383             hir::ItemKind::Fn(ref item_fn_sig, _, _) => {
384                 fn_sig = Some(item_fn_sig);
385             }
386             _ => {}
387         }
388
389         self.annotate(
390             i.def_id,
391             i.span,
392             fn_sig,
393             kind,
394             InheritDeprecation::Yes,
395             const_stab_inherit,
396             InheritStability::No,
397             |v| intravisit::walk_item(v, i),
398         );
399         self.in_trait_impl = orig_in_trait_impl;
400     }
401
402     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
403         let fn_sig = match ti.kind {
404             hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
405             _ => None,
406         };
407
408         self.annotate(
409             ti.def_id,
410             ti.span,
411             fn_sig,
412             AnnotationKind::Required,
413             InheritDeprecation::Yes,
414             InheritConstStability::No,
415             InheritStability::No,
416             |v| {
417                 intravisit::walk_trait_item(v, ti);
418             },
419         );
420     }
421
422     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
423         let kind =
424             if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
425
426         let fn_sig = match ii.kind {
427             hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
428             _ => None,
429         };
430
431         self.annotate(
432             ii.def_id,
433             ii.span,
434             fn_sig,
435             kind,
436             InheritDeprecation::Yes,
437             InheritConstStability::No,
438             InheritStability::No,
439             |v| {
440                 intravisit::walk_impl_item(v, ii);
441             },
442         );
443     }
444
445     fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
446         self.annotate(
447             self.tcx.hir().local_def_id(var.id),
448             var.span,
449             None,
450             AnnotationKind::Required,
451             InheritDeprecation::Yes,
452             InheritConstStability::No,
453             InheritStability::Yes,
454             |v| {
455                 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
456                     v.annotate(
457                         v.tcx.hir().local_def_id(ctor_hir_id),
458                         var.span,
459                         None,
460                         AnnotationKind::Required,
461                         InheritDeprecation::Yes,
462                         InheritConstStability::No,
463                         InheritStability::Yes,
464                         |_| {},
465                     );
466                 }
467
468                 intravisit::walk_variant(v, var)
469             },
470         )
471     }
472
473     fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
474         self.annotate(
475             self.tcx.hir().local_def_id(s.hir_id),
476             s.span,
477             None,
478             AnnotationKind::Required,
479             InheritDeprecation::Yes,
480             InheritConstStability::No,
481             InheritStability::Yes,
482             |v| {
483                 intravisit::walk_field_def(v, s);
484             },
485         );
486     }
487
488     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
489         self.annotate(
490             i.def_id,
491             i.span,
492             None,
493             AnnotationKind::Required,
494             InheritDeprecation::Yes,
495             InheritConstStability::No,
496             InheritStability::No,
497             |v| {
498                 intravisit::walk_foreign_item(v, i);
499             },
500         );
501     }
502
503     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
504         let kind = match &p.kind {
505             // Allow stability attributes on default generic arguments.
506             hir::GenericParamKind::Type { default: Some(_), .. }
507             | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
508             _ => AnnotationKind::Prohibited,
509         };
510
511         self.annotate(
512             self.tcx.hir().local_def_id(p.hir_id),
513             p.span,
514             None,
515             kind,
516             InheritDeprecation::No,
517             InheritConstStability::No,
518             InheritStability::No,
519             |v| {
520                 intravisit::walk_generic_param(v, p);
521             },
522         );
523     }
524 }
525
526 struct MissingStabilityAnnotations<'tcx> {
527     tcx: TyCtxt<'tcx>,
528     access_levels: &'tcx AccessLevels,
529 }
530
531 impl<'tcx> MissingStabilityAnnotations<'tcx> {
532     fn check_missing_stability(&self, def_id: LocalDefId, span: Span) {
533         let stab = self.tcx.stability().local_stability(def_id);
534         if !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(def_id) {
535             let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
536             self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
537         }
538     }
539
540     fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) {
541         if !self.tcx.features().staged_api {
542             return;
543         }
544
545         let is_const = self.tcx.is_const_fn(def_id.to_def_id())
546             || self.tcx.is_const_trait_impl_raw(def_id.to_def_id());
547         let is_stable = self
548             .tcx
549             .lookup_stability(def_id)
550             .map_or(false, |stability| stability.level.is_stable());
551         let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none();
552         let is_reachable = self.access_levels.is_reachable(def_id);
553
554         if is_const && is_stable && missing_const_stability_attribute && is_reachable {
555             let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
556             self.tcx.sess.span_err(span, &format!("{descr} has missing const stability attribute"));
557         }
558     }
559 }
560
561 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
562     type NestedFilter = nested_filter::OnlyBodies;
563
564     fn nested_visit_map(&mut self) -> Self::Map {
565         self.tcx.hir()
566     }
567
568     fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
569         // Inherent impls and foreign modules serve only as containers for other items,
570         // they don't have their own stability. They still can be annotated as unstable
571         // and propagate this instability to children, but this annotation is completely
572         // optional. They inherit stability from their parents when unannotated.
573         if !matches!(
574             i.kind,
575             hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
576                 | hir::ItemKind::ForeignMod { .. }
577         ) {
578             self.check_missing_stability(i.def_id, i.span);
579         }
580
581         // Ensure stable `const fn` have a const stability attribute.
582         self.check_missing_const_stability(i.def_id, i.span);
583
584         intravisit::walk_item(self, i)
585     }
586
587     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
588         self.check_missing_stability(ti.def_id, ti.span);
589         intravisit::walk_trait_item(self, ti);
590     }
591
592     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
593         let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id());
594         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
595             self.check_missing_stability(ii.def_id, ii.span);
596             self.check_missing_const_stability(ii.def_id, ii.span);
597         }
598         intravisit::walk_impl_item(self, ii);
599     }
600
601     fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
602         self.check_missing_stability(self.tcx.hir().local_def_id(var.id), var.span);
603         if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
604             self.check_missing_stability(self.tcx.hir().local_def_id(ctor_hir_id), var.span);
605         }
606         intravisit::walk_variant(self, var);
607     }
608
609     fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
610         self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
611         intravisit::walk_field_def(self, s);
612     }
613
614     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
615         self.check_missing_stability(i.def_id, i.span);
616         intravisit::walk_foreign_item(self, i);
617     }
618     // Note that we don't need to `check_missing_stability` for default generic parameters,
619     // as we assume that any default generic parameters without attributes are automatically
620     // stable (assuming they have not inherited instability from their parent).
621 }
622
623 fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
624     let mut index = Index {
625         stab_map: Default::default(),
626         const_stab_map: Default::default(),
627         default_body_stab_map: Default::default(),
628         depr_map: Default::default(),
629         implications: Default::default(),
630     };
631
632     {
633         let mut annotator = Annotator {
634             tcx,
635             index: &mut index,
636             parent_stab: None,
637             parent_const_stab: None,
638             parent_depr: None,
639             in_trait_impl: false,
640         };
641
642         // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
643         // a parent stability annotation which indicates that this is private
644         // with the `rustc_private` feature. This is intended for use when
645         // compiling `librustc_*` crates themselves so we can leverage crates.io
646         // while maintaining the invariant that all sysroot crates are unstable
647         // by default and are unable to be used.
648         if tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
649             let stability = Stability {
650                 level: attr::StabilityLevel::Unstable {
651                     reason: UnstableReason::Default,
652                     issue: NonZeroU32::new(27812),
653                     is_soft: false,
654                     implied_by: None,
655                 },
656                 feature: sym::rustc_private,
657             };
658             annotator.parent_stab = Some(stability);
659         }
660
661         annotator.annotate(
662             CRATE_DEF_ID,
663             tcx.hir().span(CRATE_HIR_ID),
664             None,
665             AnnotationKind::Required,
666             InheritDeprecation::Yes,
667             InheritConstStability::No,
668             InheritStability::No,
669             |v| tcx.hir().walk_toplevel_module(v),
670         );
671     }
672     index
673 }
674
675 /// Cross-references the feature names of unstable APIs with enabled
676 /// features and possibly prints errors.
677 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
678     tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx });
679 }
680
681 pub(crate) fn provide(providers: &mut Providers) {
682     *providers = Providers {
683         check_mod_unstable_api_usage,
684         stability_index,
685         stability_implications: |tcx, _| tcx.stability().implications.clone(),
686         lookup_stability: |tcx, id| tcx.stability().local_stability(id.expect_local()),
687         lookup_const_stability: |tcx, id| tcx.stability().local_const_stability(id.expect_local()),
688         lookup_default_body_stability: |tcx, id| {
689             tcx.stability().local_default_body_stability(id.expect_local())
690         },
691         lookup_deprecation_entry: |tcx, id| {
692             tcx.stability().local_deprecation_entry(id.expect_local())
693         },
694         ..*providers
695     };
696 }
697
698 struct Checker<'tcx> {
699     tcx: TyCtxt<'tcx>,
700 }
701
702 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
703     type NestedFilter = nested_filter::OnlyBodies;
704
705     /// Because stability levels are scoped lexically, we want to walk
706     /// nested items in the context of the outer item, so enable
707     /// deep-walking.
708     fn nested_visit_map(&mut self) -> Self::Map {
709         self.tcx.hir()
710     }
711
712     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
713         match item.kind {
714             hir::ItemKind::ExternCrate(_) => {
715                 // compiler-generated `extern crate` items have a dummy span.
716                 // `std` is still checked for the `restricted-std` feature.
717                 if item.span.is_dummy() && item.ident.name != sym::std {
718                     return;
719                 }
720
721                 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id) else {
722                     return;
723                 };
724                 let def_id = cnum.as_def_id();
725                 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
726             }
727
728             // For implementations of traits, check the stability of each item
729             // individually as it's possible to have a stable trait with unstable
730             // items.
731             hir::ItemKind::Impl(hir::Impl {
732                 of_trait: Some(ref t),
733                 self_ty,
734                 items,
735                 constness,
736                 ..
737             }) => {
738                 let features = self.tcx.features();
739                 if features.staged_api {
740                     let attrs = self.tcx.hir().attrs(item.hir_id());
741                     let (stab, const_stab, _) =
742                         attr::find_stability(&self.tcx.sess, attrs, item.span);
743
744                     // If this impl block has an #[unstable] attribute, give an
745                     // error if all involved types and traits are stable, because
746                     // it will have no effect.
747                     // See: https://github.com/rust-lang/rust/issues/55436
748                     if let Some((Stability { level: attr::Unstable { .. }, .. }, span)) = stab {
749                         let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
750                         c.visit_ty(self_ty);
751                         c.visit_trait_ref(t);
752                         if c.fully_stable {
753                             self.tcx.struct_span_lint_hir(
754                                 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
755                                 item.hir_id(),
756                                 span,
757                                 |lint| {lint
758                                     .build("an `#[unstable]` annotation here has no effect")
759                                     .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
760                                     .emit();}
761                             );
762                         }
763                     }
764
765                     // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable
766                     // needs to have an error emitted.
767                     if features.const_trait_impl
768                         && *constness == hir::Constness::Const
769                         && const_stab.map_or(false, |(stab, _)| stab.is_const_stable())
770                     {
771                         self.tcx
772                             .sess
773                             .struct_span_err(item.span, "trait implementations cannot be const stable yet")
774                             .note("see issue #67792 <https://github.com/rust-lang/rust/issues/67792> for more information")
775                             .emit();
776                     }
777                 }
778
779                 for impl_item_ref in *items {
780                     let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
781
782                     if let Some(def_id) = impl_item.trait_item_def_id {
783                         // Pass `None` to skip deprecation warnings.
784                         self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
785                     }
786                 }
787             }
788
789             _ => (/* pass */),
790         }
791         intravisit::walk_item(self, item);
792     }
793
794     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
795         if let Some(def_id) = path.res.opt_def_id() {
796             let method_span = path.segments.last().map(|s| s.ident.span);
797             let item_is_allowed = self.tcx.check_stability_allow_unstable(
798                 def_id,
799                 Some(id),
800                 path.span,
801                 method_span,
802                 if is_unstable_reexport(self.tcx, id) {
803                     AllowUnstable::Yes
804                 } else {
805                     AllowUnstable::No
806                 },
807             );
808
809             let is_allowed_through_unstable_modules = |def_id| {
810                 self.tcx
811                     .lookup_stability(def_id)
812                     .map(|stab| match stab.level {
813                         StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {
814                             allowed_through_unstable_modules
815                         }
816                         _ => false,
817                     })
818                     .unwrap_or(false)
819             };
820
821             if item_is_allowed && !is_allowed_through_unstable_modules(def_id) {
822                 // Check parent modules stability as well if the item the path refers to is itself
823                 // stable. We only emit warnings for unstable path segments if the item is stable
824                 // or allowed because stability is often inherited, so the most common case is that
825                 // both the segments and the item are unstable behind the same feature flag.
826                 //
827                 // We check here rather than in `visit_path_segment` to prevent visiting the last
828                 // path segment twice
829                 //
830                 // We include special cases via #[rustc_allowed_through_unstable_modules] for items
831                 // that were accidentally stabilized through unstable paths before this check was
832                 // added, such as `core::intrinsics::transmute`
833                 let parents = path.segments.iter().rev().skip(1);
834                 for path_segment in parents {
835                     if let Some(def_id) = path_segment.res.as_ref().and_then(Res::opt_def_id) {
836                         // use `None` for id to prevent deprecation check
837                         self.tcx.check_stability_allow_unstable(
838                             def_id,
839                             None,
840                             path.span,
841                             None,
842                             if is_unstable_reexport(self.tcx, id) {
843                                 AllowUnstable::Yes
844                             } else {
845                                 AllowUnstable::No
846                             },
847                         );
848                     }
849                 }
850             }
851         }
852
853         intravisit::walk_path(self, path)
854     }
855 }
856
857 /// Check whether a path is a `use` item that has been marked as unstable.
858 ///
859 /// See issue #94972 for details on why this is a special case
860 fn is_unstable_reexport<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId) -> bool {
861     // Get the LocalDefId so we can lookup the item to check the kind.
862     let Some(def_id) = tcx.hir().opt_local_def_id(id) else { return false; };
863
864     let Some(stab) = tcx.stability().local_stability(def_id) else {
865         return false;
866     };
867
868     if stab.level.is_stable() {
869         // The re-export is not marked as unstable, don't override
870         return false;
871     }
872
873     // If this is a path that isn't a use, we don't need to do anything special
874     if !matches!(tcx.hir().item(hir::ItemId { def_id }).kind, ItemKind::Use(..)) {
875         return false;
876     }
877
878     true
879 }
880
881 struct CheckTraitImplStable<'tcx> {
882     tcx: TyCtxt<'tcx>,
883     fully_stable: bool,
884 }
885
886 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
887     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
888         if let Some(def_id) = path.res.opt_def_id() {
889             if let Some(stab) = self.tcx.lookup_stability(def_id) {
890                 self.fully_stable &= stab.level.is_stable();
891             }
892         }
893         intravisit::walk_path(self, path)
894     }
895
896     fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
897         if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
898             if let Some(stab) = self.tcx.lookup_stability(trait_did) {
899                 self.fully_stable &= stab.level.is_stable();
900             }
901         }
902         intravisit::walk_trait_ref(self, t)
903     }
904
905     fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
906         if let TyKind::Never = t.kind {
907             self.fully_stable = false;
908         }
909         intravisit::walk_ty(self, t)
910     }
911 }
912
913 /// Given the list of enabled features that were not language features (i.e., that
914 /// were expected to be library features), and the list of features used from
915 /// libraries, identify activated features that don't exist and error about them.
916 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
917     let is_staged_api =
918         tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api;
919     if is_staged_api {
920         let access_levels = &tcx.privacy_access_levels(());
921         let mut missing = MissingStabilityAnnotations { tcx, access_levels };
922         missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
923         tcx.hir().walk_toplevel_module(&mut missing);
924         tcx.hir().visit_all_item_likes_in_crate(&mut missing);
925     }
926
927     let declared_lang_features = &tcx.features().declared_lang_features;
928     let mut lang_features = FxHashSet::default();
929     for &(feature, span, since) in declared_lang_features {
930         if let Some(since) = since {
931             // Warn if the user has enabled an already-stable lang feature.
932             unnecessary_stable_feature_lint(tcx, span, feature, since);
933         }
934         if !lang_features.insert(feature) {
935             // Warn if the user enables a lang feature multiple times.
936             duplicate_feature_err(tcx.sess, span, feature);
937         }
938     }
939
940     let declared_lib_features = &tcx.features().declared_lib_features;
941     let mut remaining_lib_features = FxIndexMap::default();
942     for (feature, span) in declared_lib_features {
943         if !tcx.sess.opts.unstable_features.is_nightly_build() {
944             struct_span_err!(
945                 tcx.sess,
946                 *span,
947                 E0554,
948                 "`#![feature]` may not be used on the {} release channel",
949                 env!("CFG_RELEASE_CHANNEL")
950             )
951             .emit();
952         }
953         if remaining_lib_features.contains_key(&feature) {
954             // Warn if the user enables a lib feature multiple times.
955             duplicate_feature_err(tcx.sess, *span, *feature);
956         }
957         remaining_lib_features.insert(feature, *span);
958     }
959     // `stdbuild` has special handling for `libc`, so we need to
960     // recognise the feature when building std.
961     // Likewise, libtest is handled specially, so `test` isn't
962     // available as we'd like it to be.
963     // FIXME: only remove `libc` when `stdbuild` is active.
964     // FIXME: remove special casing for `test`.
965     remaining_lib_features.remove(&sym::libc);
966     remaining_lib_features.remove(&sym::test);
967
968     /// For each feature in `defined_features`..
969     ///
970     /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in
971     ///   the current crate), check if it is stable (or partially stable) and thus an unnecessary
972     ///   attribute.
973     /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`
974     ///   from the current crate), then remove it from the remaining implications.
975     ///
976     /// Once this function has been invoked for every feature (local crate and all extern crates),
977     /// then..
978     ///
979     /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that
980     ///   does not exist.
981     /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that
982     ///   does not exist.
983     ///
984     /// By structuring the code in this way: checking the features defined from each crate one at a
985     /// time, less loading from metadata is performed and thus compiler performance is improved.
986     fn check_features<'tcx>(
987         tcx: TyCtxt<'tcx>,
988         remaining_lib_features: &mut FxIndexMap<&Symbol, Span>,
989         remaining_implications: &mut FxHashMap<Symbol, Symbol>,
990         defined_features: &[(Symbol, Option<Symbol>)],
991         all_implications: &FxHashMap<Symbol, Symbol>,
992     ) {
993         for (feature, since) in defined_features {
994             if let Some(since) = since && let Some(span) = remaining_lib_features.get(&feature) {
995                 // Warn if the user has enabled an already-stable lib feature.
996                 if let Some(implies) = all_implications.get(&feature) {
997                     unnecessary_partially_stable_feature_lint(tcx, *span, *feature, *implies, *since);
998                 } else {
999                     unnecessary_stable_feature_lint(tcx, *span, *feature, *since);
1000                 }
1001
1002             }
1003             remaining_lib_features.remove(feature);
1004
1005             // `feature` is the feature doing the implying, but `implied_by` is the feature with
1006             // the attribute that establishes this relationship. `implied_by` is guaranteed to be a
1007             // feature defined in the local crate because `remaining_implications` is only the
1008             // implications from this crate.
1009             remaining_implications.remove(feature);
1010
1011             if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1012                 break;
1013             }
1014         }
1015     }
1016
1017     // All local crate implications need to have the feature that implies it confirmed to exist.
1018     let mut remaining_implications =
1019         tcx.stability_implications(rustc_hir::def_id::LOCAL_CRATE).clone();
1020
1021     // We always collect the lib features declared in the current crate, even if there are
1022     // no unknown features, because the collection also does feature attribute validation.
1023     let local_defined_features = tcx.lib_features(()).to_vec();
1024     if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {
1025         // Loading the implications of all crates is unavoidable to be able to emit the partial
1026         // stabilization diagnostic, but it can be avoided when there are no
1027         // `remaining_lib_features`.
1028         let mut all_implications = remaining_implications.clone();
1029         for &cnum in tcx.crates(()) {
1030             all_implications.extend(tcx.stability_implications(cnum));
1031         }
1032
1033         check_features(
1034             tcx,
1035             &mut remaining_lib_features,
1036             &mut remaining_implications,
1037             local_defined_features.as_slice(),
1038             &all_implications,
1039         );
1040
1041         for &cnum in tcx.crates(()) {
1042             if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1043                 break;
1044             }
1045             check_features(
1046                 tcx,
1047                 &mut remaining_lib_features,
1048                 &mut remaining_implications,
1049                 tcx.defined_lib_features(cnum).to_vec().as_slice(),
1050                 &all_implications,
1051             );
1052         }
1053     }
1054
1055     for (feature, span) in remaining_lib_features {
1056         struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
1057     }
1058
1059     for (implied_by, feature) in remaining_implications {
1060         let local_defined_features = tcx.lib_features(());
1061         let span = local_defined_features
1062             .stable
1063             .get(&feature)
1064             .map(|(_, span)| span)
1065             .or_else(|| local_defined_features.unstable.get(&feature))
1066             .expect("feature that implied another does not exist");
1067         tcx.sess
1068             .struct_span_err(
1069                 *span,
1070                 format!("feature `{implied_by}` implying `{feature}` does not exist"),
1071             )
1072             .emit();
1073     }
1074
1075     // FIXME(#44232): the `used_features` table no longer exists, so we
1076     // don't lint about unused features. We should re-enable this one day!
1077 }
1078
1079 fn unnecessary_partially_stable_feature_lint(
1080     tcx: TyCtxt<'_>,
1081     span: Span,
1082     feature: Symbol,
1083     implies: Symbol,
1084     since: Symbol,
1085 ) {
1086     tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1087         lint.build(&format!(
1088             "the feature `{feature}` has been partially stabilized since {since} and is succeeded \
1089              by the feature `{implies}`"
1090         ))
1091         .span_suggestion(
1092             span,
1093             &format!(
1094                 "if you are using features which are still unstable, change to using `{implies}`"
1095             ),
1096             implies,
1097             Applicability::MaybeIncorrect,
1098         )
1099         .span_suggestion(
1100             tcx.sess.source_map().span_extend_to_line(span),
1101             "if you are using features which are now stable, remove this line",
1102             "",
1103             Applicability::MaybeIncorrect,
1104         )
1105         .emit();
1106     });
1107 }
1108
1109 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
1110     tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1111         lint.build(&format!(
1112             "the feature `{feature}` has been stable since {since} and no longer requires an \
1113              attribute to enable",
1114         ))
1115         .emit();
1116     });
1117 }
1118
1119 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
1120     struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
1121         .emit();
1122 }
1123
1124 fn missing_const_err(session: &Session, fn_sig_span: Span, const_span: Span) {
1125     const ERROR_MSG: &'static str = "attributes `#[rustc_const_unstable]` \
1126          and `#[rustc_const_stable]` require \
1127          the function or method to be `const`";
1128
1129     session
1130         .struct_span_err(fn_sig_span, ERROR_MSG)
1131         .span_help(fn_sig_span, "make the function or method const")
1132         .span_label(const_span, "attribute specified here")
1133         .emit();
1134 }