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::PublicItems;
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::{FnDecl, Block, Crate, Item, Generics, StructField, Variant};
34 use rustc_front::visit::{self, FnKind, 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 }
51 /// A stability index, giving the stability level for items and methods.
52 pub struct Index<'tcx> {
53 /// This is mostly a cache, except the stabilities of local items
54 /// are filled by the annotator.
55 map: DefIdMap<Option<&'tcx Stability>>,
57 /// Maps for each crate whether it is part of the staged API.
58 staged_api: FnvHashMap<ast::CrateNum, bool>
61 // A private tree-walker for producing an Index.
62 struct Annotator<'a, 'tcx: 'a> {
63 tcx: &'a ty::ctxt<'tcx>,
64 index: &'a mut Index<'tcx>,
65 parent: Option<&'tcx Stability>,
66 export_map: &'a PublicItems,
69 impl<'a, 'tcx: 'a> Annotator<'a, 'tcx> {
70 // Determine the stability for a node based on its attributes and inherited
71 // stability. The stability is recorded in the index and used as the parent.
72 fn annotate<F>(&mut self, id: NodeId, use_parent: bool,
73 attrs: &Vec<Attribute>, item_sp: Span, f: F, required: bool) where
74 F: FnOnce(&mut Annotator),
76 if self.index.staged_api[&LOCAL_CRATE] {
77 debug!("annotate(id = {:?}, attrs = {:?})", id, attrs);
78 match attr::find_stability(self.tcx.sess.diagnostic(), attrs, item_sp) {
80 debug!("annotate: found {:?}", stab);
81 // if parent is deprecated and we're not, inherit this by merging
82 // deprecated_since and its reason.
83 if let Some(parent_stab) = self.parent {
84 if parent_stab.depr.is_some()
85 && stab.depr.is_none() {
86 stab.depr = parent_stab.depr.clone()
90 let stab = self.tcx.intern_stability(stab);
92 // Check if deprecated_since < stable_since. If it is,
93 // this is *almost surely* an accident.
94 let deprecated_predates_stable = match (&stab.depr, &stab.level) {
95 (&Some(attr::Deprecation {since: ref dep_since, ..}),
96 &attr::Stable {since: ref stab_since}) => {
97 // explicit version of iter::order::lt to handle parse errors properly
98 let mut is_less = false;
99 for (dep_v, stab_v) in dep_since.split(".").zip(stab_since.split(".")) {
100 match (dep_v.parse::<u64>(), stab_v.parse::<u64>()) {
101 (Ok(dep_v), Ok(stab_v)) => match dep_v.cmp(&stab_v) {
106 Ordering::Equal => { continue; }
107 Ordering::Greater => { break; }
110 self.tcx.sess.span_err(item_sp,
111 "Invalid stability or deprecation version found");
112 // act like it isn't less because the question is now
113 // nonsensical, and this makes us not do anything else
124 if deprecated_predates_stable {
125 self.tcx.sess.span_err(item_sp,
126 "An API can't be stabilized after it is deprecated");
129 let def_id = self.tcx.map.local_def_id(id);
130 self.index.map.insert(def_id, Some(stab));
132 // Don't inherit #[stable(feature = "rust1", since = "1.0.0")]
133 if !stab.level.is_stable() {
134 let parent = replace(&mut self.parent, Some(stab));
136 self.parent = parent;
142 debug!("annotate: not found, use_parent = {:?}, parent = {:?}",
143 use_parent, self.parent);
145 if let Some(stab) = self.parent {
146 let def_id = self.tcx.map.local_def_id(id);
147 self.index.map.insert(def_id, Some(stab));
148 } else if self.index.staged_api[&LOCAL_CRATE] && required
149 && self.export_map.contains(&id)
150 && !self.tcx.sess.opts.test {
151 self.tcx.sess.span_err(item_sp,
152 "This node does not \
153 have a stability attribute");
160 // Emit warnings for non-staged-api crates. These should be errors.
162 let tag = attr.name();
163 if tag == "unstable" || tag == "stable" || tag == "deprecated" {
164 attr::mark_used(attr);
165 self.tcx.sess.span_err(attr.span(),
166 "stability attributes may not be used outside \
167 of the standard library");
175 impl<'a, 'tcx, 'v> Visitor<'v> for Annotator<'a, 'tcx> {
176 fn visit_item(&mut self, i: &Item) {
177 // FIXME (#18969): the following is a hack around the fact
178 // that we cannot currently annotate the stability of
179 // `deriving`. Basically, we do *not* allow stability
180 // inheritance on trait implementations, so that derived
181 // implementations appear to be unannotated. This then allows
182 // derived implementations to be automatically tagged with the
183 // stability of the trait. This is WRONG, but expedient to get
184 // libstd stabilized for the 1.0 release.
185 let use_parent = match i.node {
186 hir::ItemImpl(_, _, _, Some(_), _, _) => false,
190 // In case of a `pub use <mod>;`, we should not error since the stability
191 // is inherited from the module itself
192 let required = match i.node {
193 hir::ItemUse(_) => i.vis != hir::Public,
197 self.annotate(i.id, use_parent, &i.attrs, i.span,
198 |v| visit::walk_item(v, i), required);
200 if let hir::ItemStruct(ref sd, _) = i.node {
202 self.annotate(sd.id(), true, &i.attrs, i.span, |_| {}, true)
207 fn visit_fn(&mut self, _: FnKind<'v>, _: &'v FnDecl,
208 _: &'v Block, _: Span, _: NodeId) {
209 // Items defined in a function body have no reason to have
210 // a stability attribute, so we don't recurse.
213 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
214 self.annotate(ti.id, true, &ti.attrs, ti.span,
215 |v| visit::walk_trait_item(v, ti), true);
218 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
219 self.annotate(ii.id, true, &ii.attrs, ii.span,
220 |v| visit::walk_impl_item(v, ii), false);
223 fn visit_variant(&mut self, var: &Variant, g: &'v Generics, item_id: NodeId) {
224 self.annotate(var.node.data.id(), true, &var.node.attrs, var.span,
225 |v| visit::walk_variant(v, var, g, item_id), true)
228 fn visit_struct_field(&mut self, s: &StructField) {
229 self.annotate(s.node.id, true, &s.node.attrs, s.span,
230 |v| visit::walk_struct_field(v, s), !s.node.kind.is_unnamed());
233 fn visit_foreign_item(&mut self, i: &hir::ForeignItem) {
234 self.annotate(i.id, true, &i.attrs, i.span, |_| {}, true);
238 impl<'tcx> Index<'tcx> {
239 /// Construct the stability index for a crate being compiled.
240 pub fn build(&mut self, tcx: &ty::ctxt<'tcx>, krate: &Crate, export_map: &PublicItems) {
241 let mut annotator = Annotator {
245 export_map: export_map,
247 annotator.annotate(ast::CRATE_NODE_ID, true, &krate.attrs, krate.span,
248 |v| visit::walk_crate(v, krate), true);
251 pub fn new(krate: &Crate) -> Index {
252 let mut is_staged_api = false;
253 for attr in &krate.attrs {
254 if &attr.name()[..] == "staged_api" {
255 match attr.node.value.node {
256 ast::MetaWord(_) => {
257 attr::mark_used(attr);
258 is_staged_api = true;
264 let mut staged_api = FnvHashMap();
265 staged_api.insert(LOCAL_CRATE, is_staged_api);
267 staged_api: staged_api,
273 /// Cross-references the feature names of unstable APIs with enabled
274 /// features and possibly prints errors. Returns a list of all
276 pub fn check_unstable_api_usage(tcx: &ty::ctxt)
277 -> FnvHashMap<InternedString, StabilityLevel> {
278 let ref active_lib_features = tcx.sess.features.borrow().declared_lib_features;
280 // Put the active features into a map for quick lookup
281 let active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
283 let mut checker = Checker {
285 active_features: active_features,
286 used_features: FnvHashMap(),
290 let krate = tcx.map.krate();
291 visit::walk_crate(&mut checker, krate);
293 let used_features = checker.used_features;
294 return used_features;
297 struct Checker<'a, 'tcx: 'a> {
298 tcx: &'a ty::ctxt<'tcx>,
299 active_features: FnvHashSet<InternedString>,
300 used_features: FnvHashMap<InternedString, StabilityLevel>,
301 // Within a block where feature gate checking can be skipped.
305 impl<'a, 'tcx> Checker<'a, 'tcx> {
306 fn check(&mut self, id: DefId, span: Span, stab: &Option<&Stability>) {
307 // Only the cross-crate scenario matters when checking unstable APIs
308 let cross_crate = !id.is_local();
313 // We don't need to check for stability - presumably compiler generated code.
314 if self.in_skip_block > 0 {
319 Some(&Stability { level: attr::Unstable {ref reason, issue}, ref feature, .. }) => {
320 self.used_features.insert(feature.clone(), Unstable);
322 if !self.active_features.contains(feature) {
323 let msg = match *reason {
324 Some(ref r) => format!("use of unstable library feature '{}': {}",
326 None => format!("use of unstable library feature '{}'", &feature)
328 emit_feature_err(&self.tcx.sess.parse_sess.span_diagnostic,
329 &feature, span, GateIssue::Library(Some(issue)), &msg);
332 Some(&Stability { ref level, ref feature, .. }) => {
333 self.used_features.insert(feature.clone(), StabilityLevel::from_attr_level(level));
335 // Stable APIs are always ok to call and deprecated APIs are
336 // handled by a lint.
339 // This is an 'unmarked' API, which should not exist
340 // in the standard library.
341 if self.tcx.sess.features.borrow().unmarked_api {
342 self.tcx.sess.span_warn(span, "use of unmarked library feature");
343 self.tcx.sess.span_note(span, "this is either a bug in the library you are \
344 using or a bug in the compiler - please \
345 report it in both places");
347 self.tcx.sess.span_err(span, "use of unmarked library feature");
348 self.tcx.sess.span_note(span, "this is either a bug in the library you are \
349 using or a bug in the compiler - please \
350 report it in both places");
351 self.tcx.sess.span_note(span, "use #![feature(unmarked_api)] in the \
352 crate attributes to override this");
359 impl<'a, 'v, 'tcx> Visitor<'v> for Checker<'a, 'tcx> {
360 fn visit_item(&mut self, item: &hir::Item) {
361 // When compiling with --test we don't enforce stability on the
362 // compiler-generated test module, demarcated with `DUMMY_SP` plus the
364 if item.span == DUMMY_SP && item.name.as_str() == "__test" { return }
366 check_item(self.tcx, item, true,
367 &mut |id, sp, stab| self.check(id, sp, stab));
368 visit::walk_item(self, item);
371 fn visit_expr(&mut self, ex: &hir::Expr) {
372 check_expr(self.tcx, ex,
373 &mut |id, sp, stab| self.check(id, sp, stab));
374 visit::walk_expr(self, ex);
377 fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
378 check_path(self.tcx, path, id,
379 &mut |id, sp, stab| self.check(id, sp, stab));
380 visit::walk_path(self, path)
383 fn visit_path_list_item(&mut self, prefix: &hir::Path, item: &hir::PathListItem) {
384 check_path_list_item(self.tcx, item,
385 &mut |id, sp, stab| self.check(id, sp, stab));
386 visit::walk_path_list_item(self, prefix, item)
389 fn visit_pat(&mut self, pat: &hir::Pat) {
390 check_pat(self.tcx, pat,
391 &mut |id, sp, stab| self.check(id, sp, stab));
392 visit::walk_pat(self, pat)
395 fn visit_block(&mut self, b: &hir::Block) {
396 let old_skip_count = self.in_skip_block;
398 hir::BlockCheckMode::PushUnstableBlock => {
399 self.in_skip_block += 1;
401 hir::BlockCheckMode::PopUnstableBlock => {
402 self.in_skip_block = self.in_skip_block.checked_sub(1).unwrap();
406 visit::walk_block(self, b);
407 self.in_skip_block = old_skip_count;
411 /// Helper for discovering nodes to check for stability
412 pub fn check_item(tcx: &ty::ctxt, item: &hir::Item, warn_about_defns: bool,
413 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
415 hir::ItemExternCrate(_) => {
416 // compiler-generated `extern crate` items have a dummy span.
417 if item.span == DUMMY_SP { return }
419 let cnum = match tcx.sess.cstore.find_extern_mod_stmt_cnum(item.id) {
423 let id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
424 maybe_do_stability_check(tcx, id, item.span, cb);
427 // For implementations of traits, check the stability of each item
428 // individually as it's possible to have a stable trait with unstable
430 hir::ItemImpl(_, _, _, Some(ref t), _, ref impl_items) => {
431 let trait_did = tcx.def_map.borrow().get(&t.ref_id).unwrap().def_id();
432 let trait_items = tcx.trait_items(trait_did);
434 for impl_item in impl_items {
435 let item = trait_items.iter().find(|item| {
436 item.name() == impl_item.name
438 if warn_about_defns {
439 maybe_do_stability_check(tcx, item.def_id(), impl_item.span, cb);
448 /// Helper for discovering nodes to check for stability
449 pub fn check_expr(tcx: &ty::ctxt, e: &hir::Expr,
450 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
452 let id = match e.node {
453 hir::ExprMethodCall(i, _, _) => {
455 let method_call = ty::MethodCall::expr(e.id);
456 tcx.tables.borrow().method_map[&method_call].def_id
458 hir::ExprField(ref base_e, ref field) => {
460 match tcx.expr_ty_adjusted(base_e).sty {
461 ty::TyStruct(def, _) => def.struct_variant().field_named(field.node).did,
462 _ => tcx.sess.span_bug(e.span,
463 "stability::check_expr: named field access on non-struct")
466 hir::ExprTupField(ref base_e, ref field) => {
468 match tcx.expr_ty_adjusted(base_e).sty {
469 ty::TyStruct(def, _) => def.struct_variant().fields[field.node].did,
470 ty::TyTuple(..) => return,
471 _ => tcx.sess.span_bug(e.span,
472 "stability::check_expr: unnamed field access on \
473 something other than a tuple or struct")
476 hir::ExprStruct(_, ref expr_fields, _) => {
477 let type_ = tcx.expr_ty(e);
479 ty::TyStruct(def, _) => {
480 // check the stability of each field that appears
481 // in the construction expression.
482 for field in expr_fields {
483 let did = def.struct_variant()
484 .field_named(field.name.node)
486 maybe_do_stability_check(tcx, did, field.span, cb);
492 // we don't look at stability attributes on
493 // struct-like enums (yet...), but it's definitely not
494 // a bug to have construct one.
495 ty::TyEnum(..) => return,
497 tcx.sess.span_bug(e.span,
498 &format!("stability::check_expr: struct construction \
499 of non-struct, type {:?}",
507 maybe_do_stability_check(tcx, id, span, cb);
510 pub fn check_path(tcx: &ty::ctxt, path: &hir::Path, id: ast::NodeId,
511 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
512 match tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
513 Some(def::DefPrimTy(..)) => {}
514 Some(def::DefSelfTy(..)) => {}
516 maybe_do_stability_check(tcx, def.def_id(), path.span, cb);
522 pub fn check_path_list_item(tcx: &ty::ctxt, item: &hir::PathListItem,
523 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
524 match tcx.def_map.borrow().get(&item.node.id()).map(|d| d.full_def()) {
525 Some(def::DefPrimTy(..)) => {}
527 maybe_do_stability_check(tcx, def.def_id(), item.span, cb);
533 pub fn check_pat(tcx: &ty::ctxt, pat: &hir::Pat,
534 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
535 debug!("check_pat(pat = {:?})", pat);
536 if is_internal(tcx, pat.span) { return; }
538 let v = match tcx.pat_ty_opt(pat) {
539 Some(&ty::TyS { sty: ty::TyStruct(def, _), .. }) => def.struct_variant(),
540 Some(_) | None => return,
544 // A Variant(..) pattern `hir::PatEnum(_, None)` doesn't have to be recursed into.
545 hir::PatEnum(_, Some(ref pat_fields)) => {
546 for (field, struct_field) in pat_fields.iter().zip(&v.fields) {
547 maybe_do_stability_check(tcx, struct_field.did, field.span, cb)
551 hir::PatStruct(_, ref pat_fields, _) => {
552 for field in pat_fields {
553 let did = v.field_named(field.node.name).did;
554 maybe_do_stability_check(tcx, did, field.span, cb);
557 // everything else is fine.
562 fn maybe_do_stability_check(tcx: &ty::ctxt, id: DefId, span: Span,
563 cb: &mut FnMut(DefId, Span, &Option<&Stability>)) {
564 if !is_staged_api(tcx, id) {
565 debug!("maybe_do_stability_check: \
566 skipping id={:?} since it is not staged_api", id);
569 if is_internal(tcx, span) {
570 debug!("maybe_do_stability_check: \
571 skipping span={:?} since it is internal", span);
574 let ref stability = lookup(tcx, id);
575 debug!("maybe_do_stability_check: \
576 inspecting id={:?} span={:?} of stability={:?}", id, span, stability);
577 cb(id, span, stability);
580 fn is_internal(tcx: &ty::ctxt, span: Span) -> bool {
581 tcx.sess.codemap().span_allows_unstable(span)
584 fn is_staged_api(tcx: &ty::ctxt, id: DefId) -> bool {
585 match tcx.trait_item_of_item(id) {
586 Some(ty::MethodTraitItemId(trait_method_id))
587 if trait_method_id != id => {
588 is_staged_api(tcx, trait_method_id)
591 *tcx.stability.borrow_mut().staged_api.entry(id.krate).or_insert_with(
592 || csearch::is_staged_api(&tcx.sess.cstore, id.krate))
597 /// Lookup the stability for a node, loading external crate
598 /// metadata as necessary.
599 pub fn lookup<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
600 if let Some(st) = tcx.stability.borrow().map.get(&id) {
604 let st = lookup_uncached(tcx, id);
605 tcx.stability.borrow_mut().map.insert(id, st);
609 fn lookup_uncached<'tcx>(tcx: &ty::ctxt<'tcx>, id: DefId) -> Option<&'tcx Stability> {
610 debug!("lookup(id={:?})", id);
612 // is this definition the implementation of a trait method?
613 match tcx.trait_item_of_item(id) {
614 Some(ty::MethodTraitItemId(trait_method_id)) if trait_method_id != id => {
615 debug!("lookup: trait_method_id={:?}", trait_method_id);
616 return lookup(tcx, trait_method_id)
621 let item_stab = if id.is_local() {
622 None // The stability cache is filled partially lazily
624 csearch::get_stability(&tcx.sess.cstore, id).map(|st| tcx.intern_stability(st))
627 item_stab.or_else(|| {
629 if let Some(trait_id) = tcx.trait_id_of_impl(id) {
630 // FIXME (#18969): for the time being, simply use the
631 // stability of the trait to determine the stability of any
632 // unmarked impls for it. See FIXME above for more details.
634 debug!("lookup: trait_id={:?}", trait_id);
635 return lookup(tcx, trait_id);
642 /// Given the list of enabled features that were not language features (i.e. that
643 /// were expected to be library features), and the list of features used from
644 /// libraries, identify activated features that don't exist and error about them.
645 pub fn check_unused_or_stable_features(sess: &Session,
646 lib_features_used: &FnvHashMap<InternedString,
648 let ref declared_lib_features = sess.features.borrow().declared_lib_features;
649 let mut remaining_lib_features: FnvHashMap<InternedString, Span>
650 = declared_lib_features.clone().into_iter().collect();
652 let stable_msg = "this feature is stable. attribute no longer needed";
654 for &span in &sess.features.borrow().declared_stable_lang_features {
655 sess.add_lint(lint::builtin::STABLE_FEATURES,
658 stable_msg.to_string());
661 for (used_lib_feature, level) in lib_features_used {
662 match remaining_lib_features.remove(used_lib_feature) {
664 if *level == Stable {
665 sess.add_lint(lint::builtin::STABLE_FEATURES,
668 stable_msg.to_string());
671 None => ( /* used but undeclared, handled during the previous ast visit */ )
675 for &span in remaining_lib_features.values() {
676 sess.add_lint(lint::builtin::UNUSED_FEATURES,
679 "unused or unknown feature".to_string());