1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A pass that annotates every item and method with its stability level,
12 //! propagating default levels lexically from parent to children ast nodes.
14 pub use self::StabilityLevel::*;
16 use hir::map as hir_map;
19 use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, DefIndex, LOCAL_CRATE};
20 use ty::{self, TyCtxt};
21 use middle::privacy::AccessLevels;
22 use syntax::symbol::Symbol;
23 use syntax_pos::{Span, DUMMY_SP};
25 use syntax::ast::{NodeId, Attribute};
26 use syntax::feature_gate::{GateIssue, emit_feature_err, find_lang_feature_accepted_version};
27 use syntax::attr::{self, Stability, Deprecation};
28 use util::nodemap::{DefIdMap, FxHashSet, FxHashMap};
31 use hir::{Item, Generics, StructField, Variant};
32 use hir::intravisit::{self, Visitor, NestedVisitorMap};
34 use std::mem::replace;
35 use std::cmp::Ordering;
37 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
38 pub enum StabilityLevel {
44 pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
45 if level.is_stable() { Stable } else { Unstable }
51 // Annotation is required if not inherited from unstable parents
53 // Annotation is useless, reject it
55 // Annotation itself is useless, but it can be propagated to children
59 /// An entry in the `depr_map`.
61 pub struct DeprecationEntry {
62 /// The metadata of the attribute associated with this entry.
63 pub attr: Deprecation,
64 /// The def id where the attr was originally attached. `None` for non-local
66 origin: Option<DefIndex>,
69 impl DeprecationEntry {
70 fn local(attr: Deprecation, id: DefId) -> DeprecationEntry {
71 assert!(id.is_local());
74 origin: Some(id.index),
78 fn external(attr: Deprecation) -> DeprecationEntry {
85 pub fn same_origin(&self, other: &DeprecationEntry) -> bool {
86 match (self.origin, other.origin) {
87 (Some(o1), Some(o2)) => o1 == o2,
93 /// A stability index, giving the stability level for items and methods.
94 pub struct Index<'tcx> {
95 /// This is mostly a cache, except the stabilities of local items
96 /// are filled by the annotator.
97 stab_map: DefIdMap<Option<&'tcx Stability>>,
98 depr_map: DefIdMap<Option<DeprecationEntry>>,
100 /// Maps for each crate whether it is part of the staged API.
101 staged_api: FxHashMap<CrateNum, bool>,
103 /// Features enabled for this crate.
104 active_features: FxHashSet<Symbol>,
106 /// Features used by this crate. Updated before and during typeck.
107 used_features: FxHashMap<Symbol, attr::StabilityLevel>
110 // A private tree-walker for producing an Index.
111 struct Annotator<'a, 'tcx: 'a> {
112 tcx: TyCtxt<'a, 'tcx, 'tcx>,
113 index: &'a mut Index<'tcx>,
114 parent_stab: Option<&'tcx Stability>,
115 parent_depr: Option<DeprecationEntry>,
119 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
120 // Determine the stability for a node based on its attributes and inherited
121 // stability. The stability is recorded in the index and used as the parent.
122 fn annotate<F>(&mut self, id: NodeId, attrs: &[Attribute],
123 item_sp: Span, kind: AnnotationKind, visit_children: F)
124 where F: FnOnce(&mut Self)
126 if self.index.staged_api[&LOCAL_CRATE] && self.tcx.sess.features.borrow().staged_api {
127 debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
128 if let Some(..) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
129 self.tcx.sess.span_err(item_sp, "`#[deprecated]` cannot be used in staged api, \
130 use `#[rustc_deprecated]` instead");
132 if let Some(mut stab) = attr::find_stability(self.tcx.sess.diagnostic(),
134 // Error if prohibited, or can't inherit anything from a container
135 if kind == AnnotationKind::Prohibited ||
136 (kind == AnnotationKind::Container &&
137 stab.level.is_stable() &&
138 stab.rustc_depr.is_none()) {
139 self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
142 debug!("annotate: found {:?}", stab);
143 // If parent is deprecated and we're not, inherit this by merging
144 // deprecated_since and its reason.
145 if let Some(parent_stab) = self.parent_stab {
146 if parent_stab.rustc_depr.is_some() && stab.rustc_depr.is_none() {
147 stab.rustc_depr = parent_stab.rustc_depr.clone()
151 let stab = self.tcx.intern_stability(stab);
153 // Check if deprecated_since < stable_since. If it is,
154 // this is *almost surely* an accident.
155 if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
156 &attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
157 // Explicit version of iter::order::lt to handle parse errors properly
158 for (dep_v, stab_v) in
159 dep_since.as_str().split(".").zip(stab_since.as_str().split(".")) {
160 if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
161 match dep_v.cmp(&stab_v) {
163 self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
164 after it is deprecated");
167 Ordering::Equal => continue,
168 Ordering::Greater => break,
171 // Act like it isn't less because the question is now nonsensical,
172 // and this makes us not do anything else interesting.
173 self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
180 let def_id = self.tcx.hir.local_def_id(id);
181 self.index.stab_map.insert(def_id, Some(stab));
183 let orig_parent_stab = replace(&mut self.parent_stab, Some(stab));
184 visit_children(self);
185 self.parent_stab = orig_parent_stab;
187 debug!("annotate: not found, parent = {:?}", self.parent_stab);
188 if let Some(stab) = self.parent_stab {
189 if stab.level.is_unstable() {
190 let def_id = self.tcx.hir.local_def_id(id);
191 self.index.stab_map.insert(def_id, Some(stab));
194 visit_children(self);
197 // Emit errors for non-staged-api crates.
199 let tag = unwrap_or!(attr.name(), continue);
200 if tag == "unstable" || tag == "stable" || tag == "rustc_deprecated" {
201 attr::mark_used(attr);
202 self.tcx.sess.span_err(attr.span(), "stability attributes may not be used \
203 outside of the standard library");
207 if let Some(depr) = attr::find_deprecation(self.tcx.sess.diagnostic(), attrs, item_sp) {
208 if kind == AnnotationKind::Prohibited {
209 self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless");
212 // `Deprecation` is just two pointers, no need to intern it
213 let def_id = self.tcx.hir.local_def_id(id);
214 let depr_entry = Some(DeprecationEntry::local(depr, def_id));
215 self.index.depr_map.insert(def_id, depr_entry.clone());
217 let orig_parent_depr = replace(&mut self.parent_depr, depr_entry);
218 visit_children(self);
219 self.parent_depr = orig_parent_depr;
220 } else if let parent_depr @ Some(_) = self.parent_depr.clone() {
221 let def_id = self.tcx.hir.local_def_id(id);
222 self.index.depr_map.insert(def_id, parent_depr);
223 visit_children(self);
225 visit_children(self);
231 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
232 /// Because stability levels are scoped lexically, we want to walk
233 /// nested items in the context of the outer item, so enable
235 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
236 NestedVisitorMap::All(&self.tcx.hir)
239 fn visit_item(&mut self, i: &'tcx Item) {
240 let orig_in_trait_impl = self.in_trait_impl;
241 let mut kind = AnnotationKind::Required;
243 // Inherent impls and foreign modules serve only as containers for other items,
244 // they don't have their own stability. They still can be annotated as unstable
245 // and propagate this unstability to children, but this annotation is completely
246 // optional. They inherit stability from their parents when unannotated.
247 hir::ItemImpl(.., None, _, _) | hir::ItemForeignMod(..) => {
248 self.in_trait_impl = false;
249 kind = AnnotationKind::Container;
251 hir::ItemImpl(.., Some(_), _, _) => {
252 self.in_trait_impl = true;
254 hir::ItemStruct(ref sd, _) => {
256 self.annotate(sd.id(), &i.attrs, i.span, AnnotationKind::Required, |_| {})
262 self.annotate(i.id, &i.attrs, i.span, kind, |v| {
263 intravisit::walk_item(v, i)
265 self.in_trait_impl = orig_in_trait_impl;
268 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
269 self.annotate(ti.id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
270 intravisit::walk_trait_item(v, ti);
274 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
275 let kind = if self.in_trait_impl {
276 AnnotationKind::Prohibited
278 AnnotationKind::Required
280 self.annotate(ii.id, &ii.attrs, ii.span, kind, |v| {
281 intravisit::walk_impl_item(v, ii);
285 fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
286 self.annotate(var.node.data.id(), &var.node.attrs, var.span, AnnotationKind::Required, |v| {
287 intravisit::walk_variant(v, var, g, item_id);
291 fn visit_struct_field(&mut self, s: &'tcx StructField) {
292 self.annotate(s.id, &s.attrs, s.span, AnnotationKind::Required, |v| {
293 intravisit::walk_struct_field(v, s);
297 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
298 self.annotate(i.id, &i.attrs, i.span, AnnotationKind::Required, |v| {
299 intravisit::walk_foreign_item(v, i);
303 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
304 self.annotate(md.id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
308 struct MissingStabilityAnnotations<'a, 'tcx: 'a> {
309 tcx: TyCtxt<'a, 'tcx, 'tcx>,
310 access_levels: &'a AccessLevels,
313 impl<'a, 'tcx: 'a> MissingStabilityAnnotations<'a, 'tcx> {
314 fn check_missing_stability(&self, id: NodeId, span: Span) {
315 let def_id = self.tcx.hir.local_def_id(id);
316 let is_error = !self.tcx.sess.opts.test &&
317 !self.tcx.stability.borrow().stab_map.contains_key(&def_id) &&
318 self.access_levels.is_reachable(id);
320 self.tcx.sess.span_err(span, "This node does not have a stability attribute");
325 impl<'a, 'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'a, 'tcx> {
326 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
327 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
330 fn visit_item(&mut self, i: &'tcx Item) {
332 // Inherent impls and foreign modules serve only as containers for other items,
333 // they don't have their own stability. They still can be annotated as unstable
334 // and propagate this unstability to children, but this annotation is completely
335 // optional. They inherit stability from their parents when unannotated.
336 hir::ItemImpl(.., None, _, _) | hir::ItemForeignMod(..) => {}
338 _ => self.check_missing_stability(i.id, i.span)
341 intravisit::walk_item(self, i)
344 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
345 self.check_missing_stability(ti.id, ti.span);
346 intravisit::walk_trait_item(self, ti);
349 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
350 let impl_def_id = self.tcx.hir.local_def_id(self.tcx.hir.get_parent(ii.id));
351 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
352 self.check_missing_stability(ii.id, ii.span);
354 intravisit::walk_impl_item(self, ii);
357 fn visit_variant(&mut self, var: &'tcx Variant, g: &'tcx Generics, item_id: NodeId) {
358 self.check_missing_stability(var.node.data.id(), var.span);
359 intravisit::walk_variant(self, var, g, item_id);
362 fn visit_struct_field(&mut self, s: &'tcx StructField) {
363 self.check_missing_stability(s.id, s.span);
364 intravisit::walk_struct_field(self, s);
367 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem) {
368 self.check_missing_stability(i.id, i.span);
369 intravisit::walk_foreign_item(self, i);
372 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
373 self.check_missing_stability(md.id, md.span);
377 impl<'a, 'tcx> Index<'tcx> {
378 /// Construct the stability index for a crate being compiled.
379 pub fn build(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>) {
380 let ref active_lib_features = tcx.sess.features.borrow().declared_lib_features;
382 // Put the active features into a map for quick lookup
383 self.active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
385 let krate = tcx.hir.krate();
386 let mut annotator = Annotator {
391 in_trait_impl: false,
393 annotator.annotate(ast::CRATE_NODE_ID, &krate.attrs, krate.span, AnnotationKind::Required,
394 |v| intravisit::walk_crate(v, krate));
397 pub fn new(hir_map: &hir_map::Map) -> Index<'tcx> {
398 let krate = hir_map.krate();
400 let mut is_staged_api = false;
401 for attr in &krate.attrs {
402 if attr.path == "stable" || attr.path == "unstable" {
403 is_staged_api = true;
408 let mut staged_api = FxHashMap();
409 staged_api.insert(LOCAL_CRATE, is_staged_api);
411 staged_api: staged_api,
412 stab_map: DefIdMap(),
413 depr_map: DefIdMap(),
414 active_features: FxHashSet(),
415 used_features: FxHashMap(),
420 /// Cross-references the feature names of unstable APIs with enabled
421 /// features and possibly prints errors.
422 pub fn check_unstable_api_usage<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
423 let mut checker = Checker { tcx: tcx };
424 tcx.hir.krate().visit_all_item_likes(&mut checker.as_deep_visitor());
427 struct Checker<'a, 'tcx: 'a> {
428 tcx: TyCtxt<'a, 'tcx, 'tcx>,
431 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
432 // (See issue #38412)
433 fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool {
434 // Check if `def_id` is a trait method.
435 match self.sess.cstore.describe_def(def_id) {
436 Some(Def::Method(_)) |
437 Some(Def::AssociatedTy(_)) |
438 Some(Def::AssociatedConst(_)) => {
439 match self.associated_item(def_id).container {
440 ty::TraitContainer(trait_def_id) => {
441 // Trait methods do not declare visibility (even
442 // for visibility info in cstore). Use containing
443 // trait instead, so methods of pub traits are
444 // themselves considered pub.
445 def_id = trait_def_id;
453 let visibility = self.sess.cstore.visibility(def_id);
456 // must check stability for pub items.
457 ty::Visibility::Public => false,
459 // these are not visible outside crate; therefore
460 // stability markers are irrelevant, if even present.
461 ty::Visibility::Restricted(..) |
462 ty::Visibility::Invisible => true,
466 pub fn check_stability(self, def_id: DefId, id: NodeId, span: Span) {
467 if span.allows_unstable() {
469 skipping span={:?} since it is internal", span);
473 let lint_deprecated = |note: Option<Symbol>| {
474 let msg = if let Some(note) = note {
475 format!("use of deprecated item: {}", note)
477 format!("use of deprecated item")
480 self.sess.add_lint(lint::builtin::DEPRECATED, id, span, msg);
483 // Deprecated attributes apply in-crate and cross-crate.
484 if let Some(depr_entry) = self.lookup_deprecation_entry(def_id) {
485 let skip = if id == ast::DUMMY_NODE_ID {
488 let parent_def_id = self.hir.local_def_id(self.hir.get_parent(id));
489 self.lookup_deprecation_entry(parent_def_id).map_or(false, |parent_depr| {
490 parent_depr.same_origin(&depr_entry)
495 lint_deprecated(depr_entry.attr.note);
499 let is_staged_api = *self.stability.borrow_mut().staged_api.entry(def_id.krate)
500 .or_insert_with(|| self.sess.cstore.is_staged_api(def_id.krate));
505 let stability = self.lookup_stability(def_id);
507 inspecting def_id={:?} span={:?} of stability={:?}", def_id, span, stability);
509 if let Some(&Stability{rustc_depr: Some(attr::RustcDeprecation { reason, .. }), ..})
511 if id != ast::DUMMY_NODE_ID {
512 lint_deprecated(Some(reason));
516 // Only the cross-crate scenario matters when checking unstable APIs
517 let cross_crate = !def_id.is_local();
522 if let Some(&Stability { ref level, ref feature, .. }) = stability {
523 self.stability.borrow_mut().used_features.insert(feature.clone(), level.clone());
526 // Issue 38412: private items lack stability markers.
527 if self.skip_stability_check_due_to_privacy(def_id) {
532 Some(&Stability { level: attr::Unstable {ref reason, issue}, ref feature, .. }) => {
533 if !self.stability.borrow().active_features.contains(feature) {
534 let msg = match *reason {
535 Some(ref r) => format!("use of unstable library feature '{}': {}",
536 feature.as_str(), &r),
537 None => format!("use of unstable library feature '{}'", &feature)
539 emit_feature_err(&self.sess.parse_sess, &feature.as_str(), span,
540 GateIssue::Library(Some(issue)), &msg);
544 // Stable APIs are always ok to call and deprecated APIs are
545 // handled by the lint emitting logic above.
548 span_bug!(span, "encountered unmarked API");
554 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
555 /// Because stability levels are scoped lexically, we want to walk
556 /// nested items in the context of the outer item, so enable
558 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
559 NestedVisitorMap::OnlyBodies(&self.tcx.hir)
562 fn visit_item(&mut self, item: &'tcx hir::Item) {
564 hir::ItemExternCrate(_) => {
565 // compiler-generated `extern crate` items have a dummy span.
566 if item.span == DUMMY_SP { return }
568 let cnum = match self.tcx.sess.cstore.extern_mod_stmt_cnum(item.id) {
572 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
573 self.tcx.check_stability(def_id, item.id, item.span);
576 // For implementations of traits, check the stability of each item
577 // individually as it's possible to have a stable trait with unstable
579 hir::ItemImpl(.., Some(ref t), _, ref impl_item_refs) => {
580 if let Def::Trait(trait_did) = t.path.def {
581 for impl_item_ref in impl_item_refs {
582 let impl_item = self.tcx.hir.impl_item(impl_item_ref.id);
583 let trait_item_def_id = self.tcx.associated_items(trait_did)
584 .find(|item| item.name == impl_item.name).map(|item| item.def_id);
585 if let Some(def_id) = trait_item_def_id {
586 // Pass `DUMMY_NODE_ID` to skip deprecation warnings.
587 self.tcx.check_stability(def_id, ast::DUMMY_NODE_ID, impl_item.span);
595 intravisit::walk_item(self, item);
598 fn visit_path(&mut self, path: &'tcx hir::Path, id: ast::NodeId) {
600 Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => {}
601 _ => self.tcx.check_stability(path.def.def_id(), id, path.span)
603 intravisit::walk_path(self, path)
607 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
608 /// Lookup the stability for a node, loading external crate
609 /// metadata as necessary.
610 pub fn lookup_stability(self, id: DefId) -> Option<&'gcx Stability> {
611 if let Some(st) = self.stability.borrow().stab_map.get(&id) {
615 let st = self.lookup_stability_uncached(id);
616 self.stability.borrow_mut().stab_map.insert(id, st);
620 pub fn lookup_deprecation(self, id: DefId) -> Option<Deprecation> {
621 self.lookup_deprecation_entry(id).map(|depr| depr.attr)
624 pub fn lookup_deprecation_entry(self, id: DefId) -> Option<DeprecationEntry> {
625 if let Some(depr) = self.stability.borrow().depr_map.get(&id) {
629 let depr = self.lookup_deprecation_uncached(id);
630 self.stability.borrow_mut().depr_map.insert(id, depr.clone());
634 fn lookup_stability_uncached(self, id: DefId) -> Option<&'gcx Stability> {
635 debug!("lookup(id={:?})", id);
637 None // The stability cache is filled partially lazily
639 self.sess.cstore.stability(id).map(|st| self.intern_stability(st))
643 fn lookup_deprecation_uncached(self, id: DefId) -> Option<DeprecationEntry> {
644 debug!("lookup(id={:?})", id);
646 None // The stability cache is filled partially lazily
648 self.sess.cstore.deprecation(id).map(DeprecationEntry::external)
653 /// Given the list of enabled features that were not language features (i.e. that
654 /// were expected to be library features), and the list of features used from
655 /// libraries, identify activated features that don't exist and error about them.
656 pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
657 let sess = &tcx.sess;
659 let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
661 if tcx.stability.borrow().staged_api[&LOCAL_CRATE] && tcx.sess.features.borrow().staged_api {
662 let krate = tcx.hir.krate();
663 let mut missing = MissingStabilityAnnotations {
665 access_levels: access_levels,
667 missing.check_missing_stability(ast::CRATE_NODE_ID, krate.span);
668 intravisit::walk_crate(&mut missing, krate);
669 krate.visit_all_item_likes(&mut missing.as_deep_visitor());
672 let ref declared_lib_features = sess.features.borrow().declared_lib_features;
673 let mut remaining_lib_features: FxHashMap<Symbol, Span>
674 = declared_lib_features.clone().into_iter().collect();
676 fn format_stable_since_msg(version: &str) -> String {
677 format!("this feature has been stable since {}. Attribute no longer needed", version)
680 for &(ref stable_lang_feature, span) in &sess.features.borrow().declared_stable_lang_features {
681 let version = find_lang_feature_accepted_version(&stable_lang_feature.as_str())
682 .expect("unexpectedly couldn't find version feature was stabilized");
683 sess.add_lint(lint::builtin::STABLE_FEATURES,
686 format_stable_since_msg(version));
689 let index = tcx.stability.borrow();
690 for (used_lib_feature, level) in &index.used_features {
691 match remaining_lib_features.remove(used_lib_feature) {
693 if let &attr::StabilityLevel::Stable { since: ref version } = level {
694 sess.add_lint(lint::builtin::STABLE_FEATURES,
697 format_stable_since_msg(&version.as_str()));
700 None => ( /* used but undeclared, handled during the previous ast visit */ )
704 for &span in remaining_lib_features.values() {
705 sess.add_lint(lint::builtin::UNUSED_FEATURES,
708 "unused or unknown feature".to_string());