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