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