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::*;
18 use metadata::cstore::LOCAL_CRATE;
20 use middle::def_id::{CRATE_DEF_INDEX, DefId};
22 use middle::privacy::AccessLevels;
23 use metadata::csearch;
24 use syntax::parse::token::InternedString;
25 use syntax::codemap::{Span, DUMMY_SP};
27 use syntax::ast::{NodeId, Attribute};
28 use syntax::feature_gate::{GateIssue, emit_feature_err};
29 use syntax::attr::{self, Stability, AttrMetaMethods};
30 use util::nodemap::{DefIdMap, FnvHashSet, FnvHashMap};
33 use rustc_front::hir::{Block, Crate, Item, Generics, StructField, Variant};
34 use rustc_front::intravisit::{self, Visitor};
36 use std::mem::replace;
37 use std::cmp::Ordering;
39 #[derive(RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Clone, Copy, Debug, Eq, Hash)]
40 pub enum StabilityLevel {
46 pub fn from_attr_level(level: &attr::StabilityLevel) -> Self {
47 if level.is_stable() { Stable } else { Unstable }
53 // Annotation is required if not inherited from unstable parents
55 // Annotation is useless, reject it
57 // Annotation itself is useless, but it can be propagated to children
61 /// A stability index, giving the stability level for items and methods.
62 pub struct Index<'tcx> {
63 /// This is mostly a cache, except the stabilities of local items
64 /// are filled by the annotator.
65 map: DefIdMap<Option<&'tcx Stability>>,
67 /// Maps for each crate whether it is part of the staged API.
68 staged_api: FnvHashMap<ast::CrateNum, bool>
71 // A private tree-walker for producing an Index.
72 struct Annotator<'a, 'tcx: 'a> {
73 tcx: &'a ty::ctxt<'tcx>,
74 index: &'a mut Index<'tcx>,
75 parent: Option<&'tcx Stability>,
76 access_levels: &'a AccessLevels,
81 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
82 // Determine the stability for a node based on its attributes and inherited
83 // stability. The stability is recorded in the index and used as the parent.
84 fn annotate<F>(&mut self, id: NodeId, attrs: &Vec<Attribute>,
85 item_sp: Span, kind: AnnotationKind, visit_children: F)
86 where F: FnOnce(&mut Annotator)
88 if self.index.staged_api[&LOCAL_CRATE] {
89 debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
90 if let Some(mut stab) = attr::find_stability(self.tcx.sess.diagnostic(),
92 // Error if prohibited, or can't inherit anything from a container
93 if kind == AnnotationKind::Prohibited ||
94 (kind == AnnotationKind::Container &&
95 stab.level.is_stable() &&
96 stab.depr.is_none()) {
97 self.tcx.sess.span_err(item_sp, "This stability annotation is useless");
100 debug!("annotate: found {:?}", stab);
101 // If parent is deprecated and we're not, inherit this by merging
102 // deprecated_since and its reason.
103 if let Some(parent_stab) = self.parent {
104 if parent_stab.depr.is_some() && stab.depr.is_none() {
105 stab.depr = parent_stab.depr.clone()
109 let stab = self.tcx.intern_stability(stab);
111 // Check if deprecated_since < stable_since. If it is,
112 // this is *almost surely* an accident.
113 if let (&Some(attr::Deprecation {since: ref dep_since, ..}),
114 &attr::Stable {since: ref stab_since}) = (&stab.depr, &stab.level) {
115 // Explicit version of iter::order::lt to handle parse errors properly
116 for (dep_v, stab_v) in dep_since.split(".").zip(stab_since.split(".")) {
117 if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
118 match dep_v.cmp(&stab_v) {
120 self.tcx.sess.span_err(item_sp, "An API can't be stabilized \
121 after it is deprecated");
124 Ordering::Equal => continue,
125 Ordering::Greater => break,
128 // Act like it isn't less because the question is now nonsensical,
129 // and this makes us not do anything else interesting.
130 self.tcx.sess.span_err(item_sp, "Invalid stability or deprecation \
137 let def_id = self.tcx.map.local_def_id(id);
138 self.index.map.insert(def_id, Some(stab));
140 let parent = replace(&mut self.parent, Some(stab));
141 visit_children(self);
142 self.parent = parent;
144 debug!("annotate: not found, parent = {:?}", self.parent);
145 let mut is_error = kind == AnnotationKind::Required &&
146 self.access_levels.is_reachable(id) &&
147 !self.tcx.sess.opts.test;
148 if let Some(stab) = self.parent {
149 if stab.level.is_unstable() {
150 let def_id = self.tcx.map.local_def_id(id);
151 self.index.map.insert(def_id, Some(stab));
156 self.tcx.sess.span_err(item_sp, "This node does not have \
157 a stability attribute");
159 visit_children(self);
162 // Emit errors for non-staged-api crates.
164 let tag = attr.name();
165 if tag == "unstable" || tag == "stable" || tag == "deprecated" {
166 attr::mark_used(attr);
167 self.tcx.sess.span_err(attr.span(), "stability attributes may not be used \
168 outside of the standard library");
171 visit_children(self);
176 impl<'a, 'tcx, 'v> Visitor<'v> for Annotator<'a, 'tcx> {
177 /// Because stability levels are scoped lexically, we want to walk
178 /// nested items in the context of the outer item, so enable
180 fn visit_nested_item(&mut self, item: hir::ItemId) {
181 self.visit_item(self.tcx.map.expect_item(item.id))
184 fn visit_item(&mut self, i: &Item) {
185 let orig_in_trait_impl = self.in_trait_impl;
186 let orig_in_enum = self.in_enum;
187 let mut kind = AnnotationKind::Required;
189 // Inherent impls and foreign modules serve only as containers for other items,
190 // they don't have their own stability. They still can be annotated as unstable
191 // and propagate this unstability to children, but this annotation is completely
192 // optional. They inherit stability from their parents when unannotated.
193 hir::ItemImpl(_, _, _, None, _, _) | hir::ItemForeignMod(..) => {
194 self.in_trait_impl = false;
195 kind = AnnotationKind::Container;
197 hir::ItemImpl(_, _, _, Some(_), _, _) => {
198 self.in_trait_impl = true;
200 hir::ItemStruct(ref sd, _) => {
201 self.in_enum = false;
203 self.annotate(sd.id(), &i.attrs, i.span, AnnotationKind::Required, |_| {})
206 hir::ItemEnum(..) => {
212 self.annotate(i.id, &i.attrs, i.span, kind, |v| {
213 intravisit::walk_item(v, i)
215 self.in_trait_impl = orig_in_trait_impl;
216 self.in_enum = orig_in_enum;
219 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
220 self.annotate(ti.id, &ti.attrs, ti.span, AnnotationKind::Required, |v| {
221 intravisit::walk_trait_item(v, ti);
225 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
226 let kind = if self.in_trait_impl {
227 AnnotationKind::Prohibited
229 AnnotationKind::Required
231 self.annotate(ii.id, &ii.attrs, ii.span, kind, |v| {
232 intravisit::walk_impl_item(v, ii);
236 fn visit_variant(&mut self, var: &Variant, g: &'v Generics, item_id: NodeId) {
237 self.annotate(var.node.data.id(), &var.node.attrs, var.span, AnnotationKind::Required, |v| {
238 intravisit::walk_variant(v, var, g, item_id);
242 fn visit_struct_field(&mut self, s: &StructField) {
243 // FIXME: This is temporary, can't use attributes with tuple variant fields until snapshot
244 let kind = if self.in_enum && s.node.kind.is_unnamed() {
245 AnnotationKind::Prohibited
247 AnnotationKind::Required
249 self.annotate(s.node.id, &s.node.attrs, s.span, kind, |v| {
250 intravisit::walk_struct_field(v, s);
254 fn visit_foreign_item(&mut self, i: &hir::ForeignItem) {
255 self.annotate(i.id, &i.attrs, i.span, AnnotationKind::Required, |v| {
256 intravisit::walk_foreign_item(v, i);
260 fn visit_macro_def(&mut self, md: &'v hir::MacroDef) {
261 if md.imported_from.is_none() {
262 self.annotate(md.id, &md.attrs, md.span, AnnotationKind::Required, |_| {});
267 impl<'tcx> Index<'tcx> {
268 /// Construct the stability index for a crate being compiled.
269 pub fn build(&mut self, tcx: &ty::ctxt<'tcx>, krate: &Crate, access_levels: &AccessLevels) {
270 let mut annotator = Annotator {
274 access_levels: access_levels,
275 in_trait_impl: false,
278 annotator.annotate(ast::CRATE_NODE_ID, &krate.attrs, krate.span, AnnotationKind::Required,
279 |v| intravisit::walk_crate(v, krate));
282 pub fn new(krate: &Crate) -> Index {
283 let mut is_staged_api = false;
284 for attr in &krate.attrs {
285 if attr.name() == "staged_api" {
286 if let ast::MetaWord(_) = attr.node.value.node {
287 attr::mark_used(attr);
288 is_staged_api = true;
293 let mut staged_api = FnvHashMap();
294 staged_api.insert(LOCAL_CRATE, is_staged_api);
296 staged_api: staged_api,
302 /// Cross-references the feature names of unstable APIs with enabled
303 /// features and possibly prints errors. Returns a list of all
305 pub fn check_unstable_api_usage(tcx: &ty::ctxt)
306 -> FnvHashMap<InternedString, StabilityLevel> {
307 let ref active_lib_features = tcx.sess.features.borrow().declared_lib_features;
309 // Put the active features into a map for quick lookup
310 let active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
312 let mut checker = Checker {
314 active_features: active_features,
315 used_features: FnvHashMap(),
318 intravisit::walk_crate(&mut checker, tcx.map.krate());
320 let used_features = checker.used_features;
321 return used_features;
324 struct Checker<'a, 'tcx: 'a> {
325 tcx: &'a ty::ctxt<'tcx>,
326 active_features: FnvHashSet<InternedString>,
327 used_features: FnvHashMap<InternedString, StabilityLevel>,
328 // Within a block where feature gate checking can be skipped.
332 impl<'a, 'tcx> Checker<'a, 'tcx> {
333 fn check(&mut self, id: DefId, span: Span, stab: &Option<&Stability>) {
334 // Only the cross-crate scenario matters when checking unstable APIs
335 let cross_crate = !id.is_local();
340 // We don't need to check for stability - presumably compiler generated code.
341 if self.in_skip_block > 0 {
346 Some(&Stability { level: attr::Unstable {ref reason, issue}, ref feature, .. }) => {
347 self.used_features.insert(feature.clone(), Unstable);
349 if !self.active_features.contains(feature) {
350 let msg = match *reason {
351 Some(ref r) => format!("use of unstable library feature '{}': {}",
353 None => format!("use of unstable library feature '{}'", &feature)
355 emit_feature_err(&self.tcx.sess.parse_sess.span_diagnostic,
356 &feature, span, GateIssue::Library(Some(issue)), &msg);
359 Some(&Stability { ref level, ref feature, .. }) => {
360 self.used_features.insert(feature.clone(), StabilityLevel::from_attr_level(level));
362 // Stable APIs are always ok to call and deprecated APIs are
363 // handled by a lint.
366 // This is an 'unmarked' API, which should not exist
367 // in the standard library.
368 if self.tcx.sess.features.borrow().unmarked_api {
369 self.tcx.sess.span_warn(span, "use of unmarked library feature");
370 self.tcx.sess.span_note(span, "this is either a bug in the library you are \
371 using or a bug in the compiler - please \
372 report it in both places");
374 self.tcx.sess.span_err(span, "use of unmarked library feature");
375 self.tcx.sess.span_note(span, "this is either a bug in the library you are \
376 using or a bug in the compiler - please \
377 report it in both places");
378 self.tcx.sess.span_note(span, "use #![feature(unmarked_api)] in the \
379 crate attributes to override this");
386 impl<'a, 'v, 'tcx> Visitor<'v> for Checker<'a, 'tcx> {
387 /// Because stability levels are scoped lexically, we want to walk
388 /// nested items in the context of the outer item, so enable
390 fn visit_nested_item(&mut self, item: hir::ItemId) {
391 self.visit_item(self.tcx.map.expect_item(item.id))
394 fn visit_item(&mut self, item: &hir::Item) {
395 // When compiling with --test we don't enforce stability on the
396 // compiler-generated test module, demarcated with `DUMMY_SP` plus the
398 if item.span == DUMMY_SP && item.name.as_str() == "__test" { return }
400 check_item(self.tcx, item, true,
401 &mut |id, sp, stab| self.check(id, sp, stab));
402 intravisit::walk_item(self, item);
405 fn visit_expr(&mut self, ex: &hir::Expr) {
406 check_expr(self.tcx, ex,
407 &mut |id, sp, stab| self.check(id, sp, stab));
408 intravisit::walk_expr(self, ex);
411 fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
412 check_path(self.tcx, path, id,
413 &mut |id, sp, stab| self.check(id, sp, stab));
414 intravisit::walk_path(self, path)
417 fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
418 check_path_list_item(self.tcx, item,
419 &mut |id, sp, stab| self.check(id, sp, stab));
420 intravisit::walk_path_list_item(self, prefix, item)
423 fn visit_pat(&mut self, pat: &hir::Pat) {
424 check_pat(self.tcx, pat,
425 &mut |id, sp, stab| self.check(id, sp, stab));
426 intravisit::walk_pat(self, pat)
429 fn visit_block(&mut self, b: &hir::Block) {
430 let old_skip_count = self.in_skip_block;
432 hir::BlockCheckMode::PushUnstableBlock => {
433 self.in_skip_block += 1;
435 hir::BlockCheckMode::PopUnstableBlock => {
436 self.in_skip_block = self.in_skip_block.checked_sub(1).unwrap();
440 intravisit::walk_block(self, b);
441 self.in_skip_block = old_skip_count;
445 /// Helper for discovering nodes to check for stability
446 pub fn check_item(tcx: &ty::ctxt, item: &hir::Item, warn_about_defns: bool,
447 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
449 hir::ItemExternCrate(_) => {
450 // compiler-generated `extern crate` items have a dummy span.
451 if item.span == DUMMY_SP { return }
453 let cnum = match tcx.sess.cstore.find_extern_mod_stmt_cnum(item.id) {
457 let id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
458 maybe_do_stability_check(tcx, id, item.span, cb);
461 // For implementations of traits, check the stability of each item
462 // individually as it's possible to have a stable trait with unstable
464 hir::ItemImpl(_, _, _, Some(ref t), _, ref impl_items) => {
465 let trait_did = tcx.def_map.borrow().get(&t.ref_id).unwrap().def_id();
466 let trait_items = tcx.trait_items(trait_did);
468 for impl_item in impl_items {
469 let item = trait_items.iter().find(|item| {
470 item.name() == impl_item.name
472 if warn_about_defns {
473 maybe_do_stability_check(tcx, item.def_id(), impl_item.span, cb);
482 /// Helper for discovering nodes to check for stability
483 pub fn check_expr(tcx: &ty::ctxt, e: &hir::Expr,
484 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
486 let id = match e.node {
487 hir::ExprMethodCall(i, _, _) => {
489 let method_call = ty::MethodCall::expr(e.id);
490 tcx.tables.borrow().method_map[&method_call].def_id
492 hir::ExprField(ref base_e, ref field) => {
494 match tcx.expr_ty_adjusted(base_e).sty {
495 ty::TyStruct(def, _) => def.struct_variant().field_named(field.node).did,
496 _ => tcx.sess.span_bug(e.span,
497 "stability::check_expr: named field access on non-struct")
500 hir::ExprTupField(ref base_e, ref field) => {
502 match tcx.expr_ty_adjusted(base_e).sty {
503 ty::TyStruct(def, _) => def.struct_variant().fields[field.node].did,
504 ty::TyTuple(..) => return,
505 _ => tcx.sess.span_bug(e.span,
506 "stability::check_expr: unnamed field access on \
507 something other than a tuple or struct")
510 hir::ExprStruct(_, ref expr_fields, _) => {
511 let type_ = tcx.expr_ty(e);
513 ty::TyStruct(def, _) => {
514 // check the stability of each field that appears
515 // in the construction expression.
516 for field in expr_fields {
517 let did = def.struct_variant()
518 .field_named(field.name.node)
520 maybe_do_stability_check(tcx, did, field.span, cb);
526 // we don't look at stability attributes on
527 // struct-like enums (yet...), but it's definitely not
528 // a bug to have construct one.
529 ty::TyEnum(..) => return,
531 tcx.sess.span_bug(e.span,
532 &format!("stability::check_expr: struct construction \
533 of non-struct, type {:?}",
541 maybe_do_stability_check(tcx, id, span, cb);
544 pub fn check_path(tcx: &ty::ctxt, path: &hir::Path, id: ast::NodeId,
545 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
546 match tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
547 Some(def::DefPrimTy(..)) => {}
548 Some(def::DefSelfTy(..)) => {}
550 maybe_do_stability_check(tcx, def.def_id(), path.span, cb);
556 pub fn check_path_list_item(tcx: &ty::ctxt, item: &hir::PathListItem,
557 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
558 match tcx.def_map.borrow().get(&item.node.id()).map(|d| d.full_def()) {
559 Some(def::DefPrimTy(..)) => {}
561 maybe_do_stability_check(tcx, def.def_id(), item.span, cb);
567 pub fn check_pat(tcx: &ty::ctxt, pat: &hir::Pat,
568 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
569 debug!("check_pat(pat = {:?})", pat);
570 if is_internal(tcx, pat.span) { return; }
572 let v = match tcx.pat_ty_opt(pat) {
573 Some(&ty::TyS { sty: ty::TyStruct(def, _), .. }) => def.struct_variant(),
574 Some(_) | None => return,
578 // A Variant(..) pattern `hir::PatEnum(_, None)` doesn't have to be recursed into.
579 hir::PatEnum(_, Some(ref pat_fields)) => {
580 for (field, struct_field) in pat_fields.iter().zip(&v.fields) {
581 maybe_do_stability_check(tcx, struct_field.did, field.span, cb)
585 hir::PatStruct(_, ref pat_fields, _) => {
586 for field in pat_fields {
587 let did = v.field_named(field.node.name).did;
588 maybe_do_stability_check(tcx, did, field.span, cb);
591 // everything else is fine.
596 fn maybe_do_stability_check(tcx: &ty::ctxt, id: DefId, span: Span,
597 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
598 if !is_staged_api(tcx, id) {
599 debug!("maybe_do_stability_check: \
600 skipping id={:?} since it is not staged_api", id);
603 if is_internal(tcx, span) {
604 debug!("maybe_do_stability_check: \
605 skipping span={:?} since it is internal", span);
608 let ref stability = lookup(tcx, id);
609 debug!("maybe_do_stability_check: \
610 inspecting id={:?} span={:?} of stability={:?}", id, span, stability);
611 cb(id, span, stability);
614 fn is_internal(tcx: &ty::ctxt, span: Span) -> bool {
615 tcx.sess.codemap().span_allows_unstable(span)
618 fn is_staged_api(tcx: &ty::ctxt, id: DefId) -> bool {
619 match tcx.trait_item_of_item(id) {
620 Some(ty::MethodTraitItemId(trait_method_id))
621 if trait_method_id != id => {
622 is_staged_api(tcx, trait_method_id)
625 *tcx.stability.borrow_mut().staged_api.entry(id.krate).or_insert_with(
626 || csearch::is_staged_api(&tcx.sess.cstore, id.krate))
631 /// Lookup the stability for a node, loading external crate
632 /// metadata as necessary.
633 pub fn lookup<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
634 if let Some(st) = tcx.stability.borrow().map.get(&id) {
638 let st = lookup_uncached(tcx, id);
639 tcx.stability.borrow_mut().map.insert(id, st);
643 fn lookup_uncached<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
644 debug!("lookup(id={:?})", id);
646 // is this definition the implementation of a trait method?
647 match tcx.trait_item_of_item(id) {
648 Some(ty::MethodTraitItemId(trait_method_id)) if trait_method_id != id => {
649 debug!("lookup: trait_method_id={:?}", trait_method_id);
650 return lookup(tcx, trait_method_id)
655 let item_stab = if id.is_local() {
656 None // The stability cache is filled partially lazily
658 csearch::get_stability(&tcx.sess.cstore, id).map(|st| tcx.intern_stability(st))
661 item_stab.or_else(|| {
663 if let Some(trait_id) = tcx.trait_id_of_impl(id) {
664 // FIXME (#18969): for the time being, simply use the
665 // stability of the trait to determine the stability of any
666 // unmarked impls for it. See FIXME above for more details.
668 debug!("lookup: trait_id={:?}", trait_id);
669 return lookup(tcx, trait_id);
676 /// Given the list of enabled features that were not language features (i.e. that
677 /// were expected to be library features), and the list of features used from
678 /// libraries, identify activated features that don't exist and error about them.
679 pub fn check_unused_or_stable_features(sess: &Session,
680 lib_features_used: &FnvHashMap<InternedString,
682 let ref declared_lib_features = sess.features.borrow().declared_lib_features;
683 let mut remaining_lib_features: FnvHashMap<InternedString, Span>
684 = declared_lib_features.clone().into_iter().collect();
686 let stable_msg = "this feature is stable. attribute no longer needed";
688 for &span in &sess.features.borrow().declared_stable_lang_features {
689 sess.add_lint(lint::builtin::STABLE_FEATURES,
692 stable_msg.to_string());
695 for (used_lib_feature, level) in lib_features_used {
696 match remaining_lib_features.remove(used_lib_feature) {
698 if *level == Stable {
699 sess.add_lint(lint::builtin::STABLE_FEATURES,
702 stable_msg.to_string());
705 None => ( /* used but undeclared, handled during the previous ast visit */ )
709 for &span in remaining_lib_features.values() {
710 sess.add_lint(lint::builtin::UNUSED_FEATURES,
713 "unused or unknown feature".to_string());