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