]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/stability.rs
Auto merge of #76035 - tiagolam:master, r=pietroalbini
[rust.git] / src / librustc_passes / 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, 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::query::Providers;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_session::lint;
19 use rustc_session::parse::feature_err;
20 use rustc_session::Session;
21 use rustc_span::symbol::{sym, Symbol};
22 use rustc_span::Span;
23 use rustc_trait_selection::traits::misc::can_type_implement_copy;
24
25 use std::cmp::Ordering;
26 use std::mem::replace;
27 use std::num::NonZeroU32;
28
29 #[derive(PartialEq)]
30 enum AnnotationKind {
31     // Annotation is required if not inherited from unstable parents
32     Required,
33     // Annotation is useless, reject it
34     Prohibited,
35     // Annotation itself is useless, but it can be propagated to children
36     Container,
37 }
38
39 // A private tree-walker for producing an Index.
40 struct Annotator<'a, 'tcx> {
41     tcx: TyCtxt<'tcx>,
42     index: &'a mut Index<'tcx>,
43     parent_stab: Option<&'tcx Stability>,
44     parent_const_stab: Option<&'tcx ConstStability>,
45     parent_depr: Option<DeprecationEntry>,
46     in_trait_impl: bool,
47 }
48
49 impl<'a, 'tcx> Annotator<'a, 'tcx> {
50     // Determine the stability for a node based on its attributes and inherited
51     // stability. The stability is recorded in the index and used as the parent.
52     fn annotate<F>(
53         &mut self,
54         hir_id: HirId,
55         attrs: &[Attribute],
56         item_sp: Span,
57         kind: AnnotationKind,
58         visit_children: F,
59     ) where
60         F: FnOnce(&mut Self),
61     {
62         debug!("annotate(id = {:?}, attrs = {:?})", hir_id, attrs);
63         let mut did_error = false;
64         if !self.tcx.features().staged_api {
65             did_error = self.forbid_staged_api_attrs(hir_id, attrs);
66         }
67
68         let depr =
69             if did_error { None } else { attr::find_deprecation(&self.tcx.sess, attrs, item_sp) };
70         let mut is_deprecated = false;
71         if let Some(depr) = &depr {
72             is_deprecated = true;
73
74             if kind == AnnotationKind::Prohibited {
75                 self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
76             }
77
78             // `Deprecation` is just two pointers, no need to intern it
79             let depr_entry = DeprecationEntry::local(depr.clone(), hir_id);
80             self.index.depr_map.insert(hir_id, depr_entry);
81         } else if let Some(parent_depr) = self.parent_depr.clone() {
82             is_deprecated = true;
83             info!("tagging child {:?} as deprecated from parent", hir_id);
84             self.index.depr_map.insert(hir_id, parent_depr);
85         }
86
87         if self.tcx.features().staged_api {
88             if let Some(..) = attrs.iter().find(|a| self.tcx.sess.check_name(a, sym::deprecated)) {
89                 self.tcx.sess.span_err(
90                     item_sp,
91                     "`#[deprecated]` cannot be used in staged API; \
92                                                 use `#[rustc_deprecated]` instead",
93                 );
94             }
95         } else {
96             self.recurse_with_stability_attrs(
97                 depr.map(|d| DeprecationEntry::local(d, hir_id)),
98                 None,
99                 None,
100                 visit_children,
101             );
102             return;
103         }
104
105         let (stab, const_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
106
107         let const_stab = const_stab.map(|const_stab| {
108             let const_stab = self.tcx.intern_const_stability(const_stab);
109             self.index.const_stab_map.insert(hir_id, const_stab);
110             const_stab
111         });
112
113         if const_stab.is_none() {
114             debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
115             if let Some(parent) = self.parent_const_stab {
116                 if parent.level.is_unstable() {
117                     self.index.const_stab_map.insert(hir_id, parent);
118                 }
119             }
120         }
121
122         if depr.as_ref().map_or(false, |d| d.is_since_rustc_version) {
123             if stab.is_none() {
124                 struct_span_err!(
125                     self.tcx.sess,
126                     item_sp,
127                     E0549,
128                     "rustc_deprecated attribute must be paired with \
129                     either stable or unstable attribute"
130                 )
131                 .emit();
132             }
133         }
134
135         let stab = stab.map(|stab| {
136             // Error if prohibited, or can't inherit anything from a container.
137             if kind == AnnotationKind::Prohibited
138                 || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated)
139             {
140                 self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
141             }
142
143             debug!("annotate: found {:?}", stab);
144             let stab = self.tcx.intern_stability(stab);
145
146             // Check if deprecated_since < stable_since. If it is,
147             // this is *almost surely* an accident.
148             if let (&Some(dep_since), &attr::Stable { since: stab_since }) =
149                 (&depr.as_ref().and_then(|d| d.since), &stab.level)
150             {
151                 // Explicit version of iter::order::lt to handle parse errors properly
152                 for (dep_v, stab_v) in
153                     dep_since.as_str().split('.').zip(stab_since.as_str().split('.'))
154                 {
155                     if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
156                         match dep_v.cmp(&stab_v) {
157                             Ordering::Less => {
158                                 self.tcx.sess.span_err(
159                                     item_sp,
160                                     "An API can't be stabilized \
161                                                                  after it is deprecated",
162                                 );
163                                 break;
164                             }
165                             Ordering::Equal => continue,
166                             Ordering::Greater => break,
167                         }
168                     } else {
169                         // Act like it isn't less because the question is now nonsensical,
170                         // and this makes us not do anything else interesting.
171                         self.tcx.sess.span_err(
172                             item_sp,
173                             "Invalid stability or deprecation \
174                                                          version found",
175                         );
176                         break;
177                     }
178                 }
179             }
180
181             self.index.stab_map.insert(hir_id, stab);
182             stab
183         });
184
185         if stab.is_none() {
186             debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
187             if let Some(stab) = self.parent_stab {
188                 if stab.level.is_unstable() {
189                     self.index.stab_map.insert(hir_id, stab);
190                 }
191             }
192         }
193
194         self.recurse_with_stability_attrs(
195             depr.map(|d| DeprecationEntry::local(d, hir_id)),
196             stab,
197             const_stab,
198             visit_children,
199         );
200     }
201
202     fn recurse_with_stability_attrs(
203         &mut self,
204         depr: Option<DeprecationEntry>,
205         stab: Option<&'tcx Stability>,
206         const_stab: Option<&'tcx ConstStability>,
207         f: impl FnOnce(&mut Self),
208     ) {
209         // These will be `Some` if this item changes the corresponding stability attribute.
210         let mut replaced_parent_depr = None;
211         let mut replaced_parent_stab = None;
212         let mut replaced_parent_const_stab = None;
213
214         if let Some(depr) = depr {
215             replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
216         }
217         if let Some(stab) = stab {
218             replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
219         }
220         if let Some(const_stab) = const_stab {
221             replaced_parent_const_stab =
222                 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
223         }
224
225         f(self);
226
227         if let Some(orig_parent_depr) = replaced_parent_depr {
228             self.parent_depr = orig_parent_depr;
229         }
230         if let Some(orig_parent_stab) = replaced_parent_stab {
231             self.parent_stab = orig_parent_stab;
232         }
233         if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
234             self.parent_const_stab = orig_parent_const_stab;
235         }
236     }
237
238     // returns true if an error occurred, used to suppress some spurious errors
239     fn forbid_staged_api_attrs(&mut self, hir_id: HirId, attrs: &[Attribute]) -> bool {
240         // Emit errors for non-staged-api crates.
241         let unstable_attrs = [
242             sym::unstable,
243             sym::stable,
244             sym::rustc_deprecated,
245             sym::rustc_const_unstable,
246             sym::rustc_const_stable,
247         ];
248         let mut has_error = false;
249         for attr in attrs {
250             let name = attr.name_or_empty();
251             if unstable_attrs.contains(&name) {
252                 self.tcx.sess.mark_attr_used(attr);
253                 struct_span_err!(
254                     self.tcx.sess,
255                     attr.span,
256                     E0734,
257                     "stability attributes may not be used outside of the standard library",
258                 )
259                 .emit();
260                 has_error = true;
261             }
262         }
263
264         // Propagate unstability.  This can happen even for non-staged-api crates in case
265         // -Zforce-unstable-if-unmarked is set.
266         if let Some(stab) = self.parent_stab {
267             if stab.level.is_unstable() {
268                 self.index.stab_map.insert(hir_id, stab);
269             }
270         }
271
272         has_error
273     }
274 }
275
276 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
277     /// Because stability levels are scoped lexically, we want to walk
278     /// nested items in the context of the outer item, so enable
279     /// deep-walking.
280     type Map = Map<'tcx>;
281
282     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
283         NestedVisitorMap::All(self.tcx.hir())
284     }
285
286     fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
287         let orig_in_trait_impl = self.in_trait_impl;
288         let mut kind = AnnotationKind::Required;
289         match i.kind {
290             // Inherent impls and foreign modules serve only as containers for other items,
291             // they don't have their own stability. They still can be annotated as unstable
292             // and propagate this unstability to children, but this annotation is completely
293             // optional. They inherit stability from their parents when unannotated.
294             hir::ItemKind::Impl { of_trait: None, .. } | hir::ItemKind::ForeignMod(..) => {
295                 self.in_trait_impl = false;
296                 kind = AnnotationKind::Container;
297             }
298             hir::ItemKind::Impl { of_trait: Some(_), .. } => {
299                 self.in_trait_impl = true;
300             }
301             hir::ItemKind::Struct(ref sd, _) => {
302                 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
303                     self.annotate(ctor_hir_id, &i.attrs, i.span, AnnotationKind::Required, |_| {})
304                 }
305             }
306             _ => {}
307         }
308
309         self.annotate(i.hir_id, &i.attrs, i.span, kind, |v| intravisit::walk_item(v, i));
310         self.in_trait_impl = orig_in_trait_impl;
311     }
312
313     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
314         self.annotate(ti.hir_id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
315             intravisit::walk_trait_item(v, ti);
316         });
317     }
318
319     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
320         let kind =
321             if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
322         self.annotate(ii.hir_id, &ii.attrs, ii.span, kind, |v| {
323             intravisit::walk_impl_item(v, ii);
324         });
325     }
326
327     fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
328         self.annotate(var.id, &var.attrs, var.span, AnnotationKind::Required, |v| {
329             if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
330                 v.annotate(ctor_hir_id, &var.attrs, var.span, AnnotationKind::Required, |_| {});
331             }
332
333             intravisit::walk_variant(v, var, g, item_id)
334         })
335     }
336
337     fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) {
338         self.annotate(s.hir_id, &s.attrs, s.span, AnnotationKind::Required, |v| {
339             intravisit::walk_struct_field(v, s);
340         });
341     }
342
343     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
344         self.annotate(i.hir_id, &i.attrs, i.span, AnnotationKind::Required, |v| {
345             intravisit::walk_foreign_item(v, i);
346         });
347     }
348
349     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
350         self.annotate(md.hir_id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
351     }
352 }
353
354 struct MissingStabilityAnnotations<'tcx> {
355     tcx: TyCtxt<'tcx>,
356     access_levels: &'tcx AccessLevels,
357 }
358
359 impl<'tcx> MissingStabilityAnnotations<'tcx> {
360     fn check_missing_stability(&self, hir_id: HirId, span: Span) {
361         let stab = self.tcx.stability().local_stability(hir_id);
362         let is_error =
363             !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(hir_id);
364         if is_error {
365             let def_id = self.tcx.hir().local_def_id(hir_id);
366             let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
367             self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
368         }
369     }
370 }
371
372 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
373     type Map = Map<'tcx>;
374
375     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
376         NestedVisitorMap::OnlyBodies(self.tcx.hir())
377     }
378
379     fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
380         match i.kind {
381             // Inherent impls and foreign modules serve only as containers for other items,
382             // they don't have their own stability. They still can be annotated as unstable
383             // and propagate this unstability to children, but this annotation is completely
384             // optional. They inherit stability from their parents when unannotated.
385             hir::ItemKind::Impl { of_trait: None, .. } | hir::ItemKind::ForeignMod(..) => {}
386
387             _ => self.check_missing_stability(i.hir_id, i.span),
388         }
389
390         intravisit::walk_item(self, i)
391     }
392
393     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
394         self.check_missing_stability(ti.hir_id, ti.span);
395         intravisit::walk_trait_item(self, ti);
396     }
397
398     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
399         let impl_def_id = self.tcx.hir().local_def_id(self.tcx.hir().get_parent_item(ii.hir_id));
400         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
401             self.check_missing_stability(ii.hir_id, ii.span);
402         }
403         intravisit::walk_impl_item(self, ii);
404     }
405
406     fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
407         self.check_missing_stability(var.id, var.span);
408         intravisit::walk_variant(self, var, g, item_id);
409     }
410
411     fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) {
412         self.check_missing_stability(s.hir_id, s.span);
413         intravisit::walk_struct_field(self, s);
414     }
415
416     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
417         self.check_missing_stability(i.hir_id, i.span);
418         intravisit::walk_foreign_item(self, i);
419     }
420
421     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
422         self.check_missing_stability(md.hir_id, md.span);
423     }
424 }
425
426 fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> {
427     let is_staged_api =
428         tcx.sess.opts.debugging_opts.force_unstable_if_unmarked || tcx.features().staged_api;
429     let mut staged_api = FxHashMap::default();
430     staged_api.insert(LOCAL_CRATE, is_staged_api);
431     let mut index = Index {
432         staged_api,
433         stab_map: Default::default(),
434         const_stab_map: Default::default(),
435         depr_map: Default::default(),
436         active_features: Default::default(),
437     };
438
439     let active_lib_features = &tcx.features().declared_lib_features;
440     let active_lang_features = &tcx.features().declared_lang_features;
441
442     // Put the active features into a map for quick lookup.
443     index.active_features = active_lib_features
444         .iter()
445         .map(|&(s, ..)| s)
446         .chain(active_lang_features.iter().map(|&(s, ..)| s))
447         .collect();
448
449     {
450         let krate = tcx.hir().krate();
451         let mut annotator = Annotator {
452             tcx,
453             index: &mut index,
454             parent_stab: None,
455             parent_const_stab: None,
456             parent_depr: None,
457             in_trait_impl: false,
458         };
459
460         // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
461         // a parent stability annotation which indicates that this is private
462         // with the `rustc_private` feature. This is intended for use when
463         // compiling `librustc_*` crates themselves so we can leverage crates.io
464         // while maintaining the invariant that all sysroot crates are unstable
465         // by default and are unable to be used.
466         if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
467             let reason = "this crate is being loaded from the sysroot, an \
468                           unstable location; did you mean to load this crate \
469                           from crates.io via `Cargo.toml` instead?";
470             let stability = tcx.intern_stability(Stability {
471                 level: attr::StabilityLevel::Unstable {
472                     reason: Some(Symbol::intern(reason)),
473                     issue: NonZeroU32::new(27812),
474                     is_soft: false,
475                 },
476                 feature: sym::rustc_private,
477             });
478             annotator.parent_stab = Some(stability);
479         }
480
481         annotator.annotate(
482             hir::CRATE_HIR_ID,
483             &krate.item.attrs,
484             krate.item.span,
485             AnnotationKind::Required,
486             |v| intravisit::walk_crate(v, krate),
487         );
488     }
489     index
490 }
491
492 /// Cross-references the feature names of unstable APIs with enabled
493 /// features and possibly prints errors.
494 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
495     tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
496 }
497
498 pub(crate) fn provide(providers: &mut Providers) {
499     *providers = Providers { check_mod_unstable_api_usage, ..*providers };
500     providers.stability_index = |tcx, cnum| {
501         assert_eq!(cnum, LOCAL_CRATE);
502         new_index(tcx)
503     };
504 }
505
506 struct Checker<'tcx> {
507     tcx: TyCtxt<'tcx>,
508 }
509
510 impl Visitor<'tcx> for Checker<'tcx> {
511     type Map = Map<'tcx>;
512
513     /// Because stability levels are scoped lexically, we want to walk
514     /// nested items in the context of the outer item, so enable
515     /// deep-walking.
516     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
517         NestedVisitorMap::OnlyBodies(self.tcx.hir())
518     }
519
520     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
521         match item.kind {
522             hir::ItemKind::ExternCrate(_) => {
523                 // compiler-generated `extern crate` items have a dummy span.
524                 // `std` is still checked for the `restricted-std` feature.
525                 if item.span.is_dummy() && item.ident.as_str() != "std" {
526                     return;
527                 }
528
529                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
530                 let cnum = match self.tcx.extern_mod_stmt_cnum(def_id) {
531                     Some(cnum) => cnum,
532                     None => return,
533                 };
534                 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
535                 self.tcx.check_stability(def_id, Some(item.hir_id), item.span);
536             }
537
538             // For implementations of traits, check the stability of each item
539             // individually as it's possible to have a stable trait with unstable
540             // items.
541             hir::ItemKind::Impl { of_trait: Some(ref t), items, .. } => {
542                 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
543                     for impl_item_ref in items {
544                         let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
545                         let trait_item_def_id = self
546                             .tcx
547                             .associated_items(trait_did)
548                             .filter_by_name_unhygienic(impl_item.ident.name)
549                             .next()
550                             .map(|item| item.def_id);
551                         if let Some(def_id) = trait_item_def_id {
552                             // Pass `None` to skip deprecation warnings.
553                             self.tcx.check_stability(def_id, None, impl_item.span);
554                         }
555                     }
556                 }
557             }
558
559             // There's no good place to insert stability check for non-Copy unions,
560             // so semi-randomly perform it here in stability.rs
561             hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
562                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
563                 let adt_def = self.tcx.adt_def(def_id);
564                 let ty = self.tcx.type_of(def_id);
565
566                 if adt_def.has_dtor(self.tcx) {
567                     feature_err(
568                         &self.tcx.sess.parse_sess,
569                         sym::untagged_unions,
570                         item.span,
571                         "unions with `Drop` implementations are unstable",
572                     )
573                     .emit();
574                 } else {
575                     let param_env = self.tcx.param_env(def_id);
576                     if can_type_implement_copy(self.tcx, param_env, ty).is_err() {
577                         feature_err(
578                             &self.tcx.sess.parse_sess,
579                             sym::untagged_unions,
580                             item.span,
581                             "unions with non-`Copy` fields are unstable",
582                         )
583                         .emit();
584                     }
585                 }
586             }
587
588             _ => (/* pass */),
589         }
590         intravisit::walk_item(self, item);
591     }
592
593     fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
594         if let Some(def_id) = path.res.opt_def_id() {
595             self.tcx.check_stability(def_id, Some(id), path.span)
596         }
597         intravisit::walk_path(self, path)
598     }
599 }
600
601 /// Given the list of enabled features that were not language features (i.e., that
602 /// were expected to be library features), and the list of features used from
603 /// libraries, identify activated features that don't exist and error about them.
604 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
605     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
606
607     if tcx.stability().staged_api[&LOCAL_CRATE] {
608         let krate = tcx.hir().krate();
609         let mut missing = MissingStabilityAnnotations { tcx, access_levels };
610         missing.check_missing_stability(hir::CRATE_HIR_ID, krate.item.span);
611         intravisit::walk_crate(&mut missing, krate);
612         krate.visit_all_item_likes(&mut missing.as_deep_visitor());
613     }
614
615     let declared_lang_features = &tcx.features().declared_lang_features;
616     let mut lang_features = FxHashSet::default();
617     for &(feature, span, since) in declared_lang_features {
618         if let Some(since) = since {
619             // Warn if the user has enabled an already-stable lang feature.
620             unnecessary_stable_feature_lint(tcx, span, feature, since);
621         }
622         if !lang_features.insert(feature) {
623             // Warn if the user enables a lang feature multiple times.
624             duplicate_feature_err(tcx.sess, span, feature);
625         }
626     }
627
628     let declared_lib_features = &tcx.features().declared_lib_features;
629     let mut remaining_lib_features = FxHashMap::default();
630     for (feature, span) in declared_lib_features {
631         if remaining_lib_features.contains_key(&feature) {
632             // Warn if the user enables a lib feature multiple times.
633             duplicate_feature_err(tcx.sess, *span, *feature);
634         }
635         remaining_lib_features.insert(feature, *span);
636     }
637     // `stdbuild` has special handling for `libc`, so we need to
638     // recognise the feature when building std.
639     // Likewise, libtest is handled specially, so `test` isn't
640     // available as we'd like it to be.
641     // FIXME: only remove `libc` when `stdbuild` is active.
642     // FIXME: remove special casing for `test`.
643     remaining_lib_features.remove(&sym::libc);
644     remaining_lib_features.remove(&sym::test);
645
646     let check_features = |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &[_]| {
647         for &(feature, since) in defined_features {
648             if let Some(since) = since {
649                 if let Some(span) = remaining_lib_features.get(&feature) {
650                     // Warn if the user has enabled an already-stable lib feature.
651                     unnecessary_stable_feature_lint(tcx, *span, feature, since);
652                 }
653             }
654             remaining_lib_features.remove(&feature);
655             if remaining_lib_features.is_empty() {
656                 break;
657             }
658         }
659     };
660
661     // We always collect the lib features declared in the current crate, even if there are
662     // no unknown features, because the collection also does feature attribute validation.
663     let local_defined_features = tcx.lib_features().to_vec();
664     if !remaining_lib_features.is_empty() {
665         check_features(&mut remaining_lib_features, &local_defined_features);
666
667         for &cnum in &*tcx.crates() {
668             if remaining_lib_features.is_empty() {
669                 break;
670             }
671             check_features(&mut remaining_lib_features, tcx.defined_lib_features(cnum));
672         }
673     }
674
675     for (feature, span) in remaining_lib_features {
676         struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
677     }
678
679     // FIXME(#44232): the `used_features` table no longer exists, so we
680     // don't lint about unused features. We should re-enable this one day!
681 }
682
683 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
684     tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
685         lint.build(&format!(
686             "the feature `{}` has been stable since {} and no longer requires \
687                       an attribute to enable",
688             feature, since
689         ))
690         .emit();
691     });
692 }
693
694 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
695     struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
696         .emit();
697 }