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