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