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