]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
Rework stability annotation pass
[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 use self::AnnotationKind::*;
16
17 use session::Session;
18 use lint;
19 use metadata::cstore::LOCAL_CRATE;
20 use middle::def;
21 use middle::def_id::{CRATE_DEF_INDEX, DefId};
22 use middle::ty;
23 use middle::privacy::PublicItems;
24 use metadata::csearch;
25 use syntax::parse::token::InternedString;
26 use syntax::codemap::{Span, DUMMY_SP};
27 use syntax::ast;
28 use syntax::ast::{NodeId, Attribute};
29 use syntax::feature_gate::{GateIssue, emit_feature_err};
30 use syntax::attr::{self, Stability, AttrMetaMethods};
31 use util::nodemap::{DefIdMap, FnvHashSet, FnvHashMap};
32
33 use rustc_front::hir;
34 use rustc_front::hir::{Block, Crate, Item, Generics, StructField, Variant};
35 use rustc_front::visit::{self, Visitor};
36
37 use std::mem::replace;
38 use std::cmp::Ordering;
39
40 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
41 pub enum StabilityLevel {
42     Unstable,
43     Stable,
44 }
45
46 impl StabilityLevel {
47     pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
48         if level.is_stable() { Stable } else { Unstable }
49     }
50 }
51
52 #[derive(PartialEq)]
53 enum AnnotationKind {
54     // Annotation is required if not inherited from unstable parents
55     AnnRequired,
56     // Annotation is useless, reject it
57     AnnProhibited,
58     // Annotation itself is useless, but it can be propagated to children
59     AnnContainer,
60 }
61
62 /// A stability index, giving the stability level for items and methods.
63 pub struct Index<'tcx> {
64     /// This is mostly a cache, except the stabilities of local items
65     /// are filled by the annotator.
66     map: DefIdMap<Option<&'tcx Stability>>,
67
68     /// Maps for each crate whether it is part of the staged API.
69     staged_api: FnvHashMap<ast::CrateNum, bool>
70 }
71
72 // A private tree-walker for producing an Index.
73 struct Annotator<'a, 'tcx: 'a> {
74     tcx: &'a ty::ctxt<'tcx>,
75     index: &'a mut Index<'tcx>,
76     parent: Option<&'tcx Stability>,
77     export_map: &'a PublicItems,
78     in_trait_impl: bool,
79     in_enum: bool,
80 }
81
82 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
83     // Determine the stability for a node based on its attributes and inherited
84     // stability. The stability is recorded in the index and used as the parent.
85     fn annotate<F>(&mut self, id: NodeId, attrs: &Vec<Attribute>,
86                    item_sp: Span, kind: AnnotationKind, visit_children: F)
87         where F: FnOnce(&mut Annotator)
88     {
89         if self.index.staged_api[&LOCAL_CRATE] {
90             debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
91             if let Some(mut stab) = attr::find_stability(self.tcx.sess.diagnostic(),
92                                                          attrs, item_sp) {
93                 // Error if prohibited, or can't inherit anything from a container
94                 if kind == AnnProhibited ||
95                    kind == AnnContainer && stab.level.is_stable() && stab.depr.is_none() {
96                     self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
97                 }
98
99                 debug!("annotate: found {:?}", stab);
100                 // If parent is deprecated and we're not, inherit this by merging
101                 // deprecated_since and its reason.
102                 if let Some(parent_stab) = self.parent {
103                     if parent_stab.depr.is_some() && stab.depr.is_none() {
104                         stab.depr = parent_stab.depr.clone()
105                     }
106                 }
107
108                 let stab = self.tcx.intern_stability(stab);
109
110                 // Check if deprecated_since < stable_since. If it is,
111                 // this is *almost surely* an accident.
112                 if let (&Some(attr::Deprecation {since: ref dep_since, ..}),
113                         &attr::Stable {since: ref stab_since}) = (&stab.depr, &stab.level) {
114                     // Explicit version of iter::order::lt to handle parse errors properly
115                     for (dep_v, stab_v) in dep_since.split(".").zip(stab_since.split(".")) {
116                         if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
117                             match dep_v.cmp(&stab_v) {
118                                 Ordering::Less => {
119                                     self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
120                                                                      after it is deprecated");
121                                     break
122                                 }
123                                 Ordering::Equal => continue,
124                                 Ordering::Greater => break,
125                             }
126                         } else {
127                             // Act like it isn't less because the question is now nonsensical,
128                             // and this makes us not do anything else interesting.
129                             self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
130                                                              version found");
131                             break
132                         }
133                     }
134                 }
135
136                 let def_id = self.tcx.map.local_def_id(id);
137                 self.index.map.insert(def_id, Some(stab));
138
139                 let parent = replace(&mut self.parent, Some(stab));
140                 visit_children(self);
141                 self.parent = parent;
142             } else {
143                 debug!("annotate: not found, parent = {:?}", self.parent);
144                 let mut is_error = kind == AnnRequired &&
145                                    self.export_map.contains(&id) &&
146                                    !self.tcx.sess.opts.test;
147                 if let Some(stab) = self.parent {
148                     if stab.level.is_unstable() {
149                         let def_id = self.tcx.map.local_def_id(id);
150                         self.index.map.insert(def_id, Some(stab));
151                         is_error = false;
152                     }
153                 }
154                 if is_error {
155                     self.tcx.sess.span_err(item_sp, "This node does not have \
156                                                      a stability attribute");
157                 }
158                 visit_children(self);
159             }
160         } else {
161             // Emit errors for non-staged-api crates.
162             for attr in attrs {
163                 let tag = attr.name();
164                 if tag == "unstable" || tag == "stable" || tag == "deprecated" {
165                     attr::mark_used(attr);
166                     self.tcx.sess.span_err(attr.span(), "stability attributes may not be used \
167                                                          outside of the standard library");
168                 }
169             }
170             visit_children(self);
171         }
172     }
173 }
174
175 impl<'a, 'tcx, 'v> Visitor<'v> for Annotator<'a, 'tcx> {
176     fn visit_item(&mut self, i: &Item) {
177         let orig_in_trait_impl = self.in_trait_impl;
178         let orig_in_enum = self.in_enum;
179         let mut kind = AnnRequired;
180         match i.node {
181             // Inherent impls and foreign modules serve only as containers for other items,
182             // they don't have their own stability. They still can be annotated as unstable
183             // and propagate this unstability to children, but this annotation is completely
184             // optional. They inherit stability from their parents when unannotated.
185             hir::ItemImpl(_, _, _, None, _, _) | hir::ItemForeignMod(..) => {
186                 self.in_trait_impl = false;
187                 kind = AnnContainer;
188             }
189             hir::ItemImpl(_, _, _, Some(_), _, _) => {
190                 self.in_trait_impl = true;
191             }
192             hir::ItemStruct(ref sd, _) => {
193                 self.in_enum = false;
194                 if !sd.is_struct() {
195                     self.annotate(sd.id(), &i.attrs, i.span, AnnRequired, |_| {})
196                 }
197             }
198             hir::ItemEnum(..) => {
199                 self.in_enum = true;
200             }
201             _ => {}
202         }
203
204         self.annotate(i.id, &i.attrs, i.span, kind, |v| {
205             visit::walk_item(v, i)
206         });
207         self.in_trait_impl = orig_in_trait_impl;
208         self.in_enum = orig_in_enum;
209     }
210
211     fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
212         self.annotate(ti.id, &ti.attrs, ti.span, AnnRequired, |v| {
213             visit::walk_trait_item(v, ti);
214         });
215     }
216
217     fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
218         let kind = if self.in_trait_impl { AnnProhibited } else { AnnRequired };
219         self.annotate(ii.id, &ii.attrs, ii.span, kind, |v| {
220             visit::walk_impl_item(v, ii);
221         });
222     }
223
224     fn visit_variant(&mut self, var: &Variant, g: &'v Generics, item_id: NodeId) {
225         self.annotate(var.node.data.id(), &var.node.attrs, var.span, AnnRequired, |v| {
226             visit::walk_variant(v, var, g, item_id);
227         })
228     }
229
230     fn visit_struct_field(&mut self, s: &StructField) {
231         // FIXME: This is temporary, can't use attributes with tuple variant fields until snapshot
232         let kind = if self.in_enum && s.node.kind.is_unnamed() {
233             AnnProhibited
234         } else {
235             AnnRequired
236         };
237         self.annotate(s.node.id, &s.node.attrs, s.span, kind, |v| {
238             visit::walk_struct_field(v, s);
239         });
240     }
241
242     fn visit_foreign_item(&mut self, i: &hir::ForeignItem) {
243         self.annotate(i.id, &i.attrs, i.span, AnnRequired, |v| {
244             visit::walk_foreign_item(v, i);
245         });
246     }
247
248     fn visit_macro_def(&mut self, md: &'v hir::MacroDef) {
249         if md.imported_from.is_none() {
250             self.annotate(md.id, &md.attrs, md.span, AnnRequired, |_| {});
251         }
252     }
253 }
254
255 impl<'tcx> Index<'tcx> {
256     /// Construct the stability index for a crate being compiled.
257     pub fn build(&mut self, tcx: &ty::ctxt<'tcx>, krate: &Crate, export_map: &PublicItems) {
258         let mut annotator = Annotator {
259             tcx: tcx,
260             index: self,
261             parent: None,
262             export_map: export_map,
263             in_trait_impl: false,
264             in_enum: false,
265         };
266         annotator.annotate(ast::CRATE_NODE_ID, &krate.attrs, krate.span, AnnRequired,
267                            |v| visit::walk_crate(v, krate));
268     }
269
270     pub fn new(krate: &Crate) -> Index {
271         let mut is_staged_api = false;
272         for attr in &krate.attrs {
273             if attr.name() == "staged_api" {
274                 if let ast::MetaWord(_) = attr.node.value.node {
275                     attr::mark_used(attr);
276                     is_staged_api = true;
277                     break
278                 }
279             }
280         }
281         let mut staged_api = FnvHashMap();
282         staged_api.insert(LOCAL_CRATE, is_staged_api);
283         Index {
284             staged_api: staged_api,
285             map: DefIdMap(),
286         }
287     }
288 }
289
290 /// Cross-references the feature names of unstable APIs with enabled
291 /// features and possibly prints errors. Returns a list of all
292 /// features used.
293 pub fn check_unstable_api_usage(tcx: &ty::ctxt)
294                                 -> FnvHashMap<InternedString, StabilityLevel> {
295     let ref active_lib_features = tcx.sess.features.borrow().declared_lib_features;
296
297     // Put the active features into a map for quick lookup
298     let active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
299
300     let mut checker = Checker {
301         tcx: tcx,
302         active_features: active_features,
303         used_features: FnvHashMap(),
304         in_skip_block: 0,
305     };
306
307     let krate = tcx.map.krate();
308     visit::walk_crate(&mut checker, krate);
309
310     let used_features = checker.used_features;
311     return used_features;
312 }
313
314 struct Checker<'a, 'tcx: 'a> {
315     tcx: &'a ty::ctxt<'tcx>,
316     active_features: FnvHashSet<InternedString>,
317     used_features: FnvHashMap<InternedString, StabilityLevel>,
318     // Within a block where feature gate checking can be skipped.
319     in_skip_block: u32,
320 }
321
322 impl<'a, 'tcx> Checker<'a, 'tcx> {
323     fn check(&mut self, id: DefId, span: Span, stab: &Option<&Stability>) {
324         // Only the cross-crate scenario matters when checking unstable APIs
325         let cross_crate = !id.is_local();
326         if !cross_crate {
327             return
328         }
329
330         // We don't need to check for stability - presumably compiler generated code.
331         if self.in_skip_block > 0 {
332             return;
333         }
334
335         match *stab {
336             Some(&Stability { level: attr::Unstable {ref reason, issue}, ref feature, .. }) => {
337                 self.used_features.insert(feature.clone(), Unstable);
338
339                 if !self.active_features.contains(feature) {
340                     let msg = match *reason {
341                         Some(ref r) => format!("use of unstable library feature '{}': {}",
342                                                &feature, &r),
343                         None => format!("use of unstable library feature '{}'", &feature)
344                     };
345                     emit_feature_err(&self.tcx.sess.parse_sess.span_diagnostic,
346                                       &feature, span, GateIssue::Library(Some(issue)), &msg);
347                 }
348             }
349             Some(&Stability { ref level, ref feature, .. }) => {
350                 self.used_features.insert(feature.clone(), StabilityLevel::from_attr_level(level));
351
352                 // Stable APIs are always ok to call and deprecated APIs are
353                 // handled by a lint.
354             }
355             None => {
356                 // This is an 'unmarked' API, which should not exist
357                 // in the standard library.
358                 if self.tcx.sess.features.borrow().unmarked_api {
359                     self.tcx.sess.span_warn(span, "use of unmarked library feature");
360                     self.tcx.sess.span_note(span, "this is either a bug in the library you are \
361                                                    using or a bug in the compiler - please \
362                                                    report it in both places");
363                 } else {
364                     self.tcx.sess.span_err(span, "use of unmarked library feature");
365                     self.tcx.sess.span_note(span, "this is either a bug in the library you are \
366                                                    using or a bug in the compiler - please \
367                                                    report it in both places");
368                     self.tcx.sess.span_note(span, "use #![feature(unmarked_api)] in the \
369                                                    crate attributes to override this");
370                 }
371             }
372         }
373     }
374 }
375
376 impl<'a, 'v, 'tcx> Visitor<'v> for Checker<'a, 'tcx> {
377     fn visit_item(&mut self, item: &hir::Item) {
378         // When compiling with --test we don't enforce stability on the
379         // compiler-generated test module, demarcated with `DUMMY_SP` plus the
380         // name `__test`
381         if item.span == DUMMY_SP && item.name.as_str() == "__test" { return }
382
383         check_item(self.tcx, item, true,
384                    &mut |id, sp, stab| self.check(id, sp, stab));
385         visit::walk_item(self, item);
386     }
387
388     fn visit_expr(&mut self, ex: &hir::Expr) {
389         check_expr(self.tcx, ex,
390                    &mut |id, sp, stab| self.check(id, sp, stab));
391         visit::walk_expr(self, ex);
392     }
393
394     fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
395         check_path(self.tcx, path, id,
396                    &mut |id, sp, stab| self.check(id, sp, stab));
397         visit::walk_path(self, path)
398     }
399
400     fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
401         check_path_list_item(self.tcx, item,
402                    &mut |id, sp, stab| self.check(id, sp, stab));
403         visit::walk_path_list_item(self, prefix, item)
404     }
405
406     fn visit_pat(&mut self, pat: &hir::Pat) {
407         check_pat(self.tcx, pat,
408                   &mut |id, sp, stab| self.check(id, sp, stab));
409         visit::walk_pat(self, pat)
410     }
411
412     fn visit_block(&mut self, b: &hir::Block) {
413         let old_skip_count = self.in_skip_block;
414         match b.rules {
415             hir::BlockCheckMode::PushUnstableBlock => {
416                 self.in_skip_block += 1;
417             }
418             hir::BlockCheckMode::PopUnstableBlock => {
419                 self.in_skip_block = self.in_skip_block.checked_sub(1).unwrap();
420             }
421             _ => {}
422         }
423         visit::walk_block(self, b);
424         self.in_skip_block = old_skip_count;
425     }
426 }
427
428 /// Helper for discovering nodes to check for stability
429 pub fn check_item(tcx: &ty::ctxt, item: &hir::Item, warn_about_defns: bool,
430                   cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
431     match item.node {
432         hir::ItemExternCrate(_) => {
433             // compiler-generated `extern crate` items have a dummy span.
434             if item.span == DUMMY_SP { return }
435
436             let cnum = match tcx.sess.cstore.find_extern_mod_stmt_cnum(item.id) {
437                 Some(cnum) => cnum,
438                 None => return,
439             };
440             let id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
441             maybe_do_stability_check(tcx, id, item.span, cb);
442         }
443
444         // For implementations of traits, check the stability of each item
445         // individually as it's possible to have a stable trait with unstable
446         // items.
447         hir::ItemImpl(_, _, _, Some(ref t), _, ref impl_items) => {
448             let trait_did = tcx.def_map.borrow().get(&t.ref_id).unwrap().def_id();
449             let trait_items = tcx.trait_items(trait_did);
450
451             for impl_item in impl_items {
452                 let item = trait_items.iter().find(|item| {
453                     item.name() == impl_item.name
454                 }).unwrap();
455                 if warn_about_defns {
456                     maybe_do_stability_check(tcx, item.def_id(), impl_item.span, cb);
457                 }
458             }
459         }
460
461         _ => (/* pass */)
462     }
463 }
464
465 /// Helper for discovering nodes to check for stability
466 pub fn check_expr(tcx: &ty::ctxt, e: &hir::Expr,
467                   cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
468     let span;
469     let id = match e.node {
470         hir::ExprMethodCall(i, _, _) => {
471             span = i.span;
472             let method_call = ty::MethodCall::expr(e.id);
473             tcx.tables.borrow().method_map[&method_call].def_id
474         }
475         hir::ExprField(ref base_e, ref field) => {
476             span = field.span;
477             match tcx.expr_ty_adjusted(base_e).sty {
478                 ty::TyStruct(def, _) => def.struct_variant().field_named(field.node).did,
479                 _ => tcx.sess.span_bug(e.span,
480                                        "stability::check_expr: named field access on non-struct")
481             }
482         }
483         hir::ExprTupField(ref base_e, ref field) => {
484             span = field.span;
485             match tcx.expr_ty_adjusted(base_e).sty {
486                 ty::TyStruct(def, _) => def.struct_variant().fields[field.node].did,
487                 ty::TyTuple(..) => return,
488                 _ => tcx.sess.span_bug(e.span,
489                                        "stability::check_expr: unnamed field access on \
490                                         something other than a tuple or struct")
491             }
492         }
493         hir::ExprStruct(_, ref expr_fields, _) => {
494             let type_ = tcx.expr_ty(e);
495             match type_.sty {
496                 ty::TyStruct(def, _) => {
497                     // check the stability of each field that appears
498                     // in the construction expression.
499                     for field in expr_fields {
500                         let did = def.struct_variant()
501                             .field_named(field.name.node)
502                             .did;
503                         maybe_do_stability_check(tcx, did, field.span, cb);
504                     }
505
506                     // we're done.
507                     return
508                 }
509                 // we don't look at stability attributes on
510                 // struct-like enums (yet...), but it's definitely not
511                 // a bug to have construct one.
512                 ty::TyEnum(..) => return,
513                 _ => {
514                     tcx.sess.span_bug(e.span,
515                                       &format!("stability::check_expr: struct construction \
516                                                 of non-struct, type {:?}",
517                                                type_));
518                 }
519             }
520         }
521         _ => return
522     };
523
524     maybe_do_stability_check(tcx, id, span, cb);
525 }
526
527 pub fn check_path(tcx: &ty::ctxt, path: &hir::Path, id: ast::NodeId,
528                   cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
529     match tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
530         Some(def::DefPrimTy(..)) => {}
531         Some(def::DefSelfTy(..)) => {}
532         Some(def) => {
533             maybe_do_stability_check(tcx, def.def_id(), path.span, cb);
534         }
535         None => {}
536     }
537 }
538
539 pub fn check_path_list_item(tcx: &ty::ctxt, item: &hir::PathListItem,
540                   cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
541     match tcx.def_map.borrow().get(&item.node.id()).map(|d| d.full_def()) {
542         Some(def::DefPrimTy(..)) => {}
543         Some(def) => {
544             maybe_do_stability_check(tcx, def.def_id(), item.span, cb);
545         }
546         None => {}
547     }
548 }
549
550 pub fn check_pat(tcx: &ty::ctxt, pat: &hir::Pat,
551                  cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
552     debug!("check_pat(pat = {:?})", pat);
553     if is_internal(tcx, pat.span) { return; }
554
555     let v = match tcx.pat_ty_opt(pat) {
556         Some(&ty::TyS { sty: ty::TyStruct(def, _), .. }) => def.struct_variant(),
557         Some(_) | None => return,
558     };
559     match pat.node {
560         // Foo(a, b, c)
561         // A Variant(..) pattern `hir::PatEnum(_, None)` doesn't have to be recursed into.
562         hir::PatEnum(_, Some(ref pat_fields)) => {
563             for (field, struct_field) in pat_fields.iter().zip(&v.fields) {
564                 maybe_do_stability_check(tcx, struct_field.did, field.span, cb)
565             }
566         }
567         // Foo { a, b, c }
568         hir::PatStruct(_, ref pat_fields, _) => {
569             for field in pat_fields {
570                 let did = v.field_named(field.node.name).did;
571                 maybe_do_stability_check(tcx, did, field.span, cb);
572             }
573         }
574         // everything else is fine.
575         _ => {}
576     }
577 }
578
579 fn maybe_do_stability_check(tcx: &ty::ctxt, id: DefId, span: Span,
580                             cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
581     if !is_staged_api(tcx, id) {
582         debug!("maybe_do_stability_check: \
583                 skipping id={:?} since it is not staged_api", id);
584         return;
585     }
586     if is_internal(tcx, span) {
587         debug!("maybe_do_stability_check: \
588                 skipping span={:?} since it is internal", span);
589         return;
590     }
591     let ref stability = lookup(tcx, id);
592     debug!("maybe_do_stability_check: \
593             inspecting id={:?} span={:?} of stability={:?}", id, span, stability);
594     cb(id, span, stability);
595 }
596
597 fn is_internal(tcx: &ty::ctxt, span: Span) -> bool {
598     tcx.sess.codemap().span_allows_unstable(span)
599 }
600
601 fn is_staged_api(tcx: &ty::ctxt, id: DefId) -> bool {
602     match tcx.trait_item_of_item(id) {
603         Some(ty::MethodTraitItemId(trait_method_id))
604             if trait_method_id != id => {
605                 is_staged_api(tcx, trait_method_id)
606             }
607         _ => {
608             *tcx.stability.borrow_mut().staged_api.entry(id.krate).or_insert_with(
609                 || csearch::is_staged_api(&tcx.sess.cstore, id.krate))
610         }
611     }
612 }
613
614 /// Lookup the stability for a node, loading external crate
615 /// metadata as necessary.
616 pub fn lookup<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
617     if let Some(st) = tcx.stability.borrow().map.get(&id) {
618         return *st;
619     }
620
621     let st = lookup_uncached(tcx, id);
622     tcx.stability.borrow_mut().map.insert(id, st);
623     st
624 }
625
626 fn lookup_uncached<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
627     debug!("lookup(id={:?})", id);
628
629     // is this definition the implementation of a trait method?
630     match tcx.trait_item_of_item(id) {
631         Some(ty::MethodTraitItemId(trait_method_id)) if trait_method_id != id => {
632             debug!("lookup: trait_method_id={:?}", trait_method_id);
633             return lookup(tcx, trait_method_id)
634         }
635         _ => {}
636     }
637
638     let item_stab = if id.is_local() {
639         None // The stability cache is filled partially lazily
640     } else {
641         csearch::get_stability(&tcx.sess.cstore, id).map(|st| tcx.intern_stability(st))
642     };
643
644     item_stab.or_else(|| {
645         if tcx.is_impl(id) {
646             if let Some(trait_id) = tcx.trait_id_of_impl(id) {
647                 // FIXME (#18969): for the time being, simply use the
648                 // stability of the trait to determine the stability of any
649                 // unmarked impls for it. See FIXME above for more details.
650
651                 debug!("lookup: trait_id={:?}", trait_id);
652                 return lookup(tcx, trait_id);
653             }
654         }
655         None
656     })
657 }
658
659 /// Given the list of enabled features that were not language features (i.e. that
660 /// were expected to be library features), and the list of features used from
661 /// libraries, identify activated features that don't exist and error about them.
662 pub fn check_unused_or_stable_features(sess: &Session,
663                                        lib_features_used: &FnvHashMap<InternedString,
664                                                                       StabilityLevel>) {
665     let ref declared_lib_features = sess.features.borrow().declared_lib_features;
666     let mut remaining_lib_features: FnvHashMap<InternedString, Span>
667         = declared_lib_features.clone().into_iter().collect();
668
669     let stable_msg = "this feature is stable. attribute no longer needed";
670
671     for &span in &sess.features.borrow().declared_stable_lang_features {
672         sess.add_lint(lint::builtin::STABLE_FEATURES,
673                       ast::CRATE_NODE_ID,
674                       span,
675                       stable_msg.to_string());
676     }
677
678     for (used_lib_feature, level) in lib_features_used {
679         match remaining_lib_features.remove(used_lib_feature) {
680             Some(span) => {
681                 if *level == Stable {
682                     sess.add_lint(lint::builtin::STABLE_FEATURES,
683                                   ast::CRATE_NODE_ID,
684                                   span,
685                                   stable_msg.to_string());
686                 }
687             }
688             None => ( /* used but undeclared, handled during the previous ast visit */ )
689         }
690     }
691
692     for &span in remaining_lib_features.values() {
693         sess.add_lint(lint::builtin::UNUSED_FEATURES,
694                       ast::CRATE_NODE_ID,
695                       span,
696                       "unused or unknown feature".to_string());
697     }
698 }