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