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