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