]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
Auto merge of #30341 - pnkfelix:call-site-scope, 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::{Block, Crate, Item, Generics, StructField, Variant};
33 use rustc_front::intravisit::{self, Visitor};
34
35 use std::mem::replace;
36 use std::cmp::Ordering;
37
38 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
39 pub enum StabilityLevel {
40     Unstable,
41     Stable,
42 }
43
44 impl StabilityLevel {
45     pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
46         if level.is_stable() { Stable } else { Unstable }
47     }
48 }
49
50 #[derive(PartialEq)]
51 enum AnnotationKind {
52     // Annotation is required if not inherited from unstable parents
53     Required,
54     // Annotation is useless, reject it
55     Prohibited,
56     // Annotation itself is useless, but it can be propagated to children
57     Container,
58 }
59
60 /// A stability index, giving the stability level for items and methods.
61 pub struct Index<'tcx> {
62     /// This is mostly a cache, except the stabilities of local items
63     /// are filled by the annotator.
64     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: &Vec<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.span_warn(span, "use of unmarked library feature");
398                     self.tcx.sess.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                 } else {
402                     self.tcx.sess.span_err(span, "use of unmarked library feature");
403                     self.tcx.sess.span_note(span, "this is either a bug in the library you are \
404                                                    using or a bug in the compiler - please \
405                                                    report it in both places");
406                     self.tcx.sess.span_note(span, "use #![feature(unmarked_api)] in the \
407                                                    crate attributes to override this");
408                 }
409             }
410         }
411     }
412 }
413
414 impl<'a, 'v, 'tcx> Visitor<'v> for Checker<'a, 'tcx> {
415     /// Because stability levels are scoped lexically, we want to walk
416     /// nested items in the context of the outer item, so enable
417     /// deep-walking.
418     fn visit_nested_item(&mut self, item: hir::ItemId) {
419         self.visit_item(self.tcx.map.expect_item(item.id))
420     }
421
422     fn visit_item(&mut self, item: &hir::Item) {
423         // When compiling with --test we don't enforce stability on the
424         // compiler-generated test module, demarcated with `DUMMY_SP` plus the
425         // name `__test`
426         if item.span == DUMMY_SP && item.name.as_str() == "__test" { return }
427
428         check_item(self.tcx, item, true,
429                    &mut |id, sp, stab, depr| self.check(id, sp, stab, depr));
430         intravisit::walk_item(self, item);
431     }
432
433     fn visit_expr(&mut self, ex: &hir::Expr) {
434         check_expr(self.tcx, ex,
435                    &mut |id, sp, stab, depr| self.check(id, sp, stab, depr));
436         intravisit::walk_expr(self, ex);
437     }
438
439     fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
440         check_path(self.tcx, path, id,
441                    &mut |id, sp, stab, depr| self.check(id, sp, stab, depr));
442         intravisit::walk_path(self, path)
443     }
444
445     fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
446         check_path_list_item(self.tcx, item,
447                    &mut |id, sp, stab, depr| self.check(id, sp, stab, depr));
448         intravisit::walk_path_list_item(self, prefix, item)
449     }
450
451     fn visit_pat(&mut self, pat: &hir::Pat) {
452         check_pat(self.tcx, pat,
453                   &mut |id, sp, stab, depr| self.check(id, sp, stab, depr));
454         intravisit::walk_pat(self, pat)
455     }
456
457     fn visit_block(&mut self, b: &hir::Block) {
458         let old_skip_count = self.in_skip_block;
459         match b.rules {
460             hir::BlockCheckMode::PushUnstableBlock => {
461                 self.in_skip_block += 1;
462             }
463             hir::BlockCheckMode::PopUnstableBlock => {
464                 self.in_skip_block = self.in_skip_block.checked_sub(1).unwrap();
465             }
466             _ => {}
467         }
468         intravisit::walk_block(self, b);
469         self.in_skip_block = old_skip_count;
470     }
471 }
472
473 /// Helper for discovering nodes to check for stability
474 pub fn check_item(tcx: &ty::ctxt, item: &hir::Item, warn_about_defns: bool,
475                   cb: &mut FnMut(DefId, Span, &Option<&Stability>, &Option<Deprecation>)) {
476     match item.node {
477         hir::ItemExternCrate(_) => {
478             // compiler-generated `extern crate` items have a dummy span.
479             if item.span == DUMMY_SP { return }
480
481             let cnum = match tcx.sess.cstore.extern_mod_stmt_cnum(item.id) {
482                 Some(cnum) => cnum,
483                 None => return,
484             };
485             let id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
486             maybe_do_stability_check(tcx, id, item.span, cb);
487         }
488
489         // For implementations of traits, check the stability of each item
490         // individually as it's possible to have a stable trait with unstable
491         // items.
492         hir::ItemImpl(_, _, _, Some(ref t), _, ref impl_items) => {
493             let trait_did = tcx.def_map.borrow().get(&t.ref_id).unwrap().def_id();
494             let trait_items = tcx.trait_items(trait_did);
495
496             for impl_item in impl_items {
497                 let item = trait_items.iter().find(|item| {
498                     item.name() == impl_item.name
499                 }).unwrap();
500                 if warn_about_defns {
501                     maybe_do_stability_check(tcx, item.def_id(), impl_item.span, cb);
502                 }
503             }
504         }
505
506         _ => (/* pass */)
507     }
508 }
509
510 /// Helper for discovering nodes to check for stability
511 pub fn check_expr(tcx: &ty::ctxt, e: &hir::Expr,
512                   cb: &mut FnMut(DefId, Span, &Option<&Stability>, &Option<Deprecation>)) {
513     let span;
514     let id = match e.node {
515         hir::ExprMethodCall(i, _, _) => {
516             span = i.span;
517             let method_call = ty::MethodCall::expr(e.id);
518             tcx.tables.borrow().method_map[&method_call].def_id
519         }
520         hir::ExprField(ref base_e, ref field) => {
521             span = field.span;
522             match tcx.expr_ty_adjusted(base_e).sty {
523                 ty::TyStruct(def, _) => def.struct_variant().field_named(field.node).did,
524                 _ => tcx.sess.span_bug(e.span,
525                                        "stability::check_expr: named field access on non-struct")
526             }
527         }
528         hir::ExprTupField(ref base_e, ref field) => {
529             span = field.span;
530             match tcx.expr_ty_adjusted(base_e).sty {
531                 ty::TyStruct(def, _) => def.struct_variant().fields[field.node].did,
532                 ty::TyTuple(..) => return,
533                 _ => tcx.sess.span_bug(e.span,
534                                        "stability::check_expr: unnamed field access on \
535                                         something other than a tuple or struct")
536             }
537         }
538         hir::ExprStruct(_, ref expr_fields, _) => {
539             let type_ = tcx.expr_ty(e);
540             match type_.sty {
541                 ty::TyStruct(def, _) => {
542                     // check the stability of each field that appears
543                     // in the construction expression.
544                     for field in expr_fields {
545                         let did = def.struct_variant()
546                             .field_named(field.name.node)
547                             .did;
548                         maybe_do_stability_check(tcx, did, field.span, cb);
549                     }
550
551                     // we're done.
552                     return
553                 }
554                 // we don't look at stability attributes on
555                 // struct-like enums (yet...), but it's definitely not
556                 // a bug to have construct one.
557                 ty::TyEnum(..) => return,
558                 _ => {
559                     tcx.sess.span_bug(e.span,
560                                       &format!("stability::check_expr: struct construction \
561                                                 of non-struct, type {:?}",
562                                                type_));
563                 }
564             }
565         }
566         _ => return
567     };
568
569     maybe_do_stability_check(tcx, id, span, cb);
570 }
571
572 pub fn check_path(tcx: &ty::ctxt, path: &hir::Path, id: ast::NodeId,
573                   cb: &mut FnMut(DefId, Span, &Option<&Stability>, &Option<Deprecation>)) {
574     match tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
575         Some(def::DefPrimTy(..)) => {}
576         Some(def::DefSelfTy(..)) => {}
577         Some(def) => {
578             maybe_do_stability_check(tcx, def.def_id(), path.span, cb);
579         }
580         None => {}
581     }
582 }
583
584 pub fn check_path_list_item(tcx: &ty::ctxt, item: &hir::PathListItem,
585                   cb: &mut FnMut(DefId, Span, &Option<&Stability>, &Option<Deprecation>)) {
586     match tcx.def_map.borrow().get(&item.node.id()).map(|d| d.full_def()) {
587         Some(def::DefPrimTy(..)) => {}
588         Some(def) => {
589             maybe_do_stability_check(tcx, def.def_id(), item.span, cb);
590         }
591         None => {}
592     }
593 }
594
595 pub fn check_pat(tcx: &ty::ctxt, pat: &hir::Pat,
596                  cb: &mut FnMut(DefId, Span, &Option<&Stability>, &Option<Deprecation>)) {
597     debug!("check_pat(pat = {:?})", pat);
598     if is_internal(tcx, pat.span) { return; }
599
600     let v = match tcx.pat_ty_opt(pat) {
601         Some(&ty::TyS { sty: ty::TyStruct(def, _), .. }) => def.struct_variant(),
602         Some(_) | None => return,
603     };
604     match pat.node {
605         // Foo(a, b, c)
606         // A Variant(..) pattern `hir::PatEnum(_, None)` doesn't have to be recursed into.
607         hir::PatEnum(_, Some(ref pat_fields)) => {
608             for (field, struct_field) in pat_fields.iter().zip(&v.fields) {
609                 maybe_do_stability_check(tcx, struct_field.did, field.span, cb)
610             }
611         }
612         // Foo { a, b, c }
613         hir::PatStruct(_, ref pat_fields, _) => {
614             for field in pat_fields {
615                 let did = v.field_named(field.node.name).did;
616                 maybe_do_stability_check(tcx, did, field.span, cb);
617             }
618         }
619         // everything else is fine.
620         _ => {}
621     }
622 }
623
624 fn maybe_do_stability_check(tcx: &ty::ctxt, id: DefId, span: Span,
625                             cb: &mut FnMut(DefId, Span,
626                                            &Option<&Stability>, &Option<Deprecation>)) {
627     if is_internal(tcx, span) {
628         debug!("maybe_do_stability_check: \
629                 skipping span={:?} since it is internal", span);
630         return;
631     }
632     let (stability, deprecation) = if is_staged_api(tcx, id) {
633         (lookup_stability(tcx, id), None)
634     } else {
635         (None, lookup_deprecation(tcx, id))
636     };
637     debug!("maybe_do_stability_check: \
638             inspecting id={:?} span={:?} of stability={:?}", id, span, stability);
639     cb(id, span, &stability, &deprecation);
640 }
641
642 fn is_internal(tcx: &ty::ctxt, span: Span) -> bool {
643     tcx.sess.codemap().span_allows_unstable(span)
644 }
645
646 fn is_staged_api(tcx: &ty::ctxt, id: DefId) -> bool {
647     match tcx.trait_item_of_item(id) {
648         Some(ty::MethodTraitItemId(trait_method_id))
649             if trait_method_id != id => {
650                 is_staged_api(tcx, trait_method_id)
651             }
652         _ => {
653             *tcx.stability.borrow_mut().staged_api.entry(id.krate).or_insert_with(
654                 || tcx.sess.cstore.is_staged_api(id.krate))
655         }
656     }
657 }
658
659 /// Lookup the stability for a node, loading external crate
660 /// metadata as necessary.
661 pub fn lookup_stability<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
662     if let Some(st) = tcx.stability.borrow().stab_map.get(&id) {
663         return *st;
664     }
665
666     let st = lookup_stability_uncached(tcx, id);
667     tcx.stability.borrow_mut().stab_map.insert(id, st);
668     st
669 }
670
671 pub fn lookup_deprecation<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<Deprecation> {
672     if let Some(depr) = tcx.stability.borrow().depr_map.get(&id) {
673         return depr.clone();
674     }
675
676     let depr = lookup_deprecation_uncached(tcx, id);
677     tcx.stability.borrow_mut().depr_map.insert(id, depr.clone());
678     depr
679 }
680
681 fn lookup_stability_uncached<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
682     debug!("lookup(id={:?})", id);
683     if id.is_local() {
684         None // The stability cache is filled partially lazily
685     } else {
686         tcx.sess.cstore.stability(id).map(|st| tcx.intern_stability(st))
687     }
688 }
689
690 fn lookup_deprecation_uncached<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<Deprecation> {
691     debug!("lookup(id={:?})", id);
692     if id.is_local() {
693         None // The stability cache is filled partially lazily
694     } else {
695         tcx.sess.cstore.deprecation(id)
696     }
697 }
698
699 /// Given the list of enabled features that were not language features (i.e. that
700 /// were expected to be library features), and the list of features used from
701 /// libraries, identify activated features that don't exist and error about them.
702 pub fn check_unused_or_stable_features(sess: &Session,
703                                        lib_features_used: &FnvHashMap<InternedString,
704                                                                       StabilityLevel>) {
705     let ref declared_lib_features = sess.features.borrow().declared_lib_features;
706     let mut remaining_lib_features: FnvHashMap<InternedString, Span>
707         = declared_lib_features.clone().into_iter().collect();
708
709     let stable_msg = "this feature is stable. attribute no longer needed";
710
711     for &span in &sess.features.borrow().declared_stable_lang_features {
712         sess.add_lint(lint::builtin::STABLE_FEATURES,
713                       ast::CRATE_NODE_ID,
714                       span,
715                       stable_msg.to_string());
716     }
717
718     for (used_lib_feature, level) in lib_features_used {
719         match remaining_lib_features.remove(used_lib_feature) {
720             Some(span) => {
721                 if *level == Stable {
722                     sess.add_lint(lint::builtin::STABLE_FEATURES,
723                                   ast::CRATE_NODE_ID,
724                                   span,
725                                   stable_msg.to_string());
726                 }
727             }
728             None => ( /* used but undeclared, handled during the previous ast visit */ )
729         }
730     }
731
732     for &span in remaining_lib_features.values() {
733         sess.add_lint(lint::builtin::UNUSED_FEATURES,
734                       ast::CRATE_NODE_ID,
735                       span,
736                       "unused or unknown feature".to_string());
737     }
738 }