]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
Auto merge of #44678 - alexcrichton:rollup, r=alexcrichton
[rust.git] / src / librustc / middle / stability.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A pass that annotates every item and method with its stability level,
12 //! propagating default levels lexically from parent to children ast nodes.
13
14 pub use self::StabilityLevel::*;
15
16 use lint;
17 use hir::def::Def;
18 use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
19 use ty::{self, TyCtxt};
20 use middle::privacy::AccessLevels;
21 use syntax::symbol::Symbol;
22 use syntax_pos::{Span, DUMMY_SP};
23 use syntax::ast;
24 use syntax::ast::{NodeId, Attribute};
25 use syntax::feature_gate::{GateIssue, emit_feature_err, find_lang_feature_accepted_version};
26 use syntax::attr::{self, Stability, Deprecation};
27 use util::nodemap::{FxHashSet, FxHashMap};
28
29 use hir;
30 use hir::{Item, Generics, StructField, Variant, HirId};
31 use hir::intravisit::{self, Visitor, NestedVisitorMap};
32
33 use std::mem::replace;
34 use std::cmp::Ordering;
35
36 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
37 pub enum StabilityLevel {
38     Unstable,
39     Stable,
40 }
41
42 impl StabilityLevel {
43     pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
44         if level.is_stable() { Stable } else { Unstable }
45     }
46 }
47
48 #[derive(PartialEq)]
49 enum AnnotationKind {
50     // Annotation is required if not inherited from unstable parents
51     Required,
52     // Annotation is useless, reject it
53     Prohibited,
54     // Annotation itself is useless, but it can be propagated to children
55     Container,
56 }
57
58 /// An entry in the `depr_map`.
59 #[derive(Clone)]
60 pub struct DeprecationEntry {
61     /// The metadata of the attribute associated with this entry.
62     pub attr: Deprecation,
63     /// The def id where the attr was originally attached. `None` for non-local
64     /// `DefId`'s.
65     origin: Option<HirId>,
66 }
67
68 impl_stable_hash_for!(struct self::DeprecationEntry {
69     attr,
70     origin
71 });
72
73 impl DeprecationEntry {
74     fn local(attr: Deprecation, id: HirId) -> DeprecationEntry {
75         DeprecationEntry {
76             attr,
77             origin: Some(id),
78         }
79     }
80
81     pub fn external(attr: Deprecation) -> DeprecationEntry {
82         DeprecationEntry {
83             attr,
84             origin: None,
85         }
86     }
87
88     pub fn same_origin(&self, other: &DeprecationEntry) -> bool {
89         match (self.origin, other.origin) {
90             (Some(o1), Some(o2)) => o1 == o2,
91             _ => false
92         }
93     }
94 }
95
96 /// A stability index, giving the stability level for items and methods.
97 pub struct Index<'tcx> {
98     /// This is mostly a cache, except the stabilities of local items
99     /// are filled by the annotator.
100     stab_map: FxHashMap<HirId, &'tcx Stability>,
101     depr_map: FxHashMap<HirId, DeprecationEntry>,
102
103     /// Maps for each crate whether it is part of the staged API.
104     staged_api: FxHashMap<CrateNum, bool>,
105
106     /// Features enabled for this crate.
107     active_features: FxHashSet<Symbol>,
108 }
109
110 impl_stable_hash_for!(struct self::Index<'tcx> {
111     stab_map,
112     depr_map,
113     staged_api,
114     active_features
115 });
116
117 // A private tree-walker for producing an Index.
118 struct Annotator<'a, 'tcx: 'a> {
119     tcx: TyCtxt<'a, 'tcx, 'tcx>,
120     index: &'a mut Index<'tcx>,
121     parent_stab: Option<&'tcx Stability>,
122     parent_depr: Option<DeprecationEntry>,
123     in_trait_impl: bool,
124 }
125
126 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
127     // Determine the stability for a node based on its attributes and inherited
128     // stability. The stability is recorded in the index and used as the parent.
129     fn annotate<F>(&mut self, id: NodeId, attrs: &[Attribute],
130                    item_sp: Span, kind: AnnotationKind, visit_children: F)
131         where F: FnOnce(&mut Self)
132     {
133         if self.tcx.sess.features.borrow().staged_api {
134             // This crate explicitly wants staged API.
135             debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
136             if let Some(..) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
137                 self.tcx.sess.span_err(item_sp, "`#[deprecated]` cannot be used in staged api, \
138                                                  use `#[rustc_deprecated]` instead");
139             }
140             if let Some(mut stab) = attr::find_stability(self.tcx.sess.diagnostic(),
141                                                          attrs, item_sp) {
142                 // Error if prohibited, or can't inherit anything from a container
143                 if kind == AnnotationKind::Prohibited ||
144                    (kind == AnnotationKind::Container &&
145                     stab.level.is_stable() &&
146                     stab.rustc_depr.is_none()) {
147                     self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
148                 }
149
150                 debug!("annotate: found {:?}", stab);
151                 // If parent is deprecated and we're not, inherit this by merging
152                 // deprecated_since and its reason.
153                 if let Some(parent_stab) = self.parent_stab {
154                     if parent_stab.rustc_depr.is_some() && stab.rustc_depr.is_none() {
155                         stab.rustc_depr = parent_stab.rustc_depr.clone()
156                     }
157                 }
158
159                 let stab = self.tcx.intern_stability(stab);
160
161                 // Check if deprecated_since < stable_since. If it is,
162                 // this is *almost surely* an accident.
163                 if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
164                         &attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
165                     // Explicit version of iter::order::lt to handle parse errors properly
166                     for (dep_v, stab_v) in
167                             dep_since.as_str().split(".").zip(stab_since.as_str().split(".")) {
168                         if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
169                             match dep_v.cmp(&stab_v) {
170                                 Ordering::Less => {
171                                     self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
172                                                                      after it is deprecated");
173                                     break
174                                 }
175                                 Ordering::Equal => continue,
176                                 Ordering::Greater => break,
177                             }
178                         } else {
179                             // Act like it isn't less because the question is now nonsensical,
180                             // and this makes us not do anything else interesting.
181                             self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
182                                                              version found");
183                             break
184                         }
185                     }
186                 }
187
188                 let hir_id = self.tcx.hir.node_to_hir_id(id);
189                 self.index.stab_map.insert(hir_id, stab);
190
191                 let orig_parent_stab = replace(&mut self.parent_stab, Some(stab));
192                 visit_children(self);
193                 self.parent_stab = orig_parent_stab;
194             } else {
195                 debug!("annotate: not found, parent = {:?}", self.parent_stab);
196                 if let Some(stab) = self.parent_stab {
197                     if stab.level.is_unstable() {
198                         let hir_id = self.tcx.hir.node_to_hir_id(id);
199                         self.index.stab_map.insert(hir_id, stab);
200                     }
201                 }
202                 visit_children(self);
203             }
204         } else {
205             // Emit errors for non-staged-api crates.
206             for attr in attrs {
207                 let tag = unwrap_or!(attr.name(), continue);
208                 if tag == "unstable" || tag == "stable" || tag == "rustc_deprecated" {
209                     attr::mark_used(attr);
210                     self.tcx.sess.span_err(attr.span(), "stability attributes may not be used \
211                                                          outside of the standard library");
212                 }
213             }
214
215             // Propagate unstability.  This can happen even for non-staged-api crates in case
216             // -Zforce-unstable-if-unmarked is set.
217             if let Some(stab) = self.parent_stab {
218                 if stab.level.is_unstable() {
219                     let hir_id = self.tcx.hir.node_to_hir_id(id);
220                     self.index.stab_map.insert(hir_id, stab);
221                 }
222             }
223
224             if let Some(depr) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
225                 if kind == AnnotationKind::Prohibited {
226                     self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
227                 }
228
229                 // `Deprecation` is just two pointers, no need to intern it
230                 let hir_id = self.tcx.hir.node_to_hir_id(id);
231                 let depr_entry = DeprecationEntry::local(depr, hir_id);
232                 self.index.depr_map.insert(hir_id, depr_entry.clone());
233
234                 let orig_parent_depr = replace(&mut self.parent_depr,
235                                                Some(depr_entry));
236                 visit_children(self);
237                 self.parent_depr = orig_parent_depr;
238             } else if let Some(parent_depr) = self.parent_depr.clone() {
239                 let hir_id = self.tcx.hir.node_to_hir_id(id);
240                 self.index.depr_map.insert(hir_id, parent_depr);
241                 visit_children(self);
242             } else {
243                 visit_children(self);
244             }
245         }
246     }
247 }
248
249 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
250     /// Because stability levels are scoped lexically, we want to walk
251     /// nested items in the context of the outer item, so enable
252     /// deep-walking.
253     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
254         NestedVisitorMap::All(&self.tcx.hir)
255     }
256
257     fn visit_item(&mut self, i: &'tcx Item) {
258         let orig_in_trait_impl = self.in_trait_impl;
259         let mut kind = AnnotationKind::Required;
260         match i.node {
261             // Inherent impls and foreign modules serve only as containers for other items,
262             // they don't have their own stability. They still can be annotated as unstable
263             // and propagate this unstability to children, but this annotation is completely
264             // optional. They inherit stability from their parents when unannotated.
265             hir::ItemImpl(.., None, _, _) | hir::ItemForeignMod(..) => {
266                 self.in_trait_impl = false;
267                 kind = AnnotationKind::Container;
268             }
269             hir::ItemImpl(.., Some(_), _, _) => {
270                 self.in_trait_impl = true;
271             }
272             hir::ItemStruct(ref sd, _) => {
273                 if !sd.is_struct() {
274                     self.annotate(sd.id(), &i.attrs, i.span, AnnotationKind::Required, |_| {})
275                 }
276             }
277             _ => {}
278         }
279
280         self.annotate(i.id, &i.attrs, i.span, kind, |v| {
281             intravisit::walk_item(v, i)
282         });
283         self.in_trait_impl = orig_in_trait_impl;
284     }
285
286     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
287         self.annotate(ti.id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
288             intravisit::walk_trait_item(v, ti);
289         });
290     }
291
292     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
293         let kind = if self.in_trait_impl {
294             AnnotationKind::Prohibited
295         } else {
296             AnnotationKind::Required
297         };
298         self.annotate(ii.id, &ii.attrs, ii.span, kind, |v| {
299             intravisit::walk_impl_item(v, ii);
300         });
301     }
302
303     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
304         self.annotate(var.node.data.id(), &var.node.attrs, var.span, AnnotationKind::Required, |v| {
305             intravisit::walk_variant(v, var, g, item_id);
306         })
307     }
308
309     fn visit_struct_field(&mut self, s: &'tcx StructField) {
310         self.annotate(s.id, &s.attrs, s.span, AnnotationKind::Required, |v| {
311             intravisit::walk_struct_field(v, s);
312         });
313     }
314
315     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
316         self.annotate(i.id, &i.attrs, i.span, AnnotationKind::Required, |v| {
317             intravisit::walk_foreign_item(v, i);
318         });
319     }
320
321     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
322         self.annotate(md.id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
323     }
324 }
325
326 struct MissingStabilityAnnotations<'a, 'tcx: 'a> {
327     tcx: TyCtxt<'a, 'tcx, 'tcx>,
328     access_levels: &'a AccessLevels,
329 }
330
331 impl<'a, 'tcx: 'a> MissingStabilityAnnotations<'a, 'tcx> {
332     fn check_missing_stability(&self, id: NodeId, span: Span) {
333         let hir_id = self.tcx.hir.node_to_hir_id(id);
334         let stab = self.tcx.stability().local_stability(hir_id);
335         let is_error = !self.tcx.sess.opts.test &&
336                         stab.is_none() &&
337                         self.access_levels.is_reachable(id);
338         if is_error {
339             self.tcx.sess.span_err(span, "This node does not have a stability attribute");
340         }
341     }
342 }
343
344 impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> {
345     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
346         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
347     }
348
349     fn visit_item(&mut self, i: &'tcx Item) {
350         match i.node {
351             // Inherent impls and foreign modules serve only as containers for other items,
352             // they don't have their own stability. They still can be annotated as unstable
353             // and propagate this unstability to children, but this annotation is completely
354             // optional. They inherit stability from their parents when unannotated.
355             hir::ItemImpl(.., None, _, _) | hir::ItemForeignMod(..) => {}
356
357             _ => self.check_missing_stability(i.id, i.span)
358         }
359
360         intravisit::walk_item(self, i)
361     }
362
363     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
364         self.check_missing_stability(ti.id, ti.span);
365         intravisit::walk_trait_item(self, ti);
366     }
367
368     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
369         let impl_def_id = self.tcx.hir.local_def_id(self.tcx.hir.get_parent(ii.id));
370         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
371             self.check_missing_stability(ii.id, ii.span);
372         }
373         intravisit::walk_impl_item(self, ii);
374     }
375
376     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
377         self.check_missing_stability(var.node.data.id(), var.span);
378         intravisit::walk_variant(self, var, g, item_id);
379     }
380
381     fn visit_struct_field(&mut self, s: &'tcx StructField) {
382         self.check_missing_stability(s.id, s.span);
383         intravisit::walk_struct_field(self, s);
384     }
385
386     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
387         self.check_missing_stability(i.id, i.span);
388         intravisit::walk_foreign_item(self, i);
389     }
390
391     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
392         self.check_missing_stability(md.id, md.span);
393     }
394 }
395
396 impl<'a, 'tcx> Index<'tcx> {
397     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Index<'tcx> {
398         let is_staged_api =
399             tcx.sess.opts.debugging_opts.force_unstable_if_unmarked ||
400             tcx.sess.features.borrow().staged_api;
401         let mut staged_api = FxHashMap();
402         staged_api.insert(LOCAL_CRATE, is_staged_api);
403         let mut index = Index {
404             staged_api,
405             stab_map: FxHashMap(),
406             depr_map: FxHashMap(),
407             active_features: FxHashSet(),
408         };
409
410         let ref active_lib_features = tcx.sess.features.borrow().declared_lib_features;
411
412         // Put the active features into a map for quick lookup
413         index.active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
414
415         {
416             let krate = tcx.hir.krate();
417             let mut annotator = Annotator {
418                 tcx,
419                 index: &mut index,
420                 parent_stab: None,
421                 parent_depr: None,
422                 in_trait_impl: false,
423             };
424
425             // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
426             // a parent stability annotation which indicates that this is private
427             // with the `rustc_private` feature. This is intended for use when
428             // compiling librustc crates themselves so we can leverage crates.io
429             // while maintaining the invariant that all sysroot crates are unstable
430             // by default and are unable to be used.
431             if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
432                 let reason = "this crate is being loaded from the sysroot, and \
433                               unstable location; did you mean to load this crate \
434                               from crates.io via `Cargo.toml` instead?";
435                 let stability = tcx.intern_stability(Stability {
436                     level: attr::StabilityLevel::Unstable {
437                         reason: Some(Symbol::intern(reason)),
438                         issue: 27812,
439                     },
440                     feature: Symbol::intern("rustc_private"),
441                     rustc_depr: None,
442                     rustc_const_unstable: None,
443                 });
444                 annotator.parent_stab = Some(stability);
445             }
446
447             annotator.annotate(ast::CRATE_NODE_ID,
448                                &krate.attrs,
449                                krate.span,
450                                AnnotationKind::Required,
451                                |v| intravisit::walk_crate(v, krate));
452         }
453         return index
454     }
455
456     pub fn local_stability(&self, id: HirId) -> Option<&'tcx Stability> {
457         self.stab_map.get(&id).cloned()
458     }
459
460     pub fn local_deprecation_entry(&self, id: HirId) -> Option<DeprecationEntry> {
461         self.depr_map.get(&id).cloned()
462     }
463 }
464
465 /// Cross-references the feature names of unstable APIs with enabled
466 /// features and possibly prints errors.
467 pub fn check_unstable_api_usage<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
468     let mut checker = Checker { tcx: tcx };
469     tcx.hir.krate().visit_all_item_likes(&mut checker.as_deep_visitor());
470 }
471
472 struct Checker<'a, 'tcx: 'a> {
473     tcx: TyCtxt<'a, 'tcx, 'tcx>,
474 }
475
476 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
477     // (See issue #38412)
478     fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
479         // Check if `def_id` is a trait method.
480         match self.describe_def(def_id) {
481             Some(Def::Method(_)) |
482             Some(Def::AssociatedTy(_)) |
483             Some(Def::AssociatedConst(_)) => {
484                 match self.associated_item(def_id).container {
485                     ty::TraitContainer(trait_def_id) => {
486                         // Trait methods do not declare visibility (even
487                         // for visibility info in cstore). Use containing
488                         // trait instead, so methods of pub traits are
489                         // themselves considered pub.
490                         def_id = trait_def_id;
491                     }
492                     _ => {}
493                 }
494             }
495             _ => {}
496         }
497
498         let visibility = self.visibility(def_id);
499
500         match visibility {
501             // must check stability for pub items.
502             ty::Visibility::Public => false,
503
504             // these are not visible outside crate; therefore
505             // stability markers are irrelevant, if even present.
506             ty::Visibility::Restricted(..) |
507             ty::Visibility::Invisible => true,
508         }
509     }
510
511     pub fn check_stability(self, def_id: DefId, id: NodeId, span: Span) {
512         if span.allows_unstable() {
513             debug!("stability: \
514                     skipping span={:?} since it is internal", span);
515             return;
516         }
517
518         let lint_deprecated = |note: Option<Symbol>| {
519             let msg = if let Some(note) = note {
520                 format!("use of deprecated item: {}", note)
521             } else {
522                 format!("use of deprecated item")
523             };
524
525             self.lint_node(lint::builtin::DEPRECATED, id, span, &msg);
526         };
527
528         // Deprecated attributes apply in-crate and cross-crate.
529         if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
530             let skip = if id == ast::DUMMY_NODE_ID {
531                 true
532             } else {
533                 let parent_def_id = self.hir.local_def_id(self.hir.get_parent(id));
534                 self.lookup_deprecation_entry(parent_def_id).map_or(false, |parent_depr| {
535                     parent_depr.same_origin(&depr_entry)
536                 })
537             };
538
539             if !skip {
540                 lint_deprecated(depr_entry.attr.note);
541             }
542         }
543
544         let is_staged_api = self.lookup_stability(DefId {
545             index: CRATE_DEF_INDEX,
546             ..def_id
547         }).is_some();
548         if !is_staged_api {
549             return;
550         }
551
552         let stability = self.lookup_stability(def_id);
553         debug!("stability: \
554                 inspecting def_id={:?} span={:?} of stability={:?}", def_id, span, stability);
555
556         if let Some(&Stability{rustc_depr: Some(attr::RustcDeprecation { reason, .. }), ..})
557                 = stability {
558             if id != ast::DUMMY_NODE_ID {
559                 lint_deprecated(Some(reason));
560             }
561         }
562
563         // Only the cross-crate scenario matters when checking unstable APIs
564         let cross_crate = !def_id.is_local();
565         if !cross_crate {
566             return
567         }
568
569         // Issue 38412: private items lack stability markers.
570         if self.skip_stability_check_due_to_privacy(def_id) {
571             return
572         }
573
574         match stability {
575             Some(&Stability { level: attr::Unstable {ref reason, issue}, ref feature, .. }) => {
576                 if self.stability().active_features.contains(feature) {
577                     return
578                 }
579
580                 // When we're compiling the compiler itself we may pull in
581                 // crates from crates.io, but those crates may depend on other
582                 // crates also pulled in from crates.io. We want to ideally be
583                 // able to compile everything without requiring upstream
584                 // modifications, so in the case that this looks like a
585                 // rustc_private crate (e.g. a compiler crate) and we also have
586                 // the `-Z force-unstable-if-unmarked` flag present (we're
587                 // compiling a compiler crate), then let this missing feature
588                 // annotation slide.
589                 if *feature == "rustc_private" && issue == 27812 {
590                     if self.sess.opts.debugging_opts.force_unstable_if_unmarked {
591                         return
592                     }
593                 }
594
595                 let msg = match *reason {
596                     Some(ref r) => format!("use of unstable library feature '{}': {}",
597                                            feature.as_str(), &r),
598                     None => format!("use of unstable library feature '{}'", &feature)
599                 };
600                 emit_feature_err(&self.sess.parse_sess, &feature.as_str(), span,
601                                  GateIssue::Library(Some(issue)), &msg);
602             }
603             Some(_) => {
604                 // Stable APIs are always ok to call and deprecated APIs are
605                 // handled by the lint emitting logic above.
606             }
607             None => {
608                 span_bug!(span, "encountered unmarked API");
609             }
610         }
611     }
612 }
613
614 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
615     /// Because stability levels are scoped lexically, we want to walk
616     /// nested items in the context of the outer item, so enable
617     /// deep-walking.
618     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
619         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
620     }
621
622     fn visit_item(&mut self, item: &'tcx hir::Item) {
623         match item.node {
624             hir::ItemExternCrate(_) => {
625                 // compiler-generated `extern crate` items have a dummy span.
626                 if item.span == DUMMY_SP { return }
627
628                 let def_id = self.tcx.hir.local_def_id(item.id);
629                 let cnum = match self.tcx.extern_mod_stmt_cnum(def_id) {
630                     Some(cnum) => cnum,
631                     None => return,
632                 };
633                 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
634                 self.tcx.check_stability(def_id, item.id, item.span);
635             }
636
637             // For implementations of traits, check the stability of each item
638             // individually as it's possible to have a stable trait with unstable
639             // items.
640             hir::ItemImpl(.., Some(ref t), _, ref impl_item_refs) => {
641                 if let Def::Trait(trait_did) = t.path.def {
642                     for impl_item_ref in impl_item_refs {
643                         let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
644                         let trait_item_def_id = self.tcx.associated_items(trait_did)
645                             .find(|item| item.name == impl_item.name).map(|item| item.def_id);
646                         if let Some(def_id) = trait_item_def_id {
647                             // Pass `DUMMY_NODE_ID` to skip deprecation warnings.
648                             self.tcx.check_stability(def_id, ast::DUMMY_NODE_ID, impl_item.span);
649                         }
650                     }
651                 }
652             }
653
654             // There's no good place to insert stability check for non-Copy unions,
655             // so semi-randomly perform it here in stability.rs
656             hir::ItemUnion(..) if !self.tcx.sess.features.borrow().untagged_unions => {
657                 let def_id = self.tcx.hir.local_def_id(item.id);
658                 let adt_def = self.tcx.adt_def(def_id);
659                 let ty = self.tcx.type_of(def_id);
660
661                 if adt_def.has_dtor(self.tcx) {
662                     emit_feature_err(&self.tcx.sess.parse_sess,
663                                      "untagged_unions", item.span, GateIssue::Language,
664                                      "unions with `Drop` implementations are unstable");
665                 } else {
666                     let param_env = self.tcx.param_env(def_id);
667                     if !param_env.can_type_implement_copy(self.tcx, ty, item.span).is_ok() {
668                         emit_feature_err(&self.tcx.sess.parse_sess,
669                                         "untagged_unions", item.span, GateIssue::Language,
670                                         "unions with non-`Copy` fields are unstable");
671                     }
672                 }
673             }
674
675             _ => (/* pass */)
676         }
677         intravisit::walk_item(self, item);
678     }
679
680     fn visit_path(&mut self, path: &'tcx hir::Path, id: ast::NodeId) {
681         match path.def {
682             Def::Local(..) | Def::Upvar(..) |
683             Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => {}
684             _ => self.tcx.check_stability(path.def.def_id(), id, path.span)
685         }
686         intravisit::walk_path(self, path)
687     }
688 }
689
690 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
691     pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
692         self.lookup_deprecation_entry(id).map(|depr| depr.attr)
693     }
694 }
695
696 /// Given the list of enabled features that were not language features (i.e. that
697 /// were expected to be library features), and the list of features used from
698 /// libraries, identify activated features that don't exist and error about them.
699 pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
700     let sess = &tcx.sess;
701
702     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
703
704     if tcx.stability().staged_api[&LOCAL_CRATE] {
705         let krate = tcx.hir.krate();
706         let mut missing = MissingStabilityAnnotations {
707             tcx,
708             access_levels,
709         };
710         missing.check_missing_stability(ast::CRATE_NODE_ID, krate.span);
711         intravisit::walk_crate(&mut missing, krate);
712         krate.visit_all_item_likes(&mut missing.as_deep_visitor());
713     }
714
715     let ref declared_lib_features = sess.features.borrow().declared_lib_features;
716     let mut remaining_lib_features: FxHashMap<Symbol, Span>
717         = declared_lib_features.clone().into_iter().collect();
718     remaining_lib_features.remove(&Symbol::intern("proc_macro"));
719
720     for &(ref stable_lang_feature, span) in &sess.features.borrow().declared_stable_lang_features {
721         let version = find_lang_feature_accepted_version(&stable_lang_feature.as_str())
722             .expect("unexpectedly couldn't find version feature was stabilized");
723         tcx.lint_node(lint::builtin::STABLE_FEATURES,
724                       ast::CRATE_NODE_ID,
725                       span,
726                       &format_stable_since_msg(version));
727     }
728
729     // FIXME(#44232) the `used_features` table no longer exists, so we don't
730     //               lint about unknown or unused features. We should reenable
731     //               this one day!
732     //
733     // let index = tcx.stability();
734     // for (used_lib_feature, level) in &index.used_features {
735     //     remaining_lib_features.remove(used_lib_feature);
736     // }
737     //
738     // for &span in remaining_lib_features.values() {
739     //     tcx.lint_node(lint::builtin::UNUSED_FEATURES,
740     //                   ast::CRATE_NODE_ID,
741     //                   span,
742     //                   "unused or unknown feature");
743     // }
744 }
745
746 fn format_stable_since_msg(version: &str) -> String {
747     format!("this feature has been stable since {}. Attribute no longer needed", version)
748 }