]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/stability.rs
Tweak move error
[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_ast::Attribute;
5 use rustc_attr::{self as attr, ConstStability, Stability};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::struct_span_err;
8 use rustc_hir as hir;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::hir_id::CRATE_HIR_ID;
12 use rustc_hir::intravisit::{self, Visitor};
13 use rustc_hir::{FieldDef, Generics, HirId, Item, TraitRef, Ty, TyKind, Variant};
14 use rustc_middle::hir::nested_filter;
15 use rustc_middle::middle::privacy::AccessLevels;
16 use rustc_middle::middle::stability::{DeprecationEntry, Index};
17 use rustc_middle::ty::{self, query::Providers, TyCtxt};
18 use rustc_session::lint;
19 use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED};
20 use rustc_session::parse::feature_err;
21 use rustc_session::Session;
22 use rustc_span::symbol::{sym, Symbol};
23 use rustc_span::{Span, DUMMY_SP};
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
99     // stability. The stability is recorded in the index and used as the parent.
100     // If the node is a function, `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.get_attrs(def_id.to_def_id());
115         debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs);
116         let mut did_error = false;
117         if !self.tcx.features().staged_api {
118             did_error = self.forbid_staged_api_attrs(def_id, attrs, inherit_deprecation.clone());
119         }
120
121         let depr = if did_error { None } else { attr::find_deprecation(&self.tcx.sess, attrs) };
122         let mut is_deprecated = false;
123         if let Some((depr, span)) = &depr {
124             is_deprecated = true;
125
126             if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited {
127                 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
128                 self.tcx.struct_span_lint_hir(USELESS_DEPRECATED, hir_id, *span, |lint| {
129                     lint.build("this `#[deprecated]` annotation has no effect")
130                         .span_suggestion_short(
131                             *span,
132                             "remove the unnecessary deprecation attribute",
133                             String::new(),
134                             rustc_errors::Applicability::MachineApplicable,
135                         )
136                         .emit()
137                 });
138             }
139
140             // `Deprecation` is just two pointers, no need to intern it
141             let depr_entry = DeprecationEntry::local(depr.clone(), def_id);
142             self.index.depr_map.insert(def_id, depr_entry);
143         } else if let Some(parent_depr) = self.parent_depr.clone() {
144             if inherit_deprecation.yes() {
145                 is_deprecated = true;
146                 info!("tagging child {:?} as deprecated from parent", def_id);
147                 self.index.depr_map.insert(def_id, parent_depr);
148             }
149         }
150
151         if self.tcx.features().staged_api {
152             if let Some(a) = attrs.iter().find(|a| a.has_name(sym::deprecated)) {
153                 self.tcx
154                     .sess
155                     .struct_span_err(a.span, "`#[deprecated]` cannot be used in staged API")
156                     .span_label(a.span, "use `#[rustc_deprecated]` instead")
157                     .span_label(item_sp, "")
158                     .emit();
159             }
160         } else {
161             self.recurse_with_stability_attrs(
162                 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
163                 None,
164                 None,
165                 visit_children,
166             );
167             return;
168         }
169
170         let (stab, const_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
171         let mut const_span = None;
172
173         let const_stab = const_stab.map(|(const_stab, const_span_node)| {
174             self.index.const_stab_map.insert(def_id, const_stab);
175             const_span = Some(const_span_node);
176             const_stab
177         });
178
179         // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
180         // check if the function/method is const or the parent impl block is const
181         if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) {
182             if fn_sig.header.abi != Abi::RustIntrinsic
183                 && fn_sig.header.abi != Abi::PlatformIntrinsic
184                 && !fn_sig.header.is_const()
185             {
186                 if !self.in_trait_impl
187                     || (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id()))
188                 {
189                     missing_const_err(&self.tcx.sess, fn_sig.span, const_span);
190                 }
191             }
192         }
193
194         // `impl const Trait for Type` items forward their const stability to their
195         // immediate children.
196         if const_stab.is_none() {
197             debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
198             if let Some(parent) = self.parent_const_stab {
199                 if parent.level.is_unstable() {
200                     self.index.const_stab_map.insert(def_id, parent);
201                 }
202             }
203         }
204
205         if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
206             if stab.is_none() {
207                 struct_span_err!(
208                     self.tcx.sess,
209                     *span,
210                     E0549,
211                     "rustc_deprecated attribute must be paired with \
212                     either stable or unstable attribute"
213                 )
214                 .emit();
215             }
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             self.index.stab_map.insert(def_id, stab);
275             stab
276         });
277
278         if stab.is_none() {
279             debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
280             if let Some(stab) = self.parent_stab {
281                 if inherit_deprecation.yes() && stab.level.is_unstable()
282                     || inherit_from_parent.yes()
283                 {
284                     self.index.stab_map.insert(def_id, stab);
285                 }
286             }
287         }
288
289         self.recurse_with_stability_attrs(
290             depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
291             stab,
292             if inherit_const_stability.yes() { const_stab } else { None },
293             visit_children,
294         );
295     }
296
297     fn recurse_with_stability_attrs(
298         &mut self,
299         depr: Option<DeprecationEntry>,
300         stab: Option<Stability>,
301         const_stab: Option<ConstStability>,
302         f: impl FnOnce(&mut Self),
303     ) {
304         // These will be `Some` if this item changes the corresponding stability attribute.
305         let mut replaced_parent_depr = None;
306         let mut replaced_parent_stab = None;
307         let mut replaced_parent_const_stab = None;
308
309         if let Some(depr) = depr {
310             replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
311         }
312         if let Some(stab) = stab {
313             replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
314         }
315         if let Some(const_stab) = const_stab {
316             replaced_parent_const_stab =
317                 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
318         }
319
320         f(self);
321
322         if let Some(orig_parent_depr) = replaced_parent_depr {
323             self.parent_depr = orig_parent_depr;
324         }
325         if let Some(orig_parent_stab) = replaced_parent_stab {
326             self.parent_stab = orig_parent_stab;
327         }
328         if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
329             self.parent_const_stab = orig_parent_const_stab;
330         }
331     }
332
333     // returns true if an error occurred, used to suppress some spurious errors
334     fn forbid_staged_api_attrs(
335         &mut self,
336         def_id: LocalDefId,
337         attrs: &[Attribute],
338         inherit_deprecation: InheritDeprecation,
339     ) -> bool {
340         // Emit errors for non-staged-api crates.
341         let unstable_attrs = [
342             sym::unstable,
343             sym::stable,
344             sym::rustc_deprecated,
345             sym::rustc_const_unstable,
346             sym::rustc_const_stable,
347         ];
348         let mut has_error = false;
349         for attr in attrs {
350             let name = attr.name_or_empty();
351             if unstable_attrs.contains(&name) {
352                 struct_span_err!(
353                     self.tcx.sess,
354                     attr.span,
355                     E0734,
356                     "stability attributes may not be used outside of the standard library",
357                 )
358                 .emit();
359                 has_error = true;
360             }
361         }
362
363         // Propagate unstability.  This can happen even for non-staged-api crates in case
364         // -Zforce-unstable-if-unmarked is set.
365         if let Some(stab) = self.parent_stab {
366             if inherit_deprecation.yes() && stab.level.is_unstable() {
367                 self.index.stab_map.insert(def_id, stab);
368             }
369         }
370
371         has_error
372     }
373 }
374
375 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
376     /// Because stability levels are scoped lexically, we want to walk
377     /// nested items in the context of the outer item, so enable
378     /// deep-walking.
379     type NestedFilter = nested_filter::All;
380
381     fn nested_visit_map(&mut self) -> Self::Map {
382         self.tcx.hir()
383     }
384
385     fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
386         let orig_in_trait_impl = self.in_trait_impl;
387         let mut kind = AnnotationKind::Required;
388         let mut const_stab_inherit = InheritConstStability::No;
389         let mut fn_sig = None;
390
391         match i.kind {
392             // Inherent impls and foreign modules serve only as containers for other items,
393             // they don't have their own stability. They still can be annotated as unstable
394             // and propagate this unstability to children, but this annotation is completely
395             // optional. They inherit stability from their parents when unannotated.
396             hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
397             | hir::ItemKind::ForeignMod { .. } => {
398                 self.in_trait_impl = false;
399                 kind = AnnotationKind::Container;
400             }
401             hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
402                 self.in_trait_impl = true;
403                 kind = AnnotationKind::DeprecationProhibited;
404                 const_stab_inherit = InheritConstStability::Yes;
405             }
406             hir::ItemKind::Struct(ref sd, _) => {
407                 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
408                     self.annotate(
409                         self.tcx.hir().local_def_id(ctor_hir_id),
410                         i.span,
411                         None,
412                         AnnotationKind::Required,
413                         InheritDeprecation::Yes,
414                         InheritConstStability::No,
415                         InheritStability::Yes,
416                         |_| {},
417                     )
418                 }
419             }
420             hir::ItemKind::Fn(ref item_fn_sig, _, _) => {
421                 fn_sig = Some(item_fn_sig);
422             }
423             _ => {}
424         }
425
426         self.annotate(
427             i.def_id,
428             i.span,
429             fn_sig,
430             kind,
431             InheritDeprecation::Yes,
432             const_stab_inherit,
433             InheritStability::No,
434             |v| intravisit::walk_item(v, i),
435         );
436         self.in_trait_impl = orig_in_trait_impl;
437     }
438
439     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
440         let fn_sig = match ti.kind {
441             hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
442             _ => None,
443         };
444
445         self.annotate(
446             ti.def_id,
447             ti.span,
448             fn_sig,
449             AnnotationKind::Required,
450             InheritDeprecation::Yes,
451             InheritConstStability::No,
452             InheritStability::No,
453             |v| {
454                 intravisit::walk_trait_item(v, ti);
455             },
456         );
457     }
458
459     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
460         let kind =
461             if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
462
463         let fn_sig = match ii.kind {
464             hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
465             _ => None,
466         };
467
468         self.annotate(
469             ii.def_id,
470             ii.span,
471             fn_sig,
472             kind,
473             InheritDeprecation::Yes,
474             InheritConstStability::No,
475             InheritStability::No,
476             |v| {
477                 intravisit::walk_impl_item(v, ii);
478             },
479         );
480     }
481
482     fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
483         self.annotate(
484             self.tcx.hir().local_def_id(var.id),
485             var.span,
486             None,
487             AnnotationKind::Required,
488             InheritDeprecation::Yes,
489             InheritConstStability::No,
490             InheritStability::Yes,
491             |v| {
492                 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
493                     v.annotate(
494                         v.tcx.hir().local_def_id(ctor_hir_id),
495                         var.span,
496                         None,
497                         AnnotationKind::Required,
498                         InheritDeprecation::Yes,
499                         InheritConstStability::No,
500                         InheritStability::No,
501                         |_| {},
502                     );
503                 }
504
505                 intravisit::walk_variant(v, var, g, item_id)
506             },
507         )
508     }
509
510     fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
511         self.annotate(
512             self.tcx.hir().local_def_id(s.hir_id),
513             s.span,
514             None,
515             AnnotationKind::Required,
516             InheritDeprecation::Yes,
517             InheritConstStability::No,
518             InheritStability::Yes,
519             |v| {
520                 intravisit::walk_field_def(v, s);
521             },
522         );
523     }
524
525     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
526         self.annotate(
527             i.def_id,
528             i.span,
529             None,
530             AnnotationKind::Required,
531             InheritDeprecation::Yes,
532             InheritConstStability::No,
533             InheritStability::No,
534             |v| {
535                 intravisit::walk_foreign_item(v, i);
536             },
537         );
538     }
539
540     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
541         let kind = match &p.kind {
542             // Allow stability attributes on default generic arguments.
543             hir::GenericParamKind::Type { default: Some(_), .. }
544             | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
545             _ => AnnotationKind::Prohibited,
546         };
547
548         self.annotate(
549             self.tcx.hir().local_def_id(p.hir_id),
550             p.span,
551             None,
552             kind,
553             InheritDeprecation::No,
554             InheritConstStability::No,
555             InheritStability::No,
556             |v| {
557                 intravisit::walk_generic_param(v, p);
558             },
559         );
560     }
561 }
562
563 struct MissingStabilityAnnotations<'tcx> {
564     tcx: TyCtxt<'tcx>,
565     access_levels: &'tcx AccessLevels,
566 }
567
568 impl<'tcx> MissingStabilityAnnotations<'tcx> {
569     fn check_missing_stability(&self, def_id: LocalDefId, span: Span) {
570         let stab = self.tcx.stability().local_stability(def_id);
571         if !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(def_id) {
572             let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
573             self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
574         }
575     }
576
577     fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) {
578         if !self.tcx.features().staged_api {
579             return;
580         }
581
582         let is_const = self.tcx.is_const_fn(def_id.to_def_id());
583         let is_stable = self
584             .tcx
585             .lookup_stability(def_id)
586             .map_or(false, |stability| stability.level.is_stable());
587         let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none();
588         let is_reachable = self.access_levels.is_reachable(def_id);
589
590         if is_const && is_stable && missing_const_stability_attribute && is_reachable {
591             let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
592             self.tcx.sess.span_err(span, &format!("{descr} has missing const stability attribute"));
593         }
594     }
595 }
596
597 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
598     type NestedFilter = nested_filter::OnlyBodies;
599
600     fn nested_visit_map(&mut self) -> Self::Map {
601         self.tcx.hir()
602     }
603
604     fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
605         // Inherent impls and foreign modules serve only as containers for other items,
606         // they don't have their own stability. They still can be annotated as unstable
607         // and propagate this unstability to children, but this annotation is completely
608         // optional. They inherit stability from their parents when unannotated.
609         if !matches!(
610             i.kind,
611             hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
612                 | hir::ItemKind::ForeignMod { .. }
613         ) {
614             self.check_missing_stability(i.def_id, i.span);
615         }
616
617         // Ensure stable `const fn` have a const stability attribute.
618         self.check_missing_const_stability(i.def_id, i.span);
619
620         intravisit::walk_item(self, i)
621     }
622
623     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
624         self.check_missing_stability(ti.def_id, ti.span);
625         intravisit::walk_trait_item(self, ti);
626     }
627
628     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
629         let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id());
630         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
631             self.check_missing_stability(ii.def_id, ii.span);
632             self.check_missing_const_stability(ii.def_id, ii.span);
633         }
634         intravisit::walk_impl_item(self, ii);
635     }
636
637     fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
638         self.check_missing_stability(self.tcx.hir().local_def_id(var.id), var.span);
639         intravisit::walk_variant(self, var, g, item_id);
640     }
641
642     fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
643         self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
644         intravisit::walk_field_def(self, s);
645     }
646
647     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
648         self.check_missing_stability(i.def_id, i.span);
649         intravisit::walk_foreign_item(self, i);
650     }
651     // Note that we don't need to `check_missing_stability` for default generic parameters,
652     // as we assume that any default generic parameters without attributes are automatically
653     // stable (assuming they have not inherited instability from their parent).
654 }
655
656 fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
657     let is_staged_api =
658         tcx.sess.opts.debugging_opts.force_unstable_if_unmarked || tcx.features().staged_api;
659     let mut staged_api = FxHashMap::default();
660     staged_api.insert(LOCAL_CRATE, is_staged_api);
661     let mut index = Index {
662         staged_api,
663         stab_map: Default::default(),
664         const_stab_map: Default::default(),
665         depr_map: Default::default(),
666         active_features: Default::default(),
667     };
668
669     let active_lib_features = &tcx.features().declared_lib_features;
670     let active_lang_features = &tcx.features().declared_lang_features;
671
672     // Put the active features into a map for quick lookup.
673     index.active_features = active_lib_features
674         .iter()
675         .map(|&(s, ..)| s)
676         .chain(active_lang_features.iter().map(|&(s, ..)| s))
677         .collect();
678
679     {
680         let mut annotator = Annotator {
681             tcx,
682             index: &mut index,
683             parent_stab: None,
684             parent_const_stab: None,
685             parent_depr: None,
686             in_trait_impl: false,
687         };
688
689         // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
690         // a parent stability annotation which indicates that this is private
691         // with the `rustc_private` feature. This is intended for use when
692         // compiling `librustc_*` crates themselves so we can leverage crates.io
693         // while maintaining the invariant that all sysroot crates are unstable
694         // by default and are unable to be used.
695         if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
696             let reason = "this crate is being loaded from the sysroot, an \
697                           unstable location; did you mean to load this crate \
698                           from crates.io via `Cargo.toml` instead?";
699             let stability = Stability {
700                 level: attr::StabilityLevel::Unstable {
701                     reason: Some(Symbol::intern(reason)),
702                     issue: NonZeroU32::new(27812),
703                     is_soft: false,
704                 },
705                 feature: sym::rustc_private,
706             };
707             annotator.parent_stab = Some(stability);
708         }
709
710         annotator.annotate(
711             CRATE_DEF_ID,
712             tcx.hir().span(CRATE_HIR_ID),
713             None,
714             AnnotationKind::Required,
715             InheritDeprecation::Yes,
716             InheritConstStability::No,
717             InheritStability::No,
718             |v| tcx.hir().walk_toplevel_module(v),
719         );
720     }
721     index
722 }
723
724 /// Cross-references the feature names of unstable APIs with enabled
725 /// features and possibly prints errors.
726 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
727     tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
728 }
729
730 pub(crate) fn provide(providers: &mut Providers) {
731     *providers = Providers { check_mod_unstable_api_usage, stability_index, ..*providers };
732 }
733
734 struct Checker<'tcx> {
735     tcx: TyCtxt<'tcx>,
736 }
737
738 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
739     type NestedFilter = nested_filter::OnlyBodies;
740
741     /// Because stability levels are scoped lexically, we want to walk
742     /// nested items in the context of the outer item, so enable
743     /// deep-walking.
744     fn nested_visit_map(&mut self) -> Self::Map {
745         self.tcx.hir()
746     }
747
748     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
749         match item.kind {
750             hir::ItemKind::ExternCrate(_) => {
751                 // compiler-generated `extern crate` items have a dummy span.
752                 // `std` is still checked for the `restricted-std` feature.
753                 if item.span.is_dummy() && item.ident.as_str() != "std" {
754                     return;
755                 }
756
757                 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id) else {
758                     return;
759                 };
760                 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
761                 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
762             }
763
764             // For implementations of traits, check the stability of each item
765             // individually as it's possible to have a stable trait with unstable
766             // items.
767             hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => {
768                 if self.tcx.features().staged_api {
769                     // If this impl block has an #[unstable] attribute, give an
770                     // error if all involved types and traits are stable, because
771                     // it will have no effect.
772                     // See: https://github.com/rust-lang/rust/issues/55436
773                     let attrs = self.tcx.hir().attrs(item.hir_id());
774                     if let (Some((Stability { level: attr::Unstable { .. }, .. }, span)), _) =
775                         attr::find_stability(&self.tcx.sess, attrs, item.span)
776                     {
777                         let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
778                         c.visit_ty(self_ty);
779                         c.visit_trait_ref(t);
780                         if c.fully_stable {
781                             self.tcx.struct_span_lint_hir(
782                                 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
783                                 item.hir_id(),
784                                 span,
785                                 |lint| lint
786                                     .build("an `#[unstable]` annotation here has no effect")
787                                     .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
788                                     .emit()
789                             );
790                         }
791                     }
792                 }
793
794                 for impl_item_ref in items {
795                     let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
796
797                     if let Some(def_id) = impl_item.trait_item_def_id {
798                         // Pass `None` to skip deprecation warnings.
799                         self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
800                     }
801                 }
802             }
803
804             // There's no good place to insert stability check for non-Copy unions,
805             // so semi-randomly perform it here in stability.rs
806             hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
807                 let ty = self.tcx.type_of(item.def_id);
808                 let ty::Adt(adt_def, substs) = ty.kind() else { bug!() };
809
810                 // Non-`Copy` fields are unstable, except for `ManuallyDrop`.
811                 let param_env = self.tcx.param_env(item.def_id);
812                 for field in &adt_def.non_enum_variant().fields {
813                     let field_ty = field.ty(self.tcx, substs);
814                     if !field_ty.ty_adt_def().map_or(false, |adt_def| adt_def.is_manually_drop())
815                         && !field_ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), param_env)
816                     {
817                         if field_ty.needs_drop(self.tcx, param_env) {
818                             // Avoid duplicate error: This will error later anyway because fields
819                             // that need drop are not allowed.
820                             self.tcx.sess.delay_span_bug(
821                                 item.span,
822                                 "union should have been rejected due to potentially dropping field",
823                             );
824                         } else {
825                             feature_err(
826                                 &self.tcx.sess.parse_sess,
827                                 sym::untagged_unions,
828                                 self.tcx.def_span(field.did),
829                                 "unions with non-`Copy` fields other than `ManuallyDrop<T>` are unstable",
830                             )
831                             .emit();
832                         }
833                     }
834                 }
835             }
836
837             _ => (/* pass */),
838         }
839         intravisit::walk_item(self, item);
840     }
841
842     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
843         if let Some(def_id) = path.res.opt_def_id() {
844             let method_span = path.segments.last().map(|s| s.ident.span);
845             self.tcx.check_stability(def_id, Some(id), path.span, method_span)
846         }
847         intravisit::walk_path(self, path)
848     }
849 }
850
851 struct CheckTraitImplStable<'tcx> {
852     tcx: TyCtxt<'tcx>,
853     fully_stable: bool,
854 }
855
856 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
857     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
858         if let Some(def_id) = path.res.opt_def_id() {
859             if let Some(stab) = self.tcx.lookup_stability(def_id) {
860                 self.fully_stable &= stab.level.is_stable();
861             }
862         }
863         intravisit::walk_path(self, path)
864     }
865
866     fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
867         if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
868             if let Some(stab) = self.tcx.lookup_stability(trait_did) {
869                 self.fully_stable &= stab.level.is_stable();
870             }
871         }
872         intravisit::walk_trait_ref(self, t)
873     }
874
875     fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
876         if let TyKind::Never = t.kind {
877             self.fully_stable = false;
878         }
879         intravisit::walk_ty(self, t)
880     }
881 }
882
883 /// Given the list of enabled features that were not language features (i.e., that
884 /// were expected to be library features), and the list of features used from
885 /// libraries, identify activated features that don't exist and error about them.
886 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
887     let access_levels = &tcx.privacy_access_levels(());
888
889     if tcx.stability().staged_api[&LOCAL_CRATE] {
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().visit_all_item_likes(&mut missing.as_deep_visitor());
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 = FxHashMap::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 FxHashMap<_, _>, 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 }