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