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