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