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