]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/stability.rs
Various minor/cosmetic improvements to code
[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::{self, Item, Generics, StructField, Variant, HirId};
18 use hir::def::Def;
19 use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
20 use hir::intravisit::{self, Visitor, NestedVisitorMap};
21 use middle::privacy::AccessLevels;
22 use session::{DiagnosticMessageId, Session};
23 use syntax::symbol::Symbol;
24 use syntax_pos::{Span, MultiSpan};
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};
29 use ty::{self, TyCtxt};
30 use util::nodemap::{FxHashSet, FxHashMap};
31
32 use std::mem::replace;
33 use std::cmp::Ordering;
34
35 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
36 pub enum StabilityLevel {
37     Unstable,
38     Stable,
39 }
40
41 impl StabilityLevel {
42     pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
43         if level.is_stable() { Stable } else { Unstable }
44     }
45 }
46
47 #[derive(PartialEq)]
48 enum AnnotationKind {
49     // Annotation is required if not inherited from unstable parents
50     Required,
51     // Annotation is useless, reject it
52     Prohibited,
53     // Annotation itself is useless, but it can be propagated to children
54     Container,
55 }
56
57 /// An entry in the `depr_map`.
58 #[derive(Clone)]
59 pub struct DeprecationEntry {
60     /// The metadata of the attribute associated with this entry.
61     pub attr: Deprecation,
62     /// The def id where the attr was originally attached. `None` for non-local
63     /// `DefId`'s.
64     origin: Option<HirId>,
65 }
66
67 impl_stable_hash_for!(struct self::DeprecationEntry {
68     attr,
69     origin
70 });
71
72 impl DeprecationEntry {
73     fn local(attr: Deprecation, id: HirId) -> DeprecationEntry {
74         DeprecationEntry {
75             attr,
76             origin: Some(id),
77         }
78     }
79
80     pub fn external(attr: Deprecation) -> DeprecationEntry {
81         DeprecationEntry {
82             attr,
83             origin: None,
84         }
85     }
86
87     pub fn same_origin(&self, other: &DeprecationEntry) -> bool {
88         match (self.origin, other.origin) {
89             (Some(o1), Some(o2)) => o1 == o2,
90             _ => false
91         }
92     }
93 }
94
95 /// A stability index, giving the stability level for items and methods.
96 pub struct Index<'tcx> {
97     /// This is mostly a cache, except the stabilities of local items
98     /// are filled by the annotator.
99     stab_map: FxHashMap<HirId, &'tcx Stability>,
100     depr_map: FxHashMap<HirId, DeprecationEntry>,
101
102     /// Maps for each crate whether it is part of the staged API.
103     staged_api: FxHashMap<CrateNum, bool>,
104
105     /// Features enabled for this crate.
106     active_features: FxHashSet<Symbol>,
107 }
108
109 impl_stable_hash_for!(struct self::Index<'tcx> {
110     stab_map,
111     depr_map,
112     staged_api,
113     active_features
114 });
115
116 // A private tree-walker for producing an Index.
117 struct Annotator<'a, 'tcx: 'a> {
118     tcx: TyCtxt<'a, 'tcx, 'tcx>,
119     index: &'a mut Index<'tcx>,
120     parent_stab: Option<&'tcx Stability>,
121     parent_depr: Option<DeprecationEntry>,
122     in_trait_impl: bool,
123 }
124
125 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
126     // Determine the stability for a node based on its attributes and inherited
127     // stability. The stability is recorded in the index and used as the parent.
128     fn annotate<F>(&mut self, id: NodeId, attrs: &[Attribute],
129                    item_sp: Span, kind: AnnotationKind, visit_children: F)
130         where F: FnOnce(&mut Self)
131     {
132         if self.tcx.features().staged_api {
133             // This crate explicitly wants staged API.
134             debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
135             if let Some(..) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) {
136                 self.tcx.sess.span_err(item_sp, "`#[deprecated]` cannot be used in staged api, \
137                                                  use `#[rustc_deprecated]` instead");
138             }
139             if let Some(mut stab) = attr::find_stability(&self.tcx.sess.parse_sess,
140                                                          attrs, item_sp) {
141                 // Error if prohibited, or can't inherit anything from a container
142                 if kind == AnnotationKind::Prohibited ||
143                    (kind == AnnotationKind::Container &&
144                     stab.level.is_stable() &&
145                     stab.rustc_depr.is_none()) {
146                     self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
147                 }
148
149                 debug!("annotate: found {:?}", stab);
150                 // If parent is deprecated and we're not, inherit this by merging
151                 // deprecated_since and its reason.
152                 if let Some(parent_stab) = self.parent_stab {
153                     if parent_stab.rustc_depr.is_some() && stab.rustc_depr.is_none() {
154                         stab.rustc_depr = parent_stab.rustc_depr.clone()
155                     }
156                 }
157
158                 let stab = self.tcx.intern_stability(stab);
159
160                 // Check if deprecated_since < stable_since. If it is,
161                 // this is *almost surely* an accident.
162                 if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
163                         &attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
164                     // Explicit version of iter::order::lt to handle parse errors properly
165                     for (dep_v, stab_v) in dep_since.as_str()
166                                                     .split('.')
167                                                     .zip(stab_since.as_str().split('.'))
168                     {
169                         if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
170                             match dep_v.cmp(&stab_v) {
171                                 Ordering::Less => {
172                                     self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
173                                                                      after it is deprecated");
174                                     break
175                                 }
176                                 Ordering::Equal => continue,
177                                 Ordering::Greater => break,
178                             }
179                         } else {
180                             // Act like it isn't less because the question is now nonsensical,
181                             // and this makes us not do anything else interesting.
182                             self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
183                                                              version found");
184                             break
185                         }
186                     }
187                 }
188
189                 let hir_id = self.tcx.hir().node_to_hir_id(id);
190                 self.index.stab_map.insert(hir_id, stab);
191
192                 let orig_parent_stab = replace(&mut self.parent_stab, Some(stab));
193                 visit_children(self);
194                 self.parent_stab = orig_parent_stab;
195             } else {
196                 debug!("annotate: not found, parent = {:?}", self.parent_stab);
197                 if let Some(stab) = self.parent_stab {
198                     if stab.level.is_unstable() {
199                         let hir_id = self.tcx.hir().node_to_hir_id(id);
200                         self.index.stab_map.insert(hir_id, stab);
201                     }
202                 }
203                 visit_children(self);
204             }
205         } else {
206             // Emit errors for non-staged-api crates.
207             for attr in attrs {
208                 let tag = attr.name();
209                 if tag == "unstable" || tag == "stable" || tag == "rustc_deprecated" {
210                     attr::mark_used(attr);
211                     self.tcx.sess.span_err(attr.span(), "stability attributes may not be used \
212                                                          outside of the standard library");
213                 }
214             }
215
216             // Propagate unstability.  This can happen even for non-staged-api crates in case
217             // -Zforce-unstable-if-unmarked is set.
218             if let Some(stab) = self.parent_stab {
219                 if stab.level.is_unstable() {
220                     let hir_id = self.tcx.hir().node_to_hir_id(id);
221                     self.index.stab_map.insert(hir_id, stab);
222                 }
223             }
224
225             if let Some(depr) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) {
226                 if kind == AnnotationKind::Prohibited {
227                     self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
228                 }
229
230                 // `Deprecation` is just two pointers, no need to intern it
231                 let hir_id = self.tcx.hir().node_to_hir_id(id);
232                 let depr_entry = DeprecationEntry::local(depr, hir_id);
233                 self.index.depr_map.insert(hir_id, depr_entry.clone());
234
235                 let orig_parent_depr = replace(&mut self.parent_depr,
236                                                Some(depr_entry));
237                 visit_children(self);
238                 self.parent_depr = orig_parent_depr;
239             } else if let Some(parent_depr) = self.parent_depr.clone() {
240                 let hir_id = self.tcx.hir().node_to_hir_id(id);
241                 self.index.depr_map.insert(hir_id, parent_depr);
242                 visit_children(self);
243             } else {
244                 visit_children(self);
245             }
246         }
247     }
248 }
249
250 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
251     /// Because stability levels are scoped lexically, we want to walk
252     /// nested items in the context of the outer item, so enable
253     /// deep-walking.
254     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
255         NestedVisitorMap::All(&self.tcx.hir())
256     }
257
258     fn visit_item(&mut self, i: &'tcx Item) {
259         let orig_in_trait_impl = self.in_trait_impl;
260         let mut kind = AnnotationKind::Required;
261         match i.node {
262             // Inherent impls and foreign modules serve only as containers for other items,
263             // they don't have their own stability. They still can be annotated as unstable
264             // and propagate this unstability to children, but this annotation is completely
265             // optional. They inherit stability from their parents when unannotated.
266             hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {
267                 self.in_trait_impl = false;
268                 kind = AnnotationKind::Container;
269             }
270             hir::ItemKind::Impl(.., Some(_), _, _) => {
271                 self.in_trait_impl = true;
272             }
273             hir::ItemKind::Struct(ref sd, _) => {
274                 if !sd.is_struct() {
275                     self.annotate(sd.id(), &i.attrs, i.span, AnnotationKind::Required, |_| {})
276                 }
277             }
278             _ => {}
279         }
280
281         self.annotate(i.id, &i.attrs, i.span, kind, |v| {
282             intravisit::walk_item(v, i)
283         });
284         self.in_trait_impl = orig_in_trait_impl;
285     }
286
287     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
288         self.annotate(ti.id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
289             intravisit::walk_trait_item(v, ti);
290         });
291     }
292
293     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
294         let kind = if self.in_trait_impl {
295             AnnotationKind::Prohibited
296         } else {
297             AnnotationKind::Required
298         };
299         self.annotate(ii.id, &ii.attrs, ii.span, kind, |v| {
300             intravisit::walk_impl_item(v, ii);
301         });
302     }
303
304     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
305         self.annotate(var.node.data.id(), &var.node.attrs, var.span, AnnotationKind::Required, |v| {
306             intravisit::walk_variant(v, var, g, item_id);
307         })
308     }
309
310     fn visit_struct_field(&mut self, s: &'tcx StructField) {
311         self.annotate(s.id, &s.attrs, s.span, AnnotationKind::Required, |v| {
312             intravisit::walk_struct_field(v, s);
313         });
314     }
315
316     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
317         self.annotate(i.id, &i.attrs, i.span, AnnotationKind::Required, |v| {
318             intravisit::walk_foreign_item(v, i);
319         });
320     }
321
322     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
323         self.annotate(md.id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
324     }
325 }
326
327 struct MissingStabilityAnnotations<'a, 'tcx: 'a> {
328     tcx: TyCtxt<'a, 'tcx, 'tcx>,
329     access_levels: &'a AccessLevels,
330 }
331
332 impl<'a, 'tcx: 'a> MissingStabilityAnnotations<'a, 'tcx> {
333     fn check_missing_stability(&self, id: NodeId, span: Span) {
334         let hir_id = self.tcx.hir().node_to_hir_id(id);
335         let stab = self.tcx.stability().local_stability(hir_id);
336         let is_error = !self.tcx.sess.opts.test &&
337                         stab.is_none() &&
338                         self.access_levels.is_reachable(id);
339         if is_error {
340             self.tcx.sess.span_err(span, "This node does not have a stability attribute");
341         }
342     }
343 }
344
345 impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> {
346     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
347         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
348     }
349
350     fn visit_item(&mut self, i: &'tcx Item) {
351         match i.node {
352             // Inherent impls and foreign modules serve only as containers for other items,
353             // they don't have their own stability. They still can be annotated as unstable
354             // and propagate this unstability to children, but this annotation is completely
355             // optional. They inherit stability from their parents when unannotated.
356             hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {}
357
358             _ => self.check_missing_stability(i.id, i.span)
359         }
360
361         intravisit::walk_item(self, i)
362     }
363
364     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
365         self.check_missing_stability(ti.id, ti.span);
366         intravisit::walk_trait_item(self, ti);
367     }
368
369     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
370         let impl_def_id = self.tcx.hir().local_def_id(self.tcx.hir().get_parent(ii.id));
371         if self.tcx.impl_trait_ref(impl_def_id).is_none() {
372             self.check_missing_stability(ii.id, ii.span);
373         }
374         intravisit::walk_impl_item(self, ii);
375     }
376
377     fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
378         self.check_missing_stability(var.node.data.id(), var.span);
379         intravisit::walk_variant(self, var, g, item_id);
380     }
381
382     fn visit_struct_field(&mut self, s: &'tcx StructField) {
383         self.check_missing_stability(s.id, s.span);
384         intravisit::walk_struct_field(self, s);
385     }
386
387     fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
388         self.check_missing_stability(i.id, i.span);
389         intravisit::walk_foreign_item(self, i);
390     }
391
392     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
393         self.check_missing_stability(md.id, md.span);
394     }
395 }
396
397 impl<'a, 'tcx> Index<'tcx> {
398     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Index<'tcx> {
399         let is_staged_api =
400             tcx.sess.opts.debugging_opts.force_unstable_if_unmarked ||
401             tcx.features().staged_api;
402         let mut staged_api = FxHashMap::default();
403         staged_api.insert(LOCAL_CRATE, is_staged_api);
404         let mut index = Index {
405             staged_api,
406             stab_map: Default::default(),
407             depr_map: Default::default(),
408             active_features: Default::default(),
409         };
410
411         let ref active_lib_features = tcx.features().declared_lib_features;
412
413         // Put the active features into a map for quick lookup
414         index.active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
415
416         {
417             let krate = tcx.hir().krate();
418             let mut annotator = Annotator {
419                 tcx,
420                 index: &mut index,
421                 parent_stab: None,
422                 parent_depr: None,
423                 in_trait_impl: false,
424             };
425
426             // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
427             // a parent stability annotation which indicates that this is private
428             // with the `rustc_private` feature. This is intended for use when
429             // compiling librustc crates themselves so we can leverage crates.io
430             // while maintaining the invariant that all sysroot crates are unstable
431             // by default and are unable to be used.
432             if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
433                 let reason = "this crate is being loaded from the sysroot, an \
434                               unstable location; did you mean to load this crate \
435                               from crates.io via `Cargo.toml` instead?";
436                 let stability = tcx.intern_stability(Stability {
437                     level: attr::StabilityLevel::Unstable {
438                         reason: Some(Symbol::intern(reason)),
439                         issue: 27812,
440                     },
441                     feature: Symbol::intern("rustc_private"),
442                     rustc_depr: None,
443                     const_stability: None,
444                     promotable: false,
445                 });
446                 annotator.parent_stab = Some(stability);
447             }
448
449             annotator.annotate(ast::CRATE_NODE_ID,
450                                &krate.attrs,
451                                krate.span,
452                                AnnotationKind::Required,
453                                |v| intravisit::walk_crate(v, krate));
454         }
455         return index
456     }
457
458     pub fn local_stability(&self, id: HirId) -> Option<&'tcx Stability> {
459         self.stab_map.get(&id).cloned()
460     }
461
462     pub fn local_deprecation_entry(&self, id: HirId) -> Option<DeprecationEntry> {
463         self.depr_map.get(&id).cloned()
464     }
465 }
466
467 /// Cross-references the feature names of unstable APIs with enabled
468 /// features and possibly prints errors.
469 pub fn check_unstable_api_usage<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
470     let mut checker = Checker { tcx };
471     tcx.hir().krate().visit_all_item_likes(&mut checker.as_deep_visitor());
472 }
473
474 /// Check whether an item marked with `deprecated(since="X")` is currently
475 /// deprecated (i.e., whether X is not greater than the current rustc version).
476 pub fn deprecation_in_effect(since: &str) -> bool {
477     fn parse_version(ver: &str) -> Vec<u32> {
478         // We ignore non-integer components of the version (e.g., "nightly").
479         ver.split(|c| c == '.' || c == '-').flat_map(|s| s.parse()).collect()
480     }
481
482     if let Some(rustc) = option_env!("CFG_RELEASE") {
483         let since: Vec<u32> = parse_version(since);
484         let rustc: Vec<u32> = parse_version(rustc);
485         // We simply treat invalid `since` attributes as relating to a previous
486         // Rust version, thus always displaying the warning.
487         if since.len() != 3 {
488             return true;
489         }
490         since <= rustc
491     } else {
492         // By default, a deprecation warning applies to
493         // the current version of the compiler.
494         true
495     }
496 }
497
498 struct Checker<'a, 'tcx: 'a> {
499     tcx: TyCtxt<'a, 'tcx, 'tcx>,
500 }
501
502 /// Result of `TyCtxt::eval_stability`.
503 pub enum EvalResult {
504     /// We can use the item because it is stable or we provided the
505     /// corresponding feature gate.
506     Allow,
507     /// We cannot use the item because it is unstable and we did not provide the
508     /// corresponding feature gate.
509     Deny {
510         feature: Symbol,
511         reason: Option<Symbol>,
512         issue: u32,
513     },
514     /// The item does not have the `#[stable]` or `#[unstable]` marker assigned.
515     Unmarked,
516 }
517
518 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
519     // See issue #38412.
520     fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
521         // Check if `def_id` is a trait method.
522         match self.describe_def(def_id) {
523             Some(Def::Method(_)) |
524             Some(Def::AssociatedTy(_)) |
525             Some(Def::AssociatedConst(_)) => {
526                 if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container {
527                     // Trait methods do not declare visibility (even
528                     // for visibility info in cstore). Use containing
529                     // trait instead, so methods of `pub` traits are
530                     // themselves considered `pub`.
531                     def_id = trait_def_id;
532                 }
533             }
534             _ => {}
535         }
536
537         let visibility = self.visibility(def_id);
538
539         match visibility {
540             // Must check stability for `pub` items.
541             ty::Visibility::Public => false,
542
543             // These are not visible outside crate; therefore
544             // stability markers are irrelevant, if even present.
545             ty::Visibility::Restricted(..) |
546             ty::Visibility::Invisible => true,
547         }
548     }
549
550     /// Evaluates the stability of an item.
551     ///
552     /// Returns `EvalResult::Allow` if the item is stable, or unstable but the corresponding
553     /// `#![feature]` has been provided. Returns `EvalResult::Deny` which describes the offending
554     /// unstable feature otherwise.
555     ///
556     /// If `id` is `Some(_)`, this function will also check if the item at `def_id` has been
557     /// deprecated. If the item is indeed deprecated, we will emit a deprecation lint attached to
558     /// `id`.
559     pub fn eval_stability(self, def_id: DefId, id: Option<NodeId>, span: Span) -> EvalResult {
560         if span.allows_unstable() {
561             debug!("stability: skipping span={:?} since it is internal", span);
562             return EvalResult::Allow;
563         }
564
565         let lint_deprecated = |def_id: DefId, id: NodeId, note: Option<Symbol>| {
566             let path = self.item_path_str(def_id);
567
568             let msg = if let Some(note) = note {
569                 format!("use of deprecated item '{}': {}", path, note)
570             } else {
571                 format!("use of deprecated item '{}'", path)
572             };
573
574             self.lint_node(lint::builtin::DEPRECATED, id, span, &msg);
575             if id == ast::DUMMY_NODE_ID {
576                 span_bug!(span, "emitted a deprecated lint with dummy node id: {:?}", def_id);
577             }
578         };
579
580         // Deprecated attributes apply in-crate and cross-crate.
581         if let Some(id) = id {
582             if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
583                 // If the deprecation is scheduled for a future Rust
584                 // version, then we should display no warning message.
585                 let deprecated_in_future_version = if let Some(sym) = depr_entry.attr.since {
586                     let since = sym.as_str();
587                     !deprecation_in_effect(&since)
588                 } else {
589                     false
590                 };
591
592                 let parent_def_id = self.hir().local_def_id(self.hir().get_parent(id));
593                 let skip = deprecated_in_future_version ||
594                            self.lookup_deprecation_entry(parent_def_id)
595                                .map_or(false, |parent_depr| parent_depr.same_origin(&depr_entry));
596                 if !skip {
597                     lint_deprecated(def_id, id, depr_entry.attr.note);
598                 }
599             };
600         }
601
602         let is_staged_api = self.lookup_stability(DefId {
603             index: CRATE_DEF_INDEX,
604             ..def_id
605         }).is_some();
606         if !is_staged_api {
607             return EvalResult::Allow;
608         }
609
610         let stability = self.lookup_stability(def_id);
611         debug!("stability: \
612                 inspecting def_id={:?} span={:?} of stability={:?}", def_id, span, stability);
613
614         if let Some(&Stability{rustc_depr: Some(attr::RustcDeprecation { reason, since }), ..})
615                 = stability {
616             if let Some(id) = id {
617                 if deprecation_in_effect(&since.as_str()) {
618                     lint_deprecated(def_id, id, Some(reason));
619                 }
620             }
621         }
622
623         // Only the cross-crate scenario matters when checking unstable APIs
624         let cross_crate = !def_id.is_local();
625         if !cross_crate {
626             return EvalResult::Allow;
627         }
628
629         // Issue #38412: private items lack stability markers.
630         if self.skip_stability_check_due_to_privacy(def_id) {
631             return EvalResult::Allow;
632         }
633
634         match stability {
635             Some(&Stability { level: attr::Unstable { reason, issue }, feature, .. }) => {
636                 if self.stability().active_features.contains(&feature) {
637                     return EvalResult::Allow;
638                 }
639
640                 // When we're compiling the compiler itself we may pull in
641                 // crates from crates.io, but those crates may depend on other
642                 // crates also pulled in from crates.io. We want to ideally be
643                 // able to compile everything without requiring upstream
644                 // modifications, so in the case that this looks like a
645                 // `rustc_private` crate (e.g., a compiler crate) and we also have
646                 // the `-Z force-unstable-if-unmarked` flag present (we're
647                 // compiling a compiler crate), then let this missing feature
648                 // annotation slide.
649                 if feature == "rustc_private" && issue == 27812 {
650                     if self.sess.opts.debugging_opts.force_unstable_if_unmarked {
651                         return EvalResult::Allow;
652                     }
653                 }
654
655                 EvalResult::Deny { feature, reason, issue }
656             }
657             Some(_) => {
658                 // Stable APIs are always ok to call and deprecated APIs are
659                 // handled by the lint emitting logic above.
660                 EvalResult::Allow
661             }
662             None => {
663                 EvalResult::Unmarked
664             }
665         }
666     }
667
668     /// Checks if an item is stable or error out.
669     ///
670     /// If the item defined by `def_id` is unstable and the corresponding `#![feature]` does not
671     /// exist, emits an error.
672     ///
673     /// Additionally, this function will also check if the item is deprecated. If so, and `id` is
674     /// not `None`, a deprecated lint attached to `id` will be emitted.
675     pub fn check_stability(self, def_id: DefId, id: Option<NodeId>, span: Span) {
676         match self.eval_stability(def_id, id, span) {
677             EvalResult::Allow => {}
678             EvalResult::Deny { feature, reason, issue } => {
679                 let msg = match reason {
680                     Some(r) => format!("use of unstable library feature '{}': {}", feature, r),
681                     None => format!("use of unstable library feature '{}'", &feature)
682                 };
683
684                 let msp: MultiSpan = span.into();
685                 let cm = &self.sess.parse_sess.source_map();
686                 let span_key = msp.primary_span().and_then(|sp: Span|
687                     if !sp.is_dummy() {
688                         let file = cm.lookup_char_pos(sp.lo()).file;
689                         if file.name.is_macros() {
690                             None
691                         } else {
692                             Some(span)
693                         }
694                     } else {
695                         None
696                     }
697                 );
698
699                 let error_id = (DiagnosticMessageId::StabilityId(issue), span_key, msg.clone());
700                 let fresh = self.sess.one_time_diagnostics.borrow_mut().insert(error_id);
701                 if fresh {
702                     emit_feature_err(&self.sess.parse_sess, &feature.as_str(), span,
703                                      GateIssue::Library(Some(issue)), &msg);
704                 }
705             }
706             EvalResult::Unmarked => {
707                 span_bug!(span, "encountered unmarked API: {:?}", def_id);
708             }
709         }
710     }
711 }
712
713 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
714     /// Because stability levels are scoped lexically, we want to walk
715     /// nested items in the context of the outer item, so enable
716     /// deep-walking.
717     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
718         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
719     }
720
721     fn visit_item(&mut self, item: &'tcx hir::Item) {
722         match item.node {
723             hir::ItemKind::ExternCrate(_) => {
724                 // compiler-generated `extern crate` items have a dummy span.
725                 if item.span.is_dummy() { return }
726
727                 let def_id = self.tcx.hir().local_def_id(item.id);
728                 let cnum = match self.tcx.extern_mod_stmt_cnum(def_id) {
729                     Some(cnum) => cnum,
730                     None => return,
731                 };
732                 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
733                 self.tcx.check_stability(def_id, Some(item.id), item.span);
734             }
735
736             // For implementations of traits, check the stability of each item
737             // individually as it's possible to have a stable trait with unstable
738             // items.
739             hir::ItemKind::Impl(.., Some(ref t), _, ref impl_item_refs) => {
740                 if let Def::Trait(trait_did) = t.path.def {
741                     for impl_item_ref in impl_item_refs {
742                         let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
743                         let trait_item_def_id = self.tcx.associated_items(trait_did)
744                             .find(|item| item.ident.name == impl_item.ident.name)
745                             .map(|item| item.def_id);
746                         if let Some(def_id) = trait_item_def_id {
747                             // Pass `None` to skip deprecation warnings.
748                             self.tcx.check_stability(def_id, None, impl_item.span);
749                         }
750                     }
751                 }
752             }
753
754             // There's no good place to insert stability check for non-Copy unions,
755             // so semi-randomly perform it here in stability.rs
756             hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
757                 let def_id = self.tcx.hir().local_def_id(item.id);
758                 let adt_def = self.tcx.adt_def(def_id);
759                 let ty = self.tcx.type_of(def_id);
760
761                 if adt_def.has_dtor(self.tcx) {
762                     emit_feature_err(&self.tcx.sess.parse_sess,
763                                      "untagged_unions", item.span, GateIssue::Language,
764                                      "unions with `Drop` implementations are unstable");
765                 } else {
766                     let param_env = self.tcx.param_env(def_id);
767                     if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() {
768                         emit_feature_err(&self.tcx.sess.parse_sess,
769                                          "untagged_unions", item.span, GateIssue::Language,
770                                          "unions with non-`Copy` fields are unstable");
771                     }
772                 }
773             }
774
775             _ => (/* pass */)
776         }
777         intravisit::walk_item(self, item);
778     }
779
780     fn visit_path(&mut self, path: &'tcx hir::Path, id: hir::HirId) {
781         let id = self.tcx.hir().hir_to_node_id(id);
782         if let Some(def_id) = path.def.opt_def_id() {
783             self.tcx.check_stability(def_id, Some(id), path.span)
784         }
785         intravisit::walk_path(self, path)
786     }
787 }
788
789 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
790     pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
791         self.lookup_deprecation_entry(id).map(|depr| depr.attr)
792     }
793 }
794
795 /// Given the list of enabled features that were not language features (i.e., that
796 /// were expected to be library features), and the list of features used from
797 /// libraries, identify activated features that don't exist and error about them.
798 pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
799     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
800
801     if tcx.stability().staged_api[&LOCAL_CRATE] {
802         let krate = tcx.hir().krate();
803         let mut missing = MissingStabilityAnnotations {
804             tcx,
805             access_levels,
806         };
807         missing.check_missing_stability(ast::CRATE_NODE_ID, krate.span);
808         intravisit::walk_crate(&mut missing, krate);
809         krate.visit_all_item_likes(&mut missing.as_deep_visitor());
810     }
811
812     let declared_lang_features = &tcx.features().declared_lang_features;
813     let mut lang_features = FxHashSet::default();
814     for &(feature, span, since) in declared_lang_features {
815         if let Some(since) = since {
816             // Warn if the user has enabled an already-stable lang feature.
817             unnecessary_stable_feature_lint(tcx, span, feature, since);
818         }
819         if lang_features.contains(&feature) {
820             // Warn if the user enables a lang feature multiple times.
821             duplicate_feature_err(tcx.sess, span, feature);
822         }
823         lang_features.insert(feature);
824     }
825
826     let declared_lib_features = &tcx.features().declared_lib_features;
827     let mut remaining_lib_features = FxHashMap::default();
828     for (feature, span) in declared_lib_features {
829         if remaining_lib_features.contains_key(&feature) {
830             // Warn if the user enables a lib feature multiple times.
831             duplicate_feature_err(tcx.sess, *span, *feature);
832         }
833         remaining_lib_features.insert(feature, span.clone());
834     }
835     // `stdbuild` has special handling for `libc`, so we need to
836     // recognise the feature when building std.
837     // Likewise, libtest is handled specially, so `test` isn't
838     // available as we'd like it to be.
839     // FIXME: only remove `libc` when `stdbuild` is active.
840     // FIXME: remove special casing for `test`.
841     remaining_lib_features.remove(&Symbol::intern("libc"));
842     remaining_lib_features.remove(&Symbol::intern("test"));
843
844     let check_features =
845         |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &Vec<_>| {
846             for &(feature, since) in defined_features {
847                 if let Some(since) = since {
848                     if let Some(span) = remaining_lib_features.get(&feature) {
849                         // Warn if the user has enabled an already-stable lib feature.
850                         unnecessary_stable_feature_lint(tcx, *span, feature, since);
851                     }
852                 }
853                 remaining_lib_features.remove(&feature);
854                 if remaining_lib_features.is_empty() {
855                     break;
856                 }
857             }
858         };
859
860     // We always collect the lib features declared in the current crate, even if there are
861     // no unknown features, because the collection also does feature attribute validation.
862     let local_defined_features = tcx.lib_features().to_vec();
863     if !remaining_lib_features.is_empty() {
864         check_features(&mut remaining_lib_features, &local_defined_features);
865
866         for &cnum in &*tcx.crates() {
867             if remaining_lib_features.is_empty() {
868                 break;
869             }
870             check_features(&mut remaining_lib_features, &tcx.defined_lib_features(cnum));
871         }
872     }
873
874     for (feature, span) in remaining_lib_features {
875         struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
876     }
877
878     // FIXME(#44232): the `used_features` table no longer exists, so we
879     // don't lint about unused features. We should reenable this one day!
880 }
881
882 fn unnecessary_stable_feature_lint<'a, 'tcx>(
883     tcx: TyCtxt<'a, 'tcx, 'tcx>,
884     span: Span,
885     feature: Symbol,
886     since: Symbol
887 ) {
888     tcx.lint_node(lint::builtin::STABLE_FEATURES,
889         ast::CRATE_NODE_ID,
890         span,
891         &format!("the feature `{}` has been stable since {} and no longer requires \
892                   an attribute to enable", feature, since));
893 }
894
895 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
896     struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
897         .emit();
898 }