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