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