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