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