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