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