]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
1cf96a4c56db587a35402c5740553d04ce14af56
[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 lint;
17 use hir::def::Def;
18 use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
19 use ty::{self, TyCtxt};
20 use middle::privacy::AccessLevels;
21 use syntax::symbol::Symbol;
22 use syntax_pos::{Span, DUMMY_SP};
23 use syntax::ast;
24 use syntax::ast::{NodeId, Attribute};
25 use syntax::feature_gate::{GateIssue, emit_feature_err, find_lang_feature_accepted_version};
26 use syntax::attr::{self, Stability, Deprecation};
27 use util::nodemap::{FxHashSet, FxHashMap};
28
29 use hir;
30 use hir::{Item, Generics, StructField, Variant, HirId};
31 use hir::intravisit::{self, Visitor, NestedVisitorMap};
32
33 use std::mem::replace;
34 use std::cmp::Ordering;
35
36 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
37 pub enum StabilityLevel {
38     Unstable,
39     Stable,
40 }
41
42 impl StabilityLevel {
43     pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
44         if level.is_stable() { Stable } else { Unstable }
45     }
46 }
47
48 #[derive(PartialEq)]
49 enum AnnotationKind {
50     // Annotation is required if not inherited from unstable parents
51     Required,
52     // Annotation is useless, reject it
53     Prohibited,
54     // Annotation itself is useless, but it can be propagated to children
55     Container,
56 }
57
58 /// An entry in the `depr_map`.
59 #[derive(Clone)]
60 pub struct DeprecationEntry {
61     /// The metadata of the attribute associated with this entry.
62     pub attr: Deprecation,
63     /// The def id where the attr was originally attached. `None` for non-local
64     /// `DefId`'s.
65     origin: Option<HirId>,
66 }
67
68 impl DeprecationEntry {
69     fn local(attr: Deprecation, id: HirId) -> DeprecationEntry {
70         DeprecationEntry {
71             attr,
72             origin: Some(id),
73         }
74     }
75
76     pub fn external(attr: Deprecation) -> DeprecationEntry {
77         DeprecationEntry {
78             attr,
79             origin: None,
80         }
81     }
82
83     pub fn same_origin(&self, other: &DeprecationEntry) -> bool {
84         match (self.origin, other.origin) {
85             (Some(o1), Some(o2)) => o1 == o2,
86             _ => false
87         }
88     }
89 }
90
91 /// A stability index, giving the stability level for items and methods.
92 pub struct Index<'tcx> {
93     /// This is mostly a cache, except the stabilities of local items
94     /// are filled by the annotator.
95     stab_map: FxHashMap<HirId, &'tcx Stability>,
96     depr_map: FxHashMap<HirId, DeprecationEntry>,
97
98     /// Maps for each crate whether it is part of the staged API.
99     staged_api: FxHashMap<CrateNum, bool>,
100
101     /// Features enabled for this crate.
102     active_features: FxHashSet<Symbol>,
103 }
104
105 // A private tree-walker for producing an Index.
106 struct Annotator<'a, 'tcx: 'a> {
107     tcx: TyCtxt<'a, 'tcx, 'tcx>,
108     index: &'a mut Index<'tcx>,
109     parent_stab: Option<&'tcx Stability>,
110     parent_depr: Option<DeprecationEntry>,
111     in_trait_impl: bool,
112 }
113
114 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
115     // Determine the stability for a node based on its attributes and inherited
116     // stability. The stability is recorded in the index and used as the parent.
117     fn annotate<F>(&mut self, id: NodeId, attrs: &[Attribute],
118                    item_sp: Span, kind: AnnotationKind, visit_children: F)
119         where F: FnOnce(&mut Self)
120     {
121         if self.tcx.sess.features.borrow().staged_api {
122             // This crate explicitly wants staged API.
123             debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
124             if let Some(..) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
125                 self.tcx.sess.span_err(item_sp, "`#[deprecated]` cannot be used in staged api, \
126                                                  use `#[rustc_deprecated]` instead");
127             }
128             if let Some(mut stab) = attr::find_stability(self.tcx.sess.diagnostic(),
129                                                          attrs, item_sp) {
130                 // Error if prohibited, or can't inherit anything from a container
131                 if kind == AnnotationKind::Prohibited ||
132                    (kind == AnnotationKind::Container &&
133                     stab.level.is_stable() &&
134                     stab.rustc_depr.is_none()) {
135                     self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
136                 }
137
138                 debug!("annotate: found {:?}", stab);
139                 // If parent is deprecated and we're not, inherit this by merging
140                 // deprecated_since and its reason.
141                 if let Some(parent_stab) = self.parent_stab {
142                     if parent_stab.rustc_depr.is_some() && stab.rustc_depr.is_none() {
143                         stab.rustc_depr = parent_stab.rustc_depr.clone()
144                     }
145                 }
146
147                 let stab = self.tcx.intern_stability(stab);
148
149                 // Check if deprecated_since < stable_since. If it is,
150                 // this is *almost surely* an accident.
151                 if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
152                         &attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
153                     // Explicit version of iter::order::lt to handle parse errors properly
154                     for (dep_v, stab_v) in
155                             dep_since.as_str().split(".").zip(stab_since.as_str().split(".")) {
156                         if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
157                             match dep_v.cmp(&stab_v) {
158                                 Ordering::Less => {
159                                     self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
160                                                                      after it is deprecated");
161                                     break
162                                 }
163                                 Ordering::Equal => continue,
164                                 Ordering::Greater => break,
165                             }
166                         } else {
167                             // Act like it isn't less because the question is now nonsensical,
168                             // and this makes us not do anything else interesting.
169                             self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
170                                                              version found");
171                             break
172                         }
173                     }
174                 }
175
176                 let hir_id = self.tcx.hir.node_to_hir_id(id);
177                 self.index.stab_map.insert(hir_id, stab);
178
179                 let orig_parent_stab = replace(&mut self.parent_stab, Some(stab));
180                 visit_children(self);
181                 self.parent_stab = orig_parent_stab;
182             } else {
183                 debug!("annotate: not found, parent = {:?}", self.parent_stab);
184                 if let Some(stab) = self.parent_stab {
185                     if stab.level.is_unstable() {
186                         let hir_id = self.tcx.hir.node_to_hir_id(id);
187                         self.index.stab_map.insert(hir_id, stab);
188                     }
189                 }
190                 visit_children(self);
191             }
192         } else {
193             // Emit errors for non-staged-api crates.
194             for attr in attrs {
195                 let tag = unwrap_or!(attr.name(), continue);
196                 if tag == "unstable" || tag == "stable" || tag == "rustc_deprecated" {
197                     attr::mark_used(attr);
198                     self.tcx.sess.span_err(attr.span(), "stability attributes may not be used \
199                                                          outside of the standard library");
200                 }
201             }
202
203             // Propagate unstability.  This can happen even for non-staged-api crates in case
204             // -Zforce-unstable-if-unmarked is set.
205             if let Some(stab) = self.parent_stab {
206                 if stab.level.is_unstable() {
207                     let hir_id = self.tcx.hir.node_to_hir_id(id);
208                     self.index.stab_map.insert(hir_id, stab);
209                 }
210             }
211
212             if let Some(depr) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
213                 if kind == AnnotationKind::Prohibited {
214                     self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
215                 }
216
217                 // `Deprecation` is just two pointers, no need to intern it
218                 let hir_id = self.tcx.hir.node_to_hir_id(id);
219                 let depr_entry = DeprecationEntry::local(depr, hir_id);
220                 self.index.depr_map.insert(hir_id, depr_entry.clone());
221
222                 let orig_parent_depr = replace(&mut self.parent_depr,
223                                                Some(depr_entry));
224                 visit_children(self);
225                 self.parent_depr = orig_parent_depr;
226             } else if let Some(parent_depr) = self.parent_depr.clone() {
227                 let hir_id = self.tcx.hir.node_to_hir_id(id);
228                 self.index.depr_map.insert(hir_id, parent_depr);
229                 visit_children(self);
230             } else {
231                 visit_children(self);
232             }
233         }
234     }
235 }
236
237 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
238     /// Because stability levels are scoped lexically, we want to walk
239     /// nested items in the context of the outer item, so enable
240     /// deep-walking.
241     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
242         NestedVisitorMap::All(&self.tcx.hir)
243     }
244
245     fn visit_item(&mut self, i: &'tcx Item) {
246         let orig_in_trait_impl = self.in_trait_impl;
247         let mut kind = AnnotationKind::Required;
248         match i.node {
249             // Inherent impls and foreign modules serve only as containers for other items,
250             // they don't have their own stability. They still can be annotated as unstable
251             // and propagate this unstability to children, but this annotation is completely
252             // optional. They inherit stability from their parents when unannotated.
253             hir::ItemImpl(.., None, _, _) | hir::ItemForeignMod(..) => {
254                 self.in_trait_impl = false;
255                 kind = AnnotationKind::Container;
256             }
257             hir::ItemImpl(.., Some(_), _, _) => {
258                 self.in_trait_impl = true;
259             }
260             hir::ItemStruct(ref sd, _) => {
261                 if !sd.is_struct() {
262                     self.annotate(sd.id(), &i.attrs, i.span, AnnotationKind::Required, |_| {})
263                 }
264             }
265             _ => {}
266         }
267
268         self.annotate(i.id, &i.attrs, i.span, kind, |v| {
269             intravisit::walk_item(v, i)
270         });
271         self.in_trait_impl = orig_in_trait_impl;
272     }
273
274     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
275         self.annotate(ti.id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
276             intravisit::walk_trait_item(v, ti);
277         });
278     }
279
280     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
281         let kind = if self.in_trait_impl {
282             AnnotationKind::Prohibited
283         } else {
284             AnnotationKind::Required
285         };
286         self.annotate(ii.id, &ii.attrs, ii.span, kind, |v| {
287             intravisit::walk_impl_item(v, ii);
288         });
289     }
290
291     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
292         self.annotate(var.node.data.id(), &var.node.attrs, var.span, AnnotationKind::Required, |v| {
293             intravisit::walk_variant(v, var, g, item_id);
294         })
295     }
296
297     fn visit_struct_field(&mut self, s: &'tcx StructField) {
298         self.annotate(s.id, &s.attrs, s.span, AnnotationKind::Required, |v| {
299             intravisit::walk_struct_field(v, s);
300         });
301     }
302
303     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
304         self.annotate(i.id, &i.attrs, i.span, AnnotationKind::Required, |v| {
305             intravisit::walk_foreign_item(v, i);
306         });
307     }
308
309     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
310         self.annotate(md.id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
311     }
312 }
313
314 struct MissingStabilityAnnotations<'a, 'tcx: 'a> {
315     tcx: TyCtxt<'a, 'tcx, 'tcx>,
316     access_levels: &'a AccessLevels,
317 }
318
319 impl<'a, 'tcx: 'a> MissingStabilityAnnotations<'a, 'tcx> {
320     fn check_missing_stability(&self, id: NodeId, span: Span) {
321         let hir_id = self.tcx.hir.node_to_hir_id(id);
322         let stab = self.tcx.stability().local_stability(hir_id);
323         let is_error = !self.tcx.sess.opts.test &&
324                         stab.is_none() &&
325                         self.access_levels.is_reachable(id);
326         if is_error {
327             self.tcx.sess.span_err(span, "This node does not have a stability attribute");
328         }
329     }
330 }
331
332 impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> {
333     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
334         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
335     }
336
337     fn visit_item(&mut self, i: &'tcx Item) {
338         match i.node {
339             // Inherent impls and foreign modules serve only as containers for other items,
340             // they don't have their own stability. They still can be annotated as unstable
341             // and propagate this unstability to children, but this annotation is completely
342             // optional. They inherit stability from their parents when unannotated.
343             hir::ItemImpl(.., None, _, _) | hir::ItemForeignMod(..) => {}
344
345             _ => self.check_missing_stability(i.id, i.span)
346         }
347
348         intravisit::walk_item(self, i)
349     }
350
351     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
352         self.check_missing_stability(ti.id, ti.span);
353         intravisit::walk_trait_item(self, ti);
354     }
355
356     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
357         let impl_def_id = self.tcx.hir.local_def_id(self.tcx.hir.get_parent(ii.id));
358         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
359             self.check_missing_stability(ii.id, ii.span);
360         }
361         intravisit::walk_impl_item(self, ii);
362     }
363
364     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
365         self.check_missing_stability(var.node.data.id(), var.span);
366         intravisit::walk_variant(self, var, g, item_id);
367     }
368
369     fn visit_struct_field(&mut self, s: &'tcx StructField) {
370         self.check_missing_stability(s.id, s.span);
371         intravisit::walk_struct_field(self, s);
372     }
373
374     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
375         self.check_missing_stability(i.id, i.span);
376         intravisit::walk_foreign_item(self, i);
377     }
378
379     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
380         self.check_missing_stability(md.id, md.span);
381     }
382 }
383
384 impl<'a, 'tcx> Index<'tcx> {
385     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Index<'tcx> {
386         let is_staged_api =
387             tcx.sess.opts.debugging_opts.force_unstable_if_unmarked ||
388             tcx.sess.features.borrow().staged_api;
389         let mut staged_api = FxHashMap();
390         staged_api.insert(LOCAL_CRATE, is_staged_api);
391         let mut index = Index {
392             staged_api,
393             stab_map: FxHashMap(),
394             depr_map: FxHashMap(),
395             active_features: FxHashSet(),
396         };
397
398         let ref active_lib_features = tcx.sess.features.borrow().declared_lib_features;
399
400         // Put the active features into a map for quick lookup
401         index.active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
402
403         {
404             let krate = tcx.hir.krate();
405             let mut annotator = Annotator {
406                 tcx,
407                 index: &mut index,
408                 parent_stab: None,
409                 parent_depr: None,
410                 in_trait_impl: false,
411             };
412
413             // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
414             // a parent stability annotation which indicates that this is private
415             // with the `rustc_private` feature. This is intended for use when
416             // compiling librustc crates themselves so we can leverage crates.io
417             // while maintaining the invariant that all sysroot crates are unstable
418             // by default and are unable to be used.
419             if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
420                 let reason = "this crate is being loaded from the sysroot, and \
421                               unstable location; did you mean to load this crate \
422                               from crates.io via `Cargo.toml` instead?";
423                 let stability = tcx.intern_stability(Stability {
424                     level: attr::StabilityLevel::Unstable {
425                         reason: Some(Symbol::intern(reason)),
426                         issue: 27812,
427                     },
428                     feature: Symbol::intern("rustc_private"),
429                     rustc_depr: None,
430                 });
431                 annotator.parent_stab = Some(stability);
432             }
433
434             annotator.annotate(ast::CRATE_NODE_ID,
435                                &krate.attrs,
436                                krate.span,
437                                AnnotationKind::Required,
438                                |v| intravisit::walk_crate(v, krate));
439         }
440         return index
441     }
442
443     pub fn local_stability(&self, id: HirId) -> Option<&'tcx Stability> {
444         self.stab_map.get(&id).cloned()
445     }
446
447     pub fn local_deprecation_entry(&self, id: HirId) -> Option<DeprecationEntry> {
448         self.depr_map.get(&id).cloned()
449     }
450 }
451
452 /// Cross-references the feature names of unstable APIs with enabled
453 /// features and possibly prints errors.
454 pub fn check_unstable_api_usage<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
455     let mut checker = Checker { tcx: tcx };
456     tcx.hir.krate().visit_all_item_likes(&mut checker.as_deep_visitor());
457 }
458
459 struct Checker<'a, 'tcx: 'a> {
460     tcx: TyCtxt<'a, 'tcx, 'tcx>,
461 }
462
463 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
464     // (See issue #38412)
465     fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
466         // Check if `def_id` is a trait method.
467         match self.describe_def(def_id) {
468             Some(Def::Method(_)) |
469             Some(Def::AssociatedTy(_)) |
470             Some(Def::AssociatedConst(_)) => {
471                 match self.associated_item(def_id).container {
472                     ty::TraitContainer(trait_def_id) => {
473                         // Trait methods do not declare visibility (even
474                         // for visibility info in cstore). Use containing
475                         // trait instead, so methods of pub traits are
476                         // themselves considered pub.
477                         def_id = trait_def_id;
478                     }
479                     _ => {}
480                 }
481             }
482             _ => {}
483         }
484
485         let visibility = self.visibility(def_id);
486
487         match visibility {
488             // must check stability for pub items.
489             ty::Visibility::Public => false,
490
491             // these are not visible outside crate; therefore
492             // stability markers are irrelevant, if even present.
493             ty::Visibility::Restricted(..) |
494             ty::Visibility::Invisible => true,
495         }
496     }
497
498     pub fn check_stability(self, def_id: DefId, id: NodeId, span: Span) {
499         if span.allows_unstable() {
500             debug!("stability: \
501                     skipping span={:?} since it is internal", span);
502             return;
503         }
504
505         let lint_deprecated = |note: Option<Symbol>| {
506             let msg = if let Some(note) = note {
507                 format!("use of deprecated item: {}", note)
508             } else {
509                 format!("use of deprecated item")
510             };
511
512             self.lint_node(lint::builtin::DEPRECATED, id, span, &msg);
513         };
514
515         // Deprecated attributes apply in-crate and cross-crate.
516         if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
517             let skip = if id == ast::DUMMY_NODE_ID {
518                 true
519             } else {
520                 let parent_def_id = self.hir.local_def_id(self.hir.get_parent(id));
521                 self.lookup_deprecation_entry(parent_def_id).map_or(false, |parent_depr| {
522                     parent_depr.same_origin(&depr_entry)
523                 })
524             };
525
526             if !skip {
527                 lint_deprecated(depr_entry.attr.note);
528             }
529         }
530
531         let is_staged_api = self.lookup_stability(DefId {
532             index: CRATE_DEF_INDEX,
533             ..def_id
534         }).is_some();
535         if !is_staged_api {
536             return;
537         }
538
539         let stability = self.lookup_stability(def_id);
540         debug!("stability: \
541                 inspecting def_id={:?} span={:?} of stability={:?}", def_id, span, stability);
542
543         if let Some(&Stability{rustc_depr: Some(attr::RustcDeprecation { reason, .. }), ..})
544                 = stability {
545             if id != ast::DUMMY_NODE_ID {
546                 lint_deprecated(Some(reason));
547             }
548         }
549
550         // Only the cross-crate scenario matters when checking unstable APIs
551         let cross_crate = !def_id.is_local();
552         if !cross_crate {
553             return
554         }
555
556         // Issue 38412: private items lack stability markers.
557         if self.skip_stability_check_due_to_privacy(def_id) {
558             return
559         }
560
561         match stability {
562             Some(&Stability { level: attr::Unstable {ref reason, issue}, ref feature, .. }) => {
563                 if self.stability().active_features.contains(feature) {
564                     return
565                 }
566
567                 // When we're compiling the compiler itself we may pull in
568                 // crates from crates.io, but those crates may depend on other
569                 // crates also pulled in from crates.io. We want to ideally be
570                 // able to compile everything without requiring upstream
571                 // modifications, so in the case that this looks like a
572                 // rustc_private crate (e.g. a compiler crate) and we also have
573                 // the `-Z force-unstable-if-unmarked` flag present (we're
574                 // compiling a compiler crate), then let this missing feature
575                 // annotation slide.
576                 if *feature == "rustc_private" && issue == 27812 {
577                     if self.sess.opts.debugging_opts.force_unstable_if_unmarked {
578                         return
579                     }
580                 }
581
582                 let msg = match *reason {
583                     Some(ref r) => format!("use of unstable library feature '{}': {}",
584                                            feature.as_str(), &r),
585                     None => format!("use of unstable library feature '{}'", &feature)
586                 };
587                 emit_feature_err(&self.sess.parse_sess, &feature.as_str(), span,
588                                  GateIssue::Library(Some(issue)), &msg);
589             }
590             Some(_) => {
591                 // Stable APIs are always ok to call and deprecated APIs are
592                 // handled by the lint emitting logic above.
593             }
594             None => {
595                 span_bug!(span, "encountered unmarked API");
596             }
597         }
598     }
599 }
600
601 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
602     /// Because stability levels are scoped lexically, we want to walk
603     /// nested items in the context of the outer item, so enable
604     /// deep-walking.
605     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
606         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
607     }
608
609     fn visit_item(&mut self, item: &'tcx hir::Item) {
610         match item.node {
611             hir::ItemExternCrate(_) => {
612                 // compiler-generated `extern crate` items have a dummy span.
613                 if item.span == DUMMY_SP { return }
614
615                 let hir_id = self.tcx.hir.node_to_hir_id(item.id);
616                 let cnum = match self.tcx.extern_mod_stmt_cnum(hir_id) {
617                     Some(cnum) => cnum,
618                     None => return,
619                 };
620                 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
621                 self.tcx.check_stability(def_id, item.id, item.span);
622             }
623
624             // For implementations of traits, check the stability of each item
625             // individually as it's possible to have a stable trait with unstable
626             // items.
627             hir::ItemImpl(.., Some(ref t), _, ref impl_item_refs) => {
628                 if let Def::Trait(trait_did) = t.path.def {
629                     for impl_item_ref in impl_item_refs {
630                         let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
631                         let trait_item_def_id = self.tcx.associated_items(trait_did)
632                             .find(|item| item.name == impl_item.name).map(|item| item.def_id);
633                         if let Some(def_id) = trait_item_def_id {
634                             // Pass `DUMMY_NODE_ID` to skip deprecation warnings.
635                             self.tcx.check_stability(def_id, ast::DUMMY_NODE_ID, impl_item.span);
636                         }
637                     }
638                 }
639             }
640
641             // There's no good place to insert stability check for non-Copy unions,
642             // so semi-randomly perform it here in stability.rs
643             hir::ItemUnion(..) if !self.tcx.sess.features.borrow().untagged_unions => {
644                 let def_id = self.tcx.hir.local_def_id(item.id);
645                 let adt_def = self.tcx.adt_def(def_id);
646                 let ty = self.tcx.type_of(def_id);
647
648                 if adt_def.has_dtor(self.tcx) {
649                     emit_feature_err(&self.tcx.sess.parse_sess,
650                                      "untagged_unions", item.span, GateIssue::Language,
651                                      "unions with `Drop` implementations are unstable");
652                 } else {
653                     let param_env = self.tcx.param_env(def_id);
654                     if !param_env.can_type_implement_copy(self.tcx, ty, item.span).is_ok() {
655                         emit_feature_err(&self.tcx.sess.parse_sess,
656                                         "untagged_unions", item.span, GateIssue::Language,
657                                         "unions with non-`Copy` fields are unstable");
658                     }
659                 }
660             }
661
662             _ => (/* pass */)
663         }
664         intravisit::walk_item(self, item);
665     }
666
667     fn visit_path(&mut self, path: &'tcx hir::Path, id: ast::NodeId) {
668         match path.def {
669             Def::Local(..) | Def::Upvar(..) |
670             Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => {}
671             _ => self.tcx.check_stability(path.def.def_id(), id, path.span)
672         }
673         intravisit::walk_path(self, path)
674     }
675 }
676
677 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
678     pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
679         self.lookup_deprecation_entry(id).map(|depr| depr.attr)
680     }
681 }
682
683 /// Given the list of enabled features that were not language features (i.e. that
684 /// were expected to be library features), and the list of features used from
685 /// libraries, identify activated features that don't exist and error about them.
686 pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
687     let sess = &tcx.sess;
688
689     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
690
691     if tcx.stability().staged_api[&LOCAL_CRATE] {
692         let krate = tcx.hir.krate();
693         let mut missing = MissingStabilityAnnotations {
694             tcx,
695             access_levels,
696         };
697         missing.check_missing_stability(ast::CRATE_NODE_ID, krate.span);
698         intravisit::walk_crate(&mut missing, krate);
699         krate.visit_all_item_likes(&mut missing.as_deep_visitor());
700     }
701
702     let ref declared_lib_features = sess.features.borrow().declared_lib_features;
703     let mut remaining_lib_features: FxHashMap<Symbol, Span>
704         = declared_lib_features.clone().into_iter().collect();
705     remaining_lib_features.remove(&Symbol::intern("proc_macro"));
706
707     for &(ref stable_lang_feature, span) in &sess.features.borrow().declared_stable_lang_features {
708         let version = find_lang_feature_accepted_version(&stable_lang_feature.as_str())
709             .expect("unexpectedly couldn't find version feature was stabilized");
710         tcx.lint_node(lint::builtin::STABLE_FEATURES,
711                       ast::CRATE_NODE_ID,
712                       span,
713                       &format_stable_since_msg(version));
714     }
715
716     // FIXME(#44232) the `used_features` table no longer exists, so we don't
717     //               lint about unknown or unused features. We should reenable
718     //               this one day!
719     //
720     // let index = tcx.stability();
721     // for (used_lib_feature, level) in &index.used_features {
722     //     remaining_lib_features.remove(used_lib_feature);
723     // }
724     //
725     // for &span in remaining_lib_features.values() {
726     //     tcx.lint_node(lint::builtin::UNUSED_FEATURES,
727     //                   ast::CRATE_NODE_ID,
728     //                   span,
729     //                   "unused or unknown feature");
730     // }
731 }
732
733 fn format_stable_since_msg(version: &str) -> String {
734     format!("this feature has been stable since {}. Attribute no longer needed", version)
735 }