]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/stability.rs
New upstream version 1.16.0+dfsg1
[rustc.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, def_id: DefId) -> bool {
437 let visibility = {
438 // Check if `def_id` is a trait method.
439 match self.sess.cstore.associated_item(def_id) {
440 Some(ty::AssociatedItem { container: ty::TraitContainer(trait_def_id), .. }) => {
441 // Trait methods do not declare visibility (even
442 // for visibility info in cstore). Use containing
443 // trait instead, so methods of pub traits are
444 // themselves considered pub.
445 self.sess.cstore.visibility(trait_def_id)
446 }
447 _ => {
448 // Otherwise, cstore info works directly.
449 self.sess.cstore.visibility(def_id)
450 }
451 }
452 };
453
454 match visibility {
455 // must check stability for pub items.
456 ty::Visibility::Public => false,
457
458 // these are not visible outside crate; therefore
459 // stability markers are irrelevant, if even present.
460 ty::Visibility::Restricted(..) |
461 ty::Visibility::Invisible => true,
462 }
463 }
464
465 pub fn check_stability(self, def_id: DefId, id: NodeId, span: Span) {
466 if self.sess.codemap().span_allows_unstable(span) {
467 debug!("stability: \
468 skipping span={:?} since it is internal", span);
469 return;
470 }
471
472 let lint_deprecated = |note: Option<Symbol>| {
473 let msg = if let Some(note) = note {
474 format!("use of deprecated item: {}", note)
475 } else {
476 format!("use of deprecated item")
477 };
478
479 self.sess.add_lint(lint::builtin::DEPRECATED, id, span, msg);
480 };
481
482 // Deprecated attributes apply in-crate and cross-crate.
483 if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
484 let skip = if id == ast::DUMMY_NODE_ID {
485 true
486 } else {
487 let parent_def_id = self.hir.local_def_id(self.hir.get_parent(id));
488 self.lookup_deprecation_entry(parent_def_id).map_or(false, |parent_depr| {
489 parent_depr.same_origin(&depr_entry)
490 })
491 };
492
493 if !skip {
494 lint_deprecated(depr_entry.attr.note);
495 }
496 }
497
498 let is_staged_api = *self.stability.borrow_mut().staged_api.entry(def_id.krate)
499 .or_insert_with(|| self.sess.cstore.is_staged_api(def_id.krate));
500 if !is_staged_api {
501 return;
502 }
503
504 let stability = self.lookup_stability(def_id);
505 debug!("stability: \
506 inspecting def_id={:?} span={:?} of stability={:?}", def_id, span, stability);
507
508 if let Some(&Stability{rustc_depr: Some(attr::RustcDeprecation { reason, .. }), ..})
509 = stability {
510 if id != ast::DUMMY_NODE_ID {
511 lint_deprecated(Some(reason));
512 }
513 }
514
515 // Only the cross-crate scenario matters when checking unstable APIs
516 let cross_crate = !def_id.is_local();
517 if !cross_crate {
518 return
519 }
520
521 if let Some(&Stability { ref level, ref feature, .. }) = stability {
522 self.stability.borrow_mut().used_features.insert(feature.clone(), level.clone());
523 }
524
525 // Issue 38412: private items lack stability markers.
526 if self.skip_stability_check_due_to_privacy(def_id) {
527 return
528 }
529
530 match stability {
531 Some(&Stability { level: attr::Unstable {ref reason, issue}, ref feature, .. }) => {
532 if !self.stability.borrow().active_features.contains(feature) {
533 let msg = match *reason {
534 Some(ref r) => format!("use of unstable library feature '{}': {}",
535 &feature.as_str(), &r),
536 None => format!("use of unstable library feature '{}'", &feature)
537 };
538 emit_feature_err(&self.sess.parse_sess, &feature.as_str(), span,
539 GateIssue::Library(Some(issue)), &msg);
540 }
541 }
542 Some(_) => {
543 // Stable APIs are always ok to call and deprecated APIs are
544 // handled by the lint emitting logic above.
545 }
546 None => {
547 span_bug!(span, "encountered unmarked API");
548 }
549 }
550 }
551 }
552
553 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
554 /// Because stability levels are scoped lexically, we want to walk
555 /// nested items in the context of the outer item, so enable
556 /// deep-walking.
557 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
558 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
559 }
560
561 fn visit_item(&mut self, item: &'tcx hir::Item) {
562 match item.node {
563 hir::ItemExternCrate(_) => {
564 // compiler-generated `extern crate` items have a dummy span.
565 if item.span == DUMMY_SP { return }
566
567 let cnum = match self.tcx.sess.cstore.extern_mod_stmt_cnum(item.id) {
568 Some(cnum) => cnum,
569 None => return,
570 };
571 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
572 self.tcx.check_stability(def_id, item.id, item.span);
573 }
574
575 // For implementations of traits, check the stability of each item
576 // individually as it's possible to have a stable trait with unstable
577 // items.
578 hir::ItemImpl(.., Some(ref t), _, ref impl_item_refs) => {
579 if let Def::Trait(trait_did) = t.path.def {
580 for impl_item_ref in impl_item_refs {
581 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
582 let trait_item_def_id = self.tcx.associated_items(trait_did)
583 .find(|item| item.name == impl_item.name).map(|item| item.def_id);
584 if let Some(def_id) = trait_item_def_id {
585 // Pass `DUMMY_NODE_ID` to skip deprecation warnings.
586 self.tcx.check_stability(def_id, ast::DUMMY_NODE_ID, impl_item.span);
587 }
588 }
589 }
590 }
591
592 _ => (/* pass */)
593 }
594 intravisit::walk_item(self, item);
595 }
596
597 fn visit_path(&mut self, path: &'tcx hir::Path, id: ast::NodeId) {
598 match path.def {
599 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => {}
600 _ => self.tcx.check_stability(path.def.def_id(), id, path.span)
601 }
602 intravisit::walk_path(self, path)
603 }
604 }
605
606 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
607 /// Lookup the stability for a node, loading external crate
608 /// metadata as necessary.
609 pub fn lookup_stability(self, id: DefId) -> Option<&'gcx Stability> {
610 if let Some(st) = self.stability.borrow().stab_map.get(&id) {
611 return *st;
612 }
613
614 let st = self.lookup_stability_uncached(id);
615 self.stability.borrow_mut().stab_map.insert(id, st);
616 st
617 }
618
619 pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
620 self.lookup_deprecation_entry(id).map(|depr| depr.attr)
621 }
622
623 pub fn lookup_deprecation_entry(self, id: DefId) -> Option<DeprecationEntry> {
624 if let Some(depr) = self.stability.borrow().depr_map.get(&id) {
625 return depr.clone();
626 }
627
628 let depr = self.lookup_deprecation_uncached(id);
629 self.stability.borrow_mut().depr_map.insert(id, depr.clone());
630 depr
631 }
632
633 fn lookup_stability_uncached(self, id: DefId) -> Option<&'gcx Stability> {
634 debug!("lookup(id={:?})", id);
635 if id.is_local() {
636 None // The stability cache is filled partially lazily
637 } else {
638 self.sess.cstore.stability(id).map(|st| self.intern_stability(st))
639 }
640 }
641
642 fn lookup_deprecation_uncached(self, id: DefId) -> Option<DeprecationEntry> {
643 debug!("lookup(id={:?})", id);
644 if id.is_local() {
645 None // The stability cache is filled partially lazily
646 } else {
647 self.sess.cstore.deprecation(id).map(DeprecationEntry::external)
648 }
649 }
650 }
651
652 /// Given the list of enabled features that were not language features (i.e. that
653 /// were expected to be library features), and the list of features used from
654 /// libraries, identify activated features that don't exist and error about them.
655 pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
656 access_levels: &AccessLevels) {
657 let sess = &tcx.sess;
658
659 if tcx.stability.borrow().staged_api[&LOCAL_CRATE] && tcx.sess.features.borrow().staged_api {
660 let _task = tcx.dep_graph.in_task(DepNode::StabilityIndex);
661 let krate = tcx.hir.krate();
662 let mut missing = MissingStabilityAnnotations {
663 tcx: tcx,
664 access_levels: access_levels,
665 };
666 missing.check_missing_stability(ast::CRATE_NODE_ID, krate.span);
667 intravisit::walk_crate(&mut missing, krate);
668 krate.visit_all_item_likes(&mut missing.as_deep_visitor());
669 }
670
671 let ref declared_lib_features = sess.features.borrow().declared_lib_features;
672 let mut remaining_lib_features: FxHashMap<Symbol, Span>
673 = declared_lib_features.clone().into_iter().collect();
674
675 fn format_stable_since_msg(version: &str) -> String {
676 format!("this feature has been stable since {}. Attribute no longer needed", version)
677 }
678
679 for &(ref stable_lang_feature, span) in &sess.features.borrow().declared_stable_lang_features {
680 let version = find_lang_feature_accepted_version(&stable_lang_feature.as_str())
681 .expect("unexpectedly couldn't find version feature was stabilized");
682 sess.add_lint(lint::builtin::STABLE_FEATURES,
683 ast::CRATE_NODE_ID,
684 span,
685 format_stable_since_msg(version));
686 }
687
688 let index = tcx.stability.borrow();
689 for (used_lib_feature, level) in &index.used_features {
690 match remaining_lib_features.remove(used_lib_feature) {
691 Some(span) => {
692 if let &attr::StabilityLevel::Stable { since: ref version } = level {
693 sess.add_lint(lint::builtin::STABLE_FEATURES,
694 ast::CRATE_NODE_ID,
695 span,
696 format_stable_since_msg(&version.as_str()));
697 }
698 }
699 None => ( /* used but undeclared, handled during the previous ast visit */ )
700 }
701 }
702
703 for &span in remaining_lib_features.values() {
704 sess.add_lint(lint::builtin::UNUSED_FEATURES,
705 ast::CRATE_NODE_ID,
706 span,
707 "unused or unknown feature".to_string());
708 }
709 }