1 //! A pass that annotates every item and method with its stability level,
2 //! propagating default levels lexically from parent to children ast nodes.
4 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
6 use rustc::middle::privacy::AccessLevels;
7 use rustc::middle::stability::{DeprecationEntry, Index};
8 use rustc::session::Session;
9 use rustc::ty::query::Providers;
10 use rustc::ty::TyCtxt;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_hir::def::{DefKind, Res};
14 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
15 use rustc_hir::{Generics, HirId, Item, StructField, Variant};
16 use rustc_span::symbol::{sym, Symbol};
18 use syntax::ast::Attribute;
19 use syntax::attr::{self, Stability};
20 use syntax::feature_gate::feature_err;
22 use std::cmp::Ordering;
23 use std::mem::replace;
24 use std::num::NonZeroU32;
26 use rustc_error_codes::*;
30 // Annotation is required if not inherited from unstable parents
32 // Annotation is useless, reject it
34 // Annotation itself is useless, but it can be propagated to children
38 // A private tree-walker for producing an Index.
39 struct Annotator<'a, 'tcx> {
41 index: &'a mut Index<'tcx>,
42 parent_stab: Option<&'tcx Stability>,
43 parent_depr: Option<DeprecationEntry>,
47 impl<'a, 'tcx> Annotator<'a, 'tcx> {
48 // Determine the stability for a node based on its attributes and inherited
49 // stability. The stability is recorded in the index and used as the parent.
60 if self.tcx.features().staged_api {
61 // This crate explicitly wants staged API.
62 debug!("annotate(id = {:?}, attrs = {:?})", hir_id, attrs);
63 if let Some(..) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) {
64 self.tcx.sess.span_err(
66 "`#[deprecated]` cannot be used in staged API; \
67 use `#[rustc_deprecated]` instead",
70 let (stab, const_stab) =
71 attr::find_stability(&self.tcx.sess.parse_sess, attrs, item_sp);
72 if let Some(const_stab) = const_stab {
73 let const_stab = self.tcx.intern_const_stability(const_stab);
74 self.index.const_stab_map.insert(hir_id, const_stab);
76 if let Some(mut stab) = stab {
77 // Error if prohibited, or can't inherit anything from a container.
78 if kind == AnnotationKind::Prohibited
79 || (kind == AnnotationKind::Container
80 && stab.level.is_stable()
81 && stab.rustc_depr.is_none())
83 self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
86 debug!("annotate: found {:?}", stab);
87 // If parent is deprecated and we're not, inherit this by merging
88 // deprecated_since and its reason.
89 if let Some(parent_stab) = self.parent_stab {
90 if parent_stab.rustc_depr.is_some() && stab.rustc_depr.is_none() {
91 stab.rustc_depr = parent_stab.rustc_depr.clone()
95 let stab = self.tcx.intern_stability(stab);
97 // Check if deprecated_since < stable_since. If it is,
98 // this is *almost surely* an accident.
100 &Some(attr::RustcDeprecation { since: dep_since, .. }),
101 &attr::Stable { since: stab_since },
102 ) = (&stab.rustc_depr, &stab.level)
104 // Explicit version of iter::order::lt to handle parse errors properly
105 for (dep_v, stab_v) in
106 dep_since.as_str().split('.').zip(stab_since.as_str().split('.'))
108 if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
109 match dep_v.cmp(&stab_v) {
111 self.tcx.sess.span_err(
113 "An API can't be stabilized \
114 after it is deprecated",
118 Ordering::Equal => continue,
119 Ordering::Greater => break,
122 // Act like it isn't less because the question is now nonsensical,
123 // and this makes us not do anything else interesting.
124 self.tcx.sess.span_err(
126 "Invalid stability or deprecation \
134 self.index.stab_map.insert(hir_id, stab);
136 let orig_parent_stab = replace(&mut self.parent_stab, Some(stab));
137 visit_children(self);
138 self.parent_stab = orig_parent_stab;
140 debug!("annotate: not found, parent = {:?}", self.parent_stab);
141 if let Some(stab) = self.parent_stab {
142 if stab.level.is_unstable() {
143 self.index.stab_map.insert(hir_id, stab);
146 visit_children(self);
149 // Emit errors for non-staged-api crates.
150 let unstable_attrs = [
153 sym::rustc_deprecated,
154 sym::rustc_const_unstable,
155 sym::rustc_const_stable,
158 let name = attr.name_or_empty();
159 if unstable_attrs.contains(&name) {
160 attr::mark_used(attr);
165 "stability attributes may not be used outside of the standard library",
171 // Propagate unstability. This can happen even for non-staged-api crates in case
172 // -Zforce-unstable-if-unmarked is set.
173 if let Some(stab) = self.parent_stab {
174 if stab.level.is_unstable() {
175 self.index.stab_map.insert(hir_id, stab);
179 if let Some(depr) = attr::find_deprecation(&self.tcx.sess.parse_sess, attrs, item_sp) {
180 if kind == AnnotationKind::Prohibited {
181 self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
184 // `Deprecation` is just two pointers, no need to intern it
185 let depr_entry = DeprecationEntry::local(depr, hir_id);
186 self.index.depr_map.insert(hir_id, depr_entry.clone());
188 let orig_parent_depr = replace(&mut self.parent_depr, Some(depr_entry));
189 visit_children(self);
190 self.parent_depr = orig_parent_depr;
191 } else if let Some(parent_depr) = self.parent_depr.clone() {
192 self.index.depr_map.insert(hir_id, parent_depr);
193 visit_children(self);
195 visit_children(self);
201 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
202 /// Because stability levels are scoped lexically, we want to walk
203 /// nested items in the context of the outer item, so enable
205 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
206 NestedVisitorMap::All(&self.tcx.hir())
209 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
210 let orig_in_trait_impl = self.in_trait_impl;
211 let mut kind = AnnotationKind::Required;
213 // Inherent impls and foreign modules serve only as containers for other items,
214 // they don't have their own stability. They still can be annotated as unstable
215 // and propagate this unstability to children, but this annotation is completely
216 // optional. They inherit stability from their parents when unannotated.
217 hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {
218 self.in_trait_impl = false;
219 kind = AnnotationKind::Container;
221 hir::ItemKind::Impl(.., Some(_), _, _) => {
222 self.in_trait_impl = true;
224 hir::ItemKind::Struct(ref sd, _) => {
225 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
226 self.annotate(ctor_hir_id, &i.attrs, i.span, AnnotationKind::Required, |_| {})
232 self.annotate(i.hir_id, &i.attrs, i.span, kind, |v| intravisit::walk_item(v, i));
233 self.in_trait_impl = orig_in_trait_impl;
236 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
237 self.annotate(ti.hir_id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
238 intravisit::walk_trait_item(v, ti);
242 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
244 if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
245 self.annotate(ii.hir_id, &ii.attrs, ii.span, kind, |v| {
246 intravisit::walk_impl_item(v, ii);
250 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
251 self.annotate(var.id, &var.attrs, var.span, AnnotationKind::Required, |v| {
252 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
253 v.annotate(ctor_hir_id, &var.attrs, var.span, AnnotationKind::Required, |_| {});
256 intravisit::walk_variant(v, var, g, item_id)
260 fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) {
261 self.annotate(s.hir_id, &s.attrs, s.span, AnnotationKind::Required, |v| {
262 intravisit::walk_struct_field(v, s);
266 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
267 self.annotate(i.hir_id, &i.attrs, i.span, AnnotationKind::Required, |v| {
268 intravisit::walk_foreign_item(v, i);
272 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
273 self.annotate(md.hir_id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
277 struct MissingStabilityAnnotations<'a, 'tcx> {
279 access_levels: &'a AccessLevels,
282 impl<'a, 'tcx> MissingStabilityAnnotations<'a, 'tcx> {
283 fn check_missing_stability(&self, hir_id: HirId, span: Span, name: &str) {
284 let stab = self.tcx.stability().local_stability(hir_id);
286 !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(hir_id);
288 self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", name));
293 impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> {
294 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
295 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
298 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
300 // Inherent impls and foreign modules serve only as containers for other items,
301 // they don't have their own stability. They still can be annotated as unstable
302 // and propagate this unstability to children, but this annotation is completely
303 // optional. They inherit stability from their parents when unannotated.
304 hir::ItemKind::Impl(.., None, _, _) | hir::ItemKind::ForeignMod(..) => {}
306 _ => self.check_missing_stability(i.hir_id, i.span, i.kind.descriptive_variant()),
309 intravisit::walk_item(self, i)
312 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
313 self.check_missing_stability(ti.hir_id, ti.span, "item");
314 intravisit::walk_trait_item(self, ti);
317 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
318 let impl_def_id = self.tcx.hir().local_def_id(self.tcx.hir().get_parent_item(ii.hir_id));
319 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
320 self.check_missing_stability(ii.hir_id, ii.span, "item");
322 intravisit::walk_impl_item(self, ii);
325 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
326 self.check_missing_stability(var.id, var.span, "variant");
327 intravisit::walk_variant(self, var, g, item_id);
330 fn visit_struct_field(&mut self, s: &'tcx StructField<'tcx>) {
331 self.check_missing_stability(s.hir_id, s.span, "field");
332 intravisit::walk_struct_field(self, s);
335 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
336 self.check_missing_stability(i.hir_id, i.span, i.kind.descriptive_variant());
337 intravisit::walk_foreign_item(self, i);
340 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
341 self.check_missing_stability(md.hir_id, md.span, "macro");
345 fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> {
347 tcx.sess.opts.debugging_opts.force_unstable_if_unmarked || tcx.features().staged_api;
348 let mut staged_api = FxHashMap::default();
349 staged_api.insert(LOCAL_CRATE, is_staged_api);
350 let mut index = Index {
352 stab_map: Default::default(),
353 const_stab_map: Default::default(),
354 depr_map: Default::default(),
355 active_features: Default::default(),
358 let active_lib_features = &tcx.features().declared_lib_features;
359 let active_lang_features = &tcx.features().declared_lang_features;
361 // Put the active features into a map for quick lookup.
362 index.active_features = active_lib_features
364 .map(|&(ref s, ..)| s.clone())
365 .chain(active_lang_features.iter().map(|&(ref s, ..)| s.clone()))
369 let krate = tcx.hir().krate();
370 let mut annotator = Annotator {
375 in_trait_impl: false,
378 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
379 // a parent stability annotation which indicates that this is private
380 // with the `rustc_private` feature. This is intended for use when
381 // compiling librustc crates themselves so we can leverage crates.io
382 // while maintaining the invariant that all sysroot crates are unstable
383 // by default and are unable to be used.
384 if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
385 let reason = "this crate is being loaded from the sysroot, an \
386 unstable location; did you mean to load this crate \
387 from crates.io via `Cargo.toml` instead?";
388 let stability = tcx.intern_stability(Stability {
389 level: attr::StabilityLevel::Unstable {
390 reason: Some(Symbol::intern(reason)),
391 issue: NonZeroU32::new(27812),
394 feature: sym::rustc_private,
397 annotator.parent_stab = Some(stability);
404 AnnotationKind::Required,
405 |v| intravisit::walk_crate(v, krate),
411 /// Cross-references the feature names of unstable APIs with enabled
412 /// features and possibly prints errors.
413 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: DefId) {
414 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
417 pub(crate) fn provide(providers: &mut Providers<'_>) {
418 *providers = Providers { check_mod_unstable_api_usage, ..*providers };
419 providers.stability_index = |tcx, cnum| {
420 assert_eq!(cnum, LOCAL_CRATE);
421 tcx.arena.alloc(new_index(tcx))
425 struct Checker<'tcx> {
429 impl Visitor<'tcx> for Checker<'tcx> {
430 /// Because stability levels are scoped lexically, we want to walk
431 /// nested items in the context of the outer item, so enable
433 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
434 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
437 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
439 hir::ItemKind::ExternCrate(_) => {
440 // compiler-generated `extern crate` items have a dummy span.
441 if item.span.is_dummy() {
445 let def_id = self.tcx.hir().local_def_id(item.hir_id);
446 let cnum = match self.tcx.extern_mod_stmt_cnum(def_id) {
450 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
451 self.tcx.check_stability(def_id, Some(item.hir_id), item.span);
454 // For implementations of traits, check the stability of each item
455 // individually as it's possible to have a stable trait with unstable
457 hir::ItemKind::Impl(.., Some(ref t), _, impl_item_refs) => {
458 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
459 for impl_item_ref in impl_item_refs {
460 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
461 let trait_item_def_id = self
463 .associated_items(trait_did)
464 .find(|item| item.ident.name == impl_item.ident.name)
465 .map(|item| item.def_id);
466 if let Some(def_id) = trait_item_def_id {
467 // Pass `None` to skip deprecation warnings.
468 self.tcx.check_stability(def_id, None, impl_item.span);
474 // There's no good place to insert stability check for non-Copy unions,
475 // so semi-randomly perform it here in stability.rs
476 hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
477 let def_id = self.tcx.hir().local_def_id(item.hir_id);
478 let adt_def = self.tcx.adt_def(def_id);
479 let ty = self.tcx.type_of(def_id);
481 if adt_def.has_dtor(self.tcx) {
483 &self.tcx.sess.parse_sess,
484 sym::untagged_unions,
486 "unions with `Drop` implementations are unstable",
490 let param_env = self.tcx.param_env(def_id);
491 if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() {
493 &self.tcx.sess.parse_sess,
494 sym::untagged_unions,
496 "unions with non-`Copy` fields are unstable",
505 intravisit::walk_item(self, item);
508 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
509 if let Some(def_id) = path.res.opt_def_id() {
510 self.tcx.check_stability(def_id, Some(id), path.span)
512 intravisit::walk_path(self, path)
516 /// Given the list of enabled features that were not language features (i.e., that
517 /// were expected to be library features), and the list of features used from
518 /// libraries, identify activated features that don't exist and error about them.
519 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
520 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
522 if tcx.stability().staged_api[&LOCAL_CRATE] {
523 let krate = tcx.hir().krate();
524 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
525 missing.check_missing_stability(hir::CRATE_HIR_ID, krate.span, "crate");
526 intravisit::walk_crate(&mut missing, krate);
527 krate.visit_all_item_likes(&mut missing.as_deep_visitor());
530 let declared_lang_features = &tcx.features().declared_lang_features;
531 let mut lang_features = FxHashSet::default();
532 for &(feature, span, since) in declared_lang_features {
533 if let Some(since) = since {
534 // Warn if the user has enabled an already-stable lang feature.
535 unnecessary_stable_feature_lint(tcx, span, feature, since);
537 if !lang_features.insert(feature) {
538 // Warn if the user enables a lang feature multiple times.
539 duplicate_feature_err(tcx.sess, span, feature);
543 let declared_lib_features = &tcx.features().declared_lib_features;
544 let mut remaining_lib_features = FxHashMap::default();
545 for (feature, span) in declared_lib_features {
546 if remaining_lib_features.contains_key(&feature) {
547 // Warn if the user enables a lib feature multiple times.
548 duplicate_feature_err(tcx.sess, *span, *feature);
550 remaining_lib_features.insert(feature, span.clone());
552 // `stdbuild` has special handling for `libc`, so we need to
553 // recognise the feature when building std.
554 // Likewise, libtest is handled specially, so `test` isn't
555 // available as we'd like it to be.
556 // FIXME: only remove `libc` when `stdbuild` is active.
557 // FIXME: remove special casing for `test`.
558 remaining_lib_features.remove(&Symbol::intern("libc"));
559 remaining_lib_features.remove(&sym::test);
561 let check_features = |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &[_]| {
562 for &(feature, since) in defined_features {
563 if let Some(since) = since {
564 if let Some(span) = remaining_lib_features.get(&feature) {
565 // Warn if the user has enabled an already-stable lib feature.
566 unnecessary_stable_feature_lint(tcx, *span, feature, since);
569 remaining_lib_features.remove(&feature);
570 if remaining_lib_features.is_empty() {
576 // We always collect the lib features declared in the current crate, even if there are
577 // no unknown features, because the collection also does feature attribute validation.
578 let local_defined_features = tcx.lib_features().to_vec();
579 if !remaining_lib_features.is_empty() {
580 check_features(&mut remaining_lib_features, &local_defined_features);
582 for &cnum in &*tcx.crates() {
583 if remaining_lib_features.is_empty() {
586 check_features(&mut remaining_lib_features, tcx.defined_lib_features(cnum));
590 for (feature, span) in remaining_lib_features {
591 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
594 // FIXME(#44232): the `used_features` table no longer exists, so we
595 // don't lint about unused features. We should reenable this one day!
598 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
600 lint::builtin::STABLE_FEATURES,
604 "the feature `{}` has been stable since {} and no longer requires \
605 an attribute to enable",
611 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
612 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)