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