]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
Improve some compiletest documentation
[rust.git] / src / librustc / middle / 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 pub use self::StabilityLevel::*;
5
6 use crate::lint::{self, Lint, in_derive_expansion};
7 use crate::hir::{self, Item, Generics, StructField, Variant, HirId};
8 use crate::hir::def::Def;
9 use crate::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
10 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
11 use crate::ty::query::Providers;
12 use crate::middle::privacy::AccessLevels;
13 use crate::session::{DiagnosticMessageId, Session};
14 use syntax::symbol::Symbol;
15 use syntax_pos::{Span, MultiSpan};
16 use syntax::ast::Attribute;
17 use syntax::errors::Applicability;
18 use syntax::feature_gate::{GateIssue, emit_feature_err};
19 use syntax::attr::{self, Stability, Deprecation};
20 use crate::ty::{self, TyCtxt};
21 use crate::util::nodemap::{FxHashSet, FxHashMap};
22
23 use std::mem::replace;
24 use std::cmp::Ordering;
25
26 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
27 pub enum StabilityLevel {
28     Unstable,
29     Stable,
30 }
31
32 impl StabilityLevel {
33     pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
34         if level.is_stable() { Stable } else { Unstable }
35     }
36 }
37
38 #[derive(PartialEq)]
39 enum AnnotationKind {
40     // Annotation is required if not inherited from unstable parents
41     Required,
42     // Annotation is useless, reject it
43     Prohibited,
44     // Annotation itself is useless, but it can be propagated to children
45     Container,
46 }
47
48 /// An entry in the `depr_map`.
49 #[derive(Clone)]
50 pub struct DeprecationEntry {
51     /// The metadata of the attribute associated with this entry.
52     pub attr: Deprecation,
53     /// The `DefId` where the attr was originally attached. `None` for non-local
54     /// `DefId`'s.
55     origin: Option<HirId>,
56 }
57
58 impl_stable_hash_for!(struct self::DeprecationEntry {
59     attr,
60     origin
61 });
62
63 impl DeprecationEntry {
64     fn local(attr: Deprecation, id: HirId) -> DeprecationEntry {
65         DeprecationEntry {
66             attr,
67             origin: Some(id),
68         }
69     }
70
71     pub fn external(attr: Deprecation) -> DeprecationEntry {
72         DeprecationEntry {
73             attr,
74             origin: None,
75         }
76     }
77
78     pub fn same_origin(&self, other: &DeprecationEntry) -> bool {
79         match (self.origin, other.origin) {
80             (Some(o1), Some(o2)) => o1 == o2,
81             _ => false
82         }
83     }
84 }
85
86 /// A stability index, giving the stability level for items and methods.
87 pub struct Index<'tcx> {
88     /// This is mostly a cache, except the stabilities of local items
89     /// are filled by the annotator.
90     stab_map: FxHashMap<HirId, &'tcx Stability>,
91     depr_map: FxHashMap<HirId, DeprecationEntry>,
92
93     /// Maps for each crate whether it is part of the staged API.
94     staged_api: FxHashMap<CrateNum, bool>,
95
96     /// Features enabled for this crate.
97     active_features: FxHashSet<Symbol>,
98 }
99
100 impl_stable_hash_for!(struct self::Index<'tcx> {
101     stab_map,
102     depr_map,
103     staged_api,
104     active_features
105 });
106
107 // A private tree-walker for producing an Index.
108 struct Annotator<'a, 'tcx: 'a> {
109     tcx: TyCtxt<'a, 'tcx, 'tcx>,
110     index: &'a mut Index<'tcx>,
111     parent_stab: Option<&'tcx Stability>,
112     parent_depr: Option<DeprecationEntry>,
113     in_trait_impl: bool,
114 }
115
116 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
117     // Determine the stability for a node based on its attributes and inherited
118     // stability. The stability is recorded in the index and used as the parent.
119     fn annotate<F>(&mut self, hir_id: HirId, attrs: &[Attribute],
120                    item_sp: Span, kind: AnnotationKind, visit_children: F)
121         where F: FnOnce(&mut Self)
122     {
123         if self.tcx.features().staged_api {
124             // This crate explicitly wants staged API.
125             debug!("annotate(id = {:?}, attrs = {:?})", hir_id, attrs);
126             if let Some(..) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) {
127                 self.tcx.sess.span_err(item_sp, "`#[deprecated]` cannot be used in staged api, \
128                                                  use `#[rustc_deprecated]` instead");
129             }
130             if let Some(mut stab) = attr::find_stability(&self.tcx.sess.parse_sess,
131                                                          attrs, item_sp) {
132                 // Error if prohibited, or can't inherit anything from a container
133                 if kind == AnnotationKind::Prohibited ||
134                    (kind == AnnotationKind::Container &&
135                     stab.level.is_stable() &&
136                     stab.rustc_depr.is_none()) {
137                     self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
138                 }
139
140                 debug!("annotate: found {:?}", stab);
141                 // If parent is deprecated and we're not, inherit this by merging
142                 // deprecated_since and its reason.
143                 if let Some(parent_stab) = self.parent_stab {
144                     if parent_stab.rustc_depr.is_some() && stab.rustc_depr.is_none() {
145                         stab.rustc_depr = parent_stab.rustc_depr.clone()
146                     }
147                 }
148
149                 let stab = self.tcx.intern_stability(stab);
150
151                 // Check if deprecated_since < stable_since. If it is,
152                 // this is *almost surely* an accident.
153                 if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
154                         &attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
155                     // Explicit version of iter::order::lt to handle parse errors properly
156                     for (dep_v, stab_v) in dep_since.as_str()
157                                                     .split('.')
158                                                     .zip(stab_since.as_str().split('.'))
159                     {
160                         if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
161                             match dep_v.cmp(&stab_v) {
162                                 Ordering::Less => {
163                                     self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
164                                                                      after it is deprecated");
165                                     break
166                                 }
167                                 Ordering::Equal => continue,
168                                 Ordering::Greater => break,
169                             }
170                         } else {
171                             // Act like it isn't less because the question is now nonsensical,
172                             // and this makes us not do anything else interesting.
173                             self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
174                                                              version found");
175                             break
176                         }
177                     }
178                 }
179
180                 self.index.stab_map.insert(hir_id, stab);
181
182                 let orig_parent_stab = replace(&mut self.parent_stab, Some(stab));
183                 visit_children(self);
184                 self.parent_stab = orig_parent_stab;
185             } else {
186                 debug!("annotate: 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                 visit_children(self);
193             }
194         } else {
195             // Emit errors for non-staged-api crates.
196             for attr in attrs {
197                 if let Some(tag) = attr.ident_str() {
198                     if tag == "unstable" || tag == "stable" || tag == "rustc_deprecated" {
199                         attr::mark_used(attr);
200                         self.tcx.sess.span_err(attr.span, "stability attributes may not be used \
201                                                            outside of the standard library");
202                     }
203                 }
204             }
205
206             // Propagate unstability.  This can happen even for non-staged-api crates in case
207             // -Zforce-unstable-if-unmarked is set.
208             if let Some(stab) = self.parent_stab {
209                 if stab.level.is_unstable() {
210                     self.index.stab_map.insert(hir_id, stab);
211                 }
212             }
213
214             if let Some(depr) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) {
215                 if kind == AnnotationKind::Prohibited {
216                     self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
217                 }
218
219                 // `Deprecation` is just two pointers, no need to intern it
220                 let depr_entry = DeprecationEntry::local(depr, hir_id);
221                 self.index.depr_map.insert(hir_id, depr_entry.clone());
222
223                 let orig_parent_depr = replace(&mut self.parent_depr,
224                                                Some(depr_entry));
225                 visit_children(self);
226                 self.parent_depr = orig_parent_depr;
227             } else if let Some(parent_depr) = self.parent_depr.clone() {
228                 self.index.depr_map.insert(hir_id, parent_depr);
229                 visit_children(self);
230             } else {
231                 visit_children(self);
232             }
233         }
234     }
235 }
236
237 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
238     /// Because stability levels are scoped lexically, we want to walk
239     /// nested items in the context of the outer item, so enable
240     /// deep-walking.
241     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
242         NestedVisitorMap::All(&self.tcx.hir())
243     }
244
245     fn visit_item(&mut self, i: &'tcx Item) {
246         let orig_in_trait_impl = self.in_trait_impl;
247         let mut kind = AnnotationKind::Required;
248         match i.node {
249             // Inherent impls and foreign modules serve only as containers for other items,
250             // they don't have their own stability. They still can be annotated as unstable
251             // and propagate this unstability to children, but this annotation is completely
252             // optional. They inherit stability from their parents when unannotated.
253             hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {
254                 self.in_trait_impl = false;
255                 kind = AnnotationKind::Container;
256             }
257             hir::ItemKind::Impl(.., Some(_), _, _) => {
258                 self.in_trait_impl = true;
259             }
260             hir::ItemKind::Struct(ref sd, _) => {
261                 if !sd.is_struct() {
262                     self.annotate(sd.hir_id(), &i.attrs, i.span, AnnotationKind::Required, |_| {})
263                 }
264             }
265             _ => {}
266         }
267
268         self.annotate(i.hir_id, &i.attrs, i.span, kind, |v| {
269             intravisit::walk_item(v, i)
270         });
271         self.in_trait_impl = orig_in_trait_impl;
272     }
273
274     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
275         self.annotate(ti.hir_id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
276             intravisit::walk_trait_item(v, ti);
277         });
278     }
279
280     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
281         let kind = if self.in_trait_impl {
282             AnnotationKind::Prohibited
283         } else {
284             AnnotationKind::Required
285         };
286         self.annotate(ii.hir_id, &ii.attrs, ii.span, kind, |v| {
287             intravisit::walk_impl_item(v, ii);
288         });
289     }
290
291     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: HirId) {
292         self.annotate(var.node.data.hir_id(), &var.node.attrs, var.span, AnnotationKind::Required,
293             |v| { intravisit::walk_variant(v, var, g, item_id) })
294     }
295
296     fn visit_struct_field(&mut self, s: &'tcx StructField) {
297         self.annotate(s.hir_id, &s.attrs, s.span, AnnotationKind::Required, |v| {
298             intravisit::walk_struct_field(v, s);
299         });
300     }
301
302     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
303         self.annotate(i.hir_id, &i.attrs, i.span, AnnotationKind::Required, |v| {
304             intravisit::walk_foreign_item(v, i);
305         });
306     }
307
308     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
309         self.annotate(md.hir_id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
310     }
311 }
312
313 struct MissingStabilityAnnotations<'a, 'tcx: 'a> {
314     tcx: TyCtxt<'a, 'tcx, 'tcx>,
315     access_levels: &'a AccessLevels,
316 }
317
318 impl<'a, 'tcx: 'a> MissingStabilityAnnotations<'a, 'tcx> {
319     fn check_missing_stability(&self, hir_id: HirId, span: Span, name: &str) {
320         let stab = self.tcx.stability().local_stability(hir_id);
321         let is_error = !self.tcx.sess.opts.test &&
322                         stab.is_none() &&
323                         self.access_levels.is_reachable(hir_id);
324         if is_error {
325             self.tcx.sess.span_err(
326                 span,
327                 &format!("{} has missing stability attribute", name),
328             );
329         }
330     }
331 }
332
333 impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> {
334     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
335         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
336     }
337
338     fn visit_item(&mut self, i: &'tcx Item) {
339         match i.node {
340             // Inherent impls and foreign modules serve only as containers for other items,
341             // they don't have their own stability. They still can be annotated as unstable
342             // and propagate this unstability to children, but this annotation is completely
343             // optional. They inherit stability from their parents when unannotated.
344             hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {}
345
346             _ => self.check_missing_stability(i.hir_id, i.span, i.node.descriptive_variant())
347         }
348
349         intravisit::walk_item(self, i)
350     }
351
352     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
353         self.check_missing_stability(ti.hir_id, ti.span, "item");
354         intravisit::walk_trait_item(self, ti);
355     }
356
357     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
358         let impl_def_id = self.tcx.hir().local_def_id_from_hir_id(
359             self.tcx.hir().get_parent_item(ii.hir_id));
360         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
361             self.check_missing_stability(ii.hir_id, ii.span, "item");
362         }
363         intravisit::walk_impl_item(self, ii);
364     }
365
366     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: HirId) {
367         self.check_missing_stability(var.node.data.hir_id(), var.span, "variant");
368         intravisit::walk_variant(self, var, g, item_id);
369     }
370
371     fn visit_struct_field(&mut self, s: &'tcx StructField) {
372         self.check_missing_stability(s.hir_id, s.span, "field");
373         intravisit::walk_struct_field(self, s);
374     }
375
376     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
377         self.check_missing_stability(i.hir_id, i.span, i.node.descriptive_variant());
378         intravisit::walk_foreign_item(self, i);
379     }
380
381     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
382         self.check_missing_stability(md.hir_id, md.span, "macro");
383     }
384 }
385
386 impl<'a, 'tcx> Index<'tcx> {
387     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Index<'tcx> {
388         let is_staged_api =
389             tcx.sess.opts.debugging_opts.force_unstable_if_unmarked ||
390             tcx.features().staged_api;
391         let mut staged_api = FxHashMap::default();
392         staged_api.insert(LOCAL_CRATE, is_staged_api);
393         let mut index = Index {
394             staged_api,
395             stab_map: Default::default(),
396             depr_map: Default::default(),
397             active_features: Default::default(),
398         };
399
400         let active_lib_features = &tcx.features().declared_lib_features;
401         let active_lang_features = &tcx.features().declared_lang_features;
402
403         // Put the active features into a map for quick lookup.
404         index.active_features =
405             active_lib_features.iter().map(|&(ref s, ..)| s.clone())
406             .chain(active_lang_features.iter().map(|&(ref s, ..)| s.clone()))
407             .collect();
408
409         {
410             let krate = tcx.hir().krate();
411             let mut annotator = Annotator {
412                 tcx,
413                 index: &mut index,
414                 parent_stab: None,
415                 parent_depr: None,
416                 in_trait_impl: false,
417             };
418
419             // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
420             // a parent stability annotation which indicates that this is private
421             // with the `rustc_private` feature. This is intended for use when
422             // compiling librustc crates themselves so we can leverage crates.io
423             // while maintaining the invariant that all sysroot crates are unstable
424             // by default and are unable to be used.
425             if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
426                 let reason = "this crate is being loaded from the sysroot, an \
427                               unstable location; did you mean to load this crate \
428                               from crates.io via `Cargo.toml` instead?";
429                 let stability = tcx.intern_stability(Stability {
430                     level: attr::StabilityLevel::Unstable {
431                         reason: Some(Symbol::intern(reason)),
432                         issue: 27812,
433                     },
434                     feature: Symbol::intern("rustc_private"),
435                     rustc_depr: None,
436                     const_stability: None,
437                     promotable: false,
438                 });
439                 annotator.parent_stab = Some(stability);
440             }
441
442             annotator.annotate(hir::CRATE_HIR_ID,
443                                &krate.attrs,
444                                krate.span,
445                                AnnotationKind::Required,
446                                |v| intravisit::walk_crate(v, krate));
447         }
448         return index
449     }
450
451     pub fn local_stability(&self, id: HirId) -> Option<&'tcx Stability> {
452         self.stab_map.get(&id).cloned()
453     }
454
455     pub fn local_deprecation_entry(&self, id: HirId) -> Option<DeprecationEntry> {
456         self.depr_map.get(&id).cloned()
457     }
458 }
459
460 /// Cross-references the feature names of unstable APIs with enabled
461 /// features and possibly prints errors.
462 fn check_mod_unstable_api_usage<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
463     tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
464 }
465
466 pub fn provide(providers: &mut Providers<'_>) {
467     *providers = Providers {
468         check_mod_unstable_api_usage,
469         ..*providers
470     };
471 }
472
473 /// Checks whether an item marked with `deprecated(since="X")` is currently
474 /// deprecated (i.e., whether X is not greater than the current rustc version).
475 pub fn deprecation_in_effect(since: &str) -> bool {
476     fn parse_version(ver: &str) -> Vec<u32> {
477         // We ignore non-integer components of the version (e.g., "nightly").
478         ver.split(|c| c == '.' || c == '-').flat_map(|s| s.parse()).collect()
479     }
480
481     if let Some(rustc) = option_env!("CFG_RELEASE") {
482         let since: Vec<u32> = parse_version(since);
483         let rustc: Vec<u32> = parse_version(rustc);
484         // We simply treat invalid `since` attributes as relating to a previous
485         // Rust version, thus always displaying the warning.
486         if since.len() != 3 {
487             return true;
488         }
489         since <= rustc
490     } else {
491         // By default, a deprecation warning applies to
492         // the current version of the compiler.
493         true
494     }
495 }
496
497 struct Checker<'a, 'tcx: 'a> {
498     tcx: TyCtxt<'a, 'tcx, 'tcx>,
499 }
500
501 /// Result of `TyCtxt::eval_stability`.
502 pub enum EvalResult {
503     /// We can use the item because it is stable or we provided the
504     /// corresponding feature gate.
505     Allow,
506     /// We cannot use the item because it is unstable and we did not provide the
507     /// corresponding feature gate.
508     Deny {
509         feature: Symbol,
510         reason: Option<Symbol>,
511         issue: u32,
512     },
513     /// The item does not have the `#[stable]` or `#[unstable]` marker assigned.
514     Unmarked,
515 }
516
517 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
518     // See issue #38412.
519     fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
520         // Check if `def_id` is a trait method.
521         match self.describe_def(def_id) {
522             Some(Def::Method(_)) |
523             Some(Def::AssociatedTy(_)) |
524             Some(Def::AssociatedConst(_)) => {
525                 if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container {
526                     // Trait methods do not declare visibility (even
527                     // for visibility info in cstore). Use containing
528                     // trait instead, so methods of `pub` traits are
529                     // themselves considered `pub`.
530                     def_id = trait_def_id;
531                 }
532             }
533             _ => {}
534         }
535
536         let visibility = self.visibility(def_id);
537
538         match visibility {
539             // Must check stability for `pub` items.
540             ty::Visibility::Public => false,
541
542             // These are not visible outside crate; therefore
543             // stability markers are irrelevant, if even present.
544             ty::Visibility::Restricted(..) |
545             ty::Visibility::Invisible => true,
546         }
547     }
548
549     /// Evaluates the stability of an item.
550     ///
551     /// Returns `EvalResult::Allow` if the item is stable, or unstable but the corresponding
552     /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
553     /// unstable feature otherwise.
554     ///
555     /// If `id` is `Some(_)`, this function will also check if the item at `def_id` has been
556     /// deprecated. If the item is indeed deprecated, we will emit a deprecation lint attached to
557     /// `id`.
558     pub fn eval_stability(self, def_id: DefId, id: Option<HirId>, span: Span) -> EvalResult {
559         let lint_deprecated = |def_id: DefId,
560                                id: HirId,
561                                note: Option<Symbol>,
562                                suggestion: Option<Symbol>,
563                                message: &str,
564                                lint: &'static Lint| {
565             if in_derive_expansion(span) {
566                 return;
567             }
568             let msg = if let Some(note) = note {
569                 format!("{}: {}", message, note)
570             } else {
571                 format!("{}", message)
572             };
573
574             let mut diag = self.struct_span_lint_hir(lint, id, span, &msg);
575             if let Some(suggestion) = suggestion {
576                 if let hir::Node::Expr(_) = self.hir().get_by_hir_id(id) {
577                     diag.span_suggestion(
578                         span,
579                         &msg,
580                         suggestion.to_string(),
581                         Applicability::MachineApplicable,
582                     );
583                 }
584             }
585             diag.emit();
586             if id == hir::DUMMY_HIR_ID {
587                 span_bug!(span, "emitted a {} lint with dummy HIR id: {:?}", lint.name, def_id);
588             }
589         };
590
591         // Deprecated attributes apply in-crate and cross-crate.
592         if let Some(id) = id {
593             if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
594                 let parent_def_id = self.hir().local_def_id_from_hir_id(
595                     self.hir().get_parent_item(id));
596                 let skip = self.lookup_deprecation_entry(parent_def_id)
597                                .map_or(false, |parent_depr| parent_depr.same_origin(&depr_entry));
598
599                 if !skip {
600                     let path = self.def_path_str(def_id);
601                     let message = format!("use of deprecated item '{}'", path);
602                     lint_deprecated(def_id,
603                                     id,
604                                     depr_entry.attr.note,
605                                     None,
606                                     &message,
607                                     lint::builtin::DEPRECATED);
608                 }
609             };
610         }
611
612         let is_staged_api = self.lookup_stability(DefId {
613             index: CRATE_DEF_INDEX,
614             ..def_id
615         }).is_some();
616         if !is_staged_api {
617             return EvalResult::Allow;
618         }
619
620         let stability = self.lookup_stability(def_id);
621         debug!("stability: \
622                 inspecting def_id={:?} span={:?} of stability={:?}", def_id, span, stability);
623
624         if let Some(id) = id {
625             if let Some(stability) = stability {
626                 if let Some(depr) = &stability.rustc_depr {
627                     let path = self.def_path_str(def_id);
628                     if deprecation_in_effect(&depr.since.as_str()) {
629                         let message = format!("use of deprecated item '{}'", path);
630                         lint_deprecated(def_id,
631                                         id,
632                                         Some(depr.reason),
633                                         depr.suggestion,
634                                         &message,
635                                         lint::builtin::DEPRECATED);
636                     } else {
637                         let message = format!("use of item '{}' \
638                                                 that will be deprecated in future version {}",
639                                                 path,
640                                                 depr.since);
641                         lint_deprecated(def_id,
642                                         id,
643                                         Some(depr.reason),
644                                         depr.suggestion,
645                                         &message,
646                                         lint::builtin::DEPRECATED_IN_FUTURE);
647                     }
648                 }
649             }
650         }
651
652         // Only the cross-crate scenario matters when checking unstable APIs
653         let cross_crate = !def_id.is_local();
654         if !cross_crate {
655             return EvalResult::Allow;
656         }
657
658         // Issue #38412: private items lack stability markers.
659         if self.skip_stability_check_due_to_privacy(def_id) {
660             return EvalResult::Allow;
661         }
662
663         match stability {
664             Some(&Stability { level: attr::Unstable { reason, issue }, feature, .. }) => {
665                 if span.allows_unstable(&feature.as_str()) {
666                     debug!("stability: skipping span={:?} since it is internal", span);
667                     return EvalResult::Allow;
668                 }
669                 if self.stability().active_features.contains(&feature) {
670                     return EvalResult::Allow;
671                 }
672
673                 // When we're compiling the compiler itself we may pull in
674                 // crates from crates.io, but those crates may depend on other
675                 // crates also pulled in from crates.io. We want to ideally be
676                 // able to compile everything without requiring upstream
677                 // modifications, so in the case that this looks like a
678                 // `rustc_private` crate (e.g., a compiler crate) and we also have
679                 // the `-Z force-unstable-if-unmarked` flag present (we're
680                 // compiling a compiler crate), then let this missing feature
681                 // annotation slide.
682                 if feature == "rustc_private" && issue == 27812 {
683                     if self.sess.opts.debugging_opts.force_unstable_if_unmarked {
684                         return EvalResult::Allow;
685                     }
686                 }
687
688                 EvalResult::Deny { feature, reason, issue }
689             }
690             Some(_) => {
691                 // Stable APIs are always ok to call and deprecated APIs are
692                 // handled by the lint emitting logic above.
693                 EvalResult::Allow
694             }
695             None => {
696                 EvalResult::Unmarked
697             }
698         }
699     }
700
701     /// Checks if an item is stable or error out.
702     ///
703     /// If the item defined by `def_id` is unstable and the corresponding `#![feature]` does not
704     /// exist, emits an error.
705     ///
706     /// Additionally, this function will also check if the item is deprecated. If so, and `id` is
707     /// not `None`, a deprecated lint attached to `id` will be emitted.
708     pub fn check_stability(self, def_id: DefId, id: Option<HirId>, span: Span) {
709         match self.eval_stability(def_id, id, span) {
710             EvalResult::Allow => {}
711             EvalResult::Deny { feature, reason, issue } => {
712                 let msg = match reason {
713                     Some(r) => format!("use of unstable library feature '{}': {}", feature, r),
714                     None => format!("use of unstable library feature '{}'", &feature)
715                 };
716
717                 let msp: MultiSpan = span.into();
718                 let cm = &self.sess.parse_sess.source_map();
719                 let span_key = msp.primary_span().and_then(|sp: Span|
720                     if !sp.is_dummy() {
721                         let file = cm.lookup_char_pos(sp.lo()).file;
722                         if file.name.is_macros() {
723                             None
724                         } else {
725                             Some(span)
726                         }
727                     } else {
728                         None
729                     }
730                 );
731
732                 let error_id = (DiagnosticMessageId::StabilityId(issue), span_key, msg.clone());
733                 let fresh = self.sess.one_time_diagnostics.borrow_mut().insert(error_id);
734                 if fresh {
735                     emit_feature_err(&self.sess.parse_sess, &feature.as_str(), span,
736                                      GateIssue::Library(Some(issue)), &msg);
737                 }
738             }
739             EvalResult::Unmarked => {
740                 // The API could be uncallable for other reasons, for example when a private module
741                 // was referenced.
742                 self.sess.delay_span_bug(span, &format!("encountered unmarked API: {:?}", def_id));
743             }
744         }
745     }
746 }
747
748 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
749     /// Because stability levels are scoped lexically, we want to walk
750     /// nested items in the context of the outer item, so enable
751     /// deep-walking.
752     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
753         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
754     }
755
756     fn visit_item(&mut self, item: &'tcx hir::Item) {
757         match item.node {
758             hir::ItemKind::ExternCrate(_) => {
759                 // compiler-generated `extern crate` items have a dummy span.
760                 if item.span.is_dummy() { return }
761
762                 let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
763                 let cnum = match self.tcx.extern_mod_stmt_cnum(def_id) {
764                     Some(cnum) => cnum,
765                     None => return,
766                 };
767                 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
768                 self.tcx.check_stability(def_id, Some(item.hir_id), item.span);
769             }
770
771             // For implementations of traits, check the stability of each item
772             // individually as it's possible to have a stable trait with unstable
773             // items.
774             hir::ItemKind::Impl(.., Some(ref t), _, ref impl_item_refs) => {
775                 if let Def::Trait(trait_did) = t.path.def {
776                     for impl_item_ref in impl_item_refs {
777                         let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
778                         let trait_item_def_id = self.tcx.associated_items(trait_did)
779                             .find(|item| item.ident.name == impl_item.ident.name)
780                             .map(|item| item.def_id);
781                         if let Some(def_id) = trait_item_def_id {
782                             // Pass `None` to skip deprecation warnings.
783                             self.tcx.check_stability(def_id, None, impl_item.span);
784                         }
785                     }
786                 }
787             }
788
789             // There's no good place to insert stability check for non-Copy unions,
790             // so semi-randomly perform it here in stability.rs
791             hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
792                 let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
793                 let adt_def = self.tcx.adt_def(def_id);
794                 let ty = self.tcx.type_of(def_id);
795
796                 if adt_def.has_dtor(self.tcx) {
797                     emit_feature_err(&self.tcx.sess.parse_sess,
798                                      "untagged_unions", item.span, GateIssue::Language,
799                                      "unions with `Drop` implementations are unstable");
800                 } else {
801                     let param_env = self.tcx.param_env(def_id);
802                     if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() {
803                         emit_feature_err(&self.tcx.sess.parse_sess,
804                                          "untagged_unions", item.span, GateIssue::Language,
805                                          "unions with non-`Copy` fields are unstable");
806                     }
807                 }
808             }
809
810             _ => (/* pass */)
811         }
812         intravisit::walk_item(self, item);
813     }
814
815     fn visit_path(&mut self, path: &'tcx hir::Path, id: hir::HirId) {
816         if let Some(def_id) = path.def.opt_def_id() {
817             self.tcx.check_stability(def_id, Some(id), path.span)
818         }
819         intravisit::walk_path(self, path)
820     }
821 }
822
823 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
824     pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
825         self.lookup_deprecation_entry(id).map(|depr| depr.attr)
826     }
827 }
828
829 /// Given the list of enabled features that were not language features (i.e., that
830 /// were expected to be library features), and the list of features used from
831 /// libraries, identify activated features that don't exist and error about them.
832 pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
833     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
834
835     if tcx.stability().staged_api[&LOCAL_CRATE] {
836         let krate = tcx.hir().krate();
837         let mut missing = MissingStabilityAnnotations {
838             tcx,
839             access_levels,
840         };
841         missing.check_missing_stability(hir::CRATE_HIR_ID, krate.span, "crate");
842         intravisit::walk_crate(&mut missing, krate);
843         krate.visit_all_item_likes(&mut missing.as_deep_visitor());
844     }
845
846     let declared_lang_features = &tcx.features().declared_lang_features;
847     let mut lang_features = FxHashSet::default();
848     for &(feature, span, since) in declared_lang_features {
849         if let Some(since) = since {
850             // Warn if the user has enabled an already-stable lang feature.
851             unnecessary_stable_feature_lint(tcx, span, feature, since);
852         }
853         if lang_features.contains(&feature) {
854             // Warn if the user enables a lang feature multiple times.
855             duplicate_feature_err(tcx.sess, span, feature);
856         }
857         lang_features.insert(feature);
858     }
859
860     let declared_lib_features = &tcx.features().declared_lib_features;
861     let mut remaining_lib_features = FxHashMap::default();
862     for (feature, span) in declared_lib_features {
863         if remaining_lib_features.contains_key(&feature) {
864             // Warn if the user enables a lib feature multiple times.
865             duplicate_feature_err(tcx.sess, *span, *feature);
866         }
867         remaining_lib_features.insert(feature, span.clone());
868     }
869     // `stdbuild` has special handling for `libc`, so we need to
870     // recognise the feature when building std.
871     // Likewise, libtest is handled specially, so `test` isn't
872     // available as we'd like it to be.
873     // FIXME: only remove `libc` when `stdbuild` is active.
874     // FIXME: remove special casing for `test`.
875     remaining_lib_features.remove(&Symbol::intern("libc"));
876     remaining_lib_features.remove(&Symbol::intern("test"));
877
878     let check_features =
879         |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &Vec<_>| {
880             for &(feature, since) in defined_features {
881                 if let Some(since) = since {
882                     if let Some(span) = remaining_lib_features.get(&feature) {
883                         // Warn if the user has enabled an already-stable lib feature.
884                         unnecessary_stable_feature_lint(tcx, *span, feature, since);
885                     }
886                 }
887                 remaining_lib_features.remove(&feature);
888                 if remaining_lib_features.is_empty() {
889                     break;
890                 }
891             }
892         };
893
894     // We always collect the lib features declared in the current crate, even if there are
895     // no unknown features, because the collection also does feature attribute validation.
896     let local_defined_features = tcx.lib_features().to_vec();
897     if !remaining_lib_features.is_empty() {
898         check_features(&mut remaining_lib_features, &local_defined_features);
899
900         for &cnum in &*tcx.crates() {
901             if remaining_lib_features.is_empty() {
902                 break;
903             }
904             check_features(&mut remaining_lib_features, &tcx.defined_lib_features(cnum));
905         }
906     }
907
908     for (feature, span) in remaining_lib_features {
909         struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
910     }
911
912     // FIXME(#44232): the `used_features` table no longer exists, so we
913     // don't lint about unused features. We should reenable this one day!
914 }
915
916 fn unnecessary_stable_feature_lint<'a, 'tcx>(
917     tcx: TyCtxt<'a, 'tcx, 'tcx>,
918     span: Span,
919     feature: Symbol,
920     since: Symbol
921 ) {
922     tcx.lint_hir(lint::builtin::STABLE_FEATURES,
923         hir::CRATE_HIR_ID,
924         span,
925         &format!("the feature `{}` has been stable since {} and no longer requires \
926                   an attribute to enable", feature, since));
927 }
928
929 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
930     struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
931         .emit();
932 }