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