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