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