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