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