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 //! Debugging code to test fingerprints computed for query results.
12 //! For each node marked with `#[rustc_clean]` or `#[rustc_dirty]`,
13 //! we will compare the fingerprint from the current and from the previous
14 //! compilation session as appropriate:
16 //! - `#[rustc_clean(cfg="rev2", except="TypeckTables")]` if we are
17 //! in `#[cfg(rev2)]`, then the fingerprints associated with
18 //! `DepNode::TypeckTables(X)` must be DIFFERENT (`X` is the def-id of the
20 //! - `#[rustc_clean(cfg="rev2")]` same as above, except that the
21 //! fingerprints must be the SAME (along with all other fingerprints).
23 //! Errors are reported if we are in the suitable configuration but
24 //! the required condition is not met.
27 use std::iter::FromIterator;
29 use rustc::dep_graph::{DepNode, label_strs};
31 use rustc::hir::{ItemKind as HirItem, ImplItemKind, TraitItemKind};
32 use rustc::hir::Node as HirNode;
33 use rustc::hir::def_id::DefId;
34 use rustc::hir::itemlikevisit::ItemLikeVisitor;
35 use rustc::hir::intravisit;
36 use rustc::ich::{ATTR_DIRTY, ATTR_CLEAN};
37 use syntax::ast::{self, Attribute, NestedMetaItem};
38 use rustc_data_structures::fx::FxHashSet;
40 use rustc::ty::TyCtxt;
42 const EXCEPT: &str = "except";
43 const LABEL: &str = "label";
44 const CFG: &str = "cfg";
46 // Base and Extra labels to build up the labels
48 /// For typedef, constants, and statics
49 const BASE_CONST: &[&str] = &[
50 label_strs::TypeOfItem,
53 /// DepNodes for functions + methods
54 const BASE_FN: &[&str] = &[
55 // Callers will depend on the signature of these items, so we better test
56 label_strs::FnSignature,
57 label_strs::GenericsOfItem,
58 label_strs::PredicatesOfItem,
59 label_strs::TypeOfItem,
61 // And a big part of compilation (that we eventually want to cache) is type inference
63 label_strs::TypeckTables,
66 /// DepNodes for Hir, which is pretty much everything
67 const BASE_HIR: &[&str] = &[
68 // Hir and HirBody should be computed for all nodes
73 /// `impl` implementation of struct/trait
74 const BASE_IMPL: &[&str] = &[
75 label_strs::AssociatedItemDefIds,
76 label_strs::GenericsOfItem,
77 label_strs::ImplTraitRef,
80 /// DepNodes for MirValidated/Optimized, which is relevant in "executable"
81 /// code, i.e. functions+methods
82 const BASE_MIR: &[&str] = &[
83 label_strs::MirOptimized,
84 label_strs::MirValidated,
87 /// Struct, Enum and Union DepNodes
89 /// Note that changing the type of a field does not change the type of the struct or enum, but
90 /// adding/removing fields or changing a fields name or visibility does.
91 const BASE_STRUCT: &[&str] = &[
92 label_strs::GenericsOfItem,
93 label_strs::PredicatesOfItem,
94 label_strs::TypeOfItem,
97 /// Trait Definition DepNodes
98 const BASE_TRAIT_DEF: &[&str] = &[
99 label_strs::AssociatedItemDefIds,
100 label_strs::GenericsOfItem,
101 label_strs::ObjectSafety,
102 label_strs::PredicatesOfItem,
103 label_strs::SpecializationGraph,
104 label_strs::TraitDefOfItem,
105 label_strs::TraitImpls,
108 /// extra DepNodes for methods (+fn)
109 const EXTRA_ASSOCIATED: &[&str] = &[
110 label_strs::AssociatedItems,
113 const EXTRA_TRAIT: &[&str] = &[
114 label_strs::TraitOfItem,
117 // Fully Built Labels
119 const LABELS_CONST: &[&[&str]] = &[
124 /// Constant/Typedef in an impl
125 const LABELS_CONST_IN_IMPL: &[&[&str]] = &[
131 /// Trait-Const/Typedef DepNodes
132 const LABELS_CONST_IN_TRAIT: &[&[&str]] = &[
140 const LABELS_FN: &[&[&str]] = &[
147 const LABELS_FN_IN_IMPL: &[&[&str]] = &[
154 /// Trait-Method DepNodes
155 const LABELS_FN_IN_TRAIT: &[&[&str]] = &[
163 /// For generic cases like inline-assembly/mod/etc
164 const LABELS_HIR_ONLY: &[&[&str]] = &[
169 const LABELS_IMPL: &[&[&str]] = &[
174 /// Abstract Data Type (Struct, Enum, Unions) DepNodes
175 const LABELS_ADT: &[&[&str]] = &[
180 /// Trait Definition DepNodes
182 const LABELS_TRAIT: &[&[&str]] = &[
188 // FIXME: Struct/Enum/Unions Fields (there is currently no way to attach these)
190 // Fields are kind of separate from their containers, as they can change independently from
191 // them. We should at least check
193 // TypeOfItem for these.
195 type Labels = FxHashSet<String>;
197 /// Represents the requested configuration by rustc_clean/dirty
204 fn from_clean_labels(labels: Labels) -> Assertion {
207 dirty: Labels::default(),
211 fn from_dirty_labels(labels: Labels) -> Assertion {
213 clean: Labels::default(),
219 pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
220 // can't add `#[rustc_dirty]` etc without opting in to this feature
221 if !tcx.features().rustc_attrs {
225 tcx.dep_graph.with_ignore(|| {
226 let krate = tcx.hir().krate();
227 let mut dirty_clean_visitor = DirtyCleanVisitor {
229 checked_attrs: Default::default(),
231 krate.visit_all_item_likes(&mut dirty_clean_visitor);
233 let mut all_attrs = FindAllAttrs {
235 attr_names: vec![ATTR_DIRTY, ATTR_CLEAN],
238 intravisit::walk_crate(&mut all_attrs, krate);
240 // Note that we cannot use the existing "unused attribute"-infrastructure
241 // here, since that is running before codegen. This is also the reason why
242 // all codegen-specific attributes are `Whitelisted` in syntax::feature_gate.
243 all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs);
247 pub struct DirtyCleanVisitor<'a, 'tcx:'a> {
248 tcx: TyCtxt<'a, 'tcx, 'tcx>,
249 checked_attrs: FxHashSet<ast::AttrId>,
252 impl<'a, 'tcx> DirtyCleanVisitor<'a, 'tcx> {
254 /// Possibly "deserialize" the attribute into a clean/dirty assertion
255 fn assertion_maybe(&mut self, item_id: ast::NodeId, attr: &Attribute)
258 let is_clean = if attr.check_name(ATTR_DIRTY) {
260 } else if attr.check_name(ATTR_CLEAN) {
263 // skip: not rustc_clean/dirty
266 if !check_config(self.tcx, attr) {
267 // skip: not the correct `cfg=`
270 let assertion = if let Some(labels) = self.labels(attr) {
272 Assertion::from_clean_labels(labels)
274 Assertion::from_dirty_labels(labels)
277 self.assertion_auto(item_id, attr, is_clean)
282 /// Get the "auto" assertion on pre-validated attr, along with the `except` labels
283 fn assertion_auto(&mut self, item_id: ast::NodeId, attr: &Attribute, is_clean: bool)
286 let (name, mut auto) = self.auto_labels(item_id, attr);
287 let except = self.except(attr);
288 for e in except.iter() {
291 "`except` specified DepNodes that can not be affected for \"{}\": \"{}\"",
295 self.tcx.sess.span_fatal(attr.span, &msg);
311 fn labels(&self, attr: &Attribute) -> Option<Labels> {
312 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
313 if item.check_name(LABEL) {
314 let value = expect_associated_value(self.tcx, &item);
315 return Some(self.resolve_labels(&item, value.as_str().as_ref()));
321 /// `except=` attribute value
322 fn except(&self, attr: &Attribute) -> Labels {
323 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
324 if item.check_name(EXCEPT) {
325 let value = expect_associated_value(self.tcx, &item);
326 return self.resolve_labels(&item, value.as_str().as_ref());
329 // if no `label` or `except` is given, only the node's group are asserted
333 /// Return all DepNode labels that should be asserted for this item.
334 /// index=0 is the "name" used for error messages
335 fn auto_labels(&mut self, item_id: ast::NodeId, attr: &Attribute) -> (&'static str, Labels) {
336 let node = self.tcx.hir().get(item_id);
337 let (name, labels) = match node {
338 HirNode::Item(item) => {
340 // note: these are in the same order as hir::Item_;
341 // FIXME(michaelwoerister): do commented out ones
343 // // An `extern crate` item, with optional original crate name,
344 // HirItem::ExternCrate(..), // intentionally no assertions
346 // // `use foo::bar::*;` or `use foo::bar::baz as quux;`
347 // HirItem::Use(..), // intentionally no assertions
350 HirItem::Static(..) => ("ItemStatic", LABELS_CONST),
353 HirItem::Const(..) => ("ItemConst", LABELS_CONST),
355 // A function declaration
356 HirItem::Fn(..) => ("ItemFn", LABELS_FN),
359 HirItem::Mod(..) =>("ItemMod", LABELS_HIR_ONLY),
361 // // An external module
362 HirItem::ForeignMod(..) => ("ItemForeignMod", LABELS_HIR_ONLY),
364 // Module-level inline assembly (from global_asm!)
365 HirItem::GlobalAsm(..) => ("ItemGlobalAsm", LABELS_HIR_ONLY),
367 // A type alias, e.g. `type Foo = Bar<u8>`
368 HirItem::Ty(..) => ("ItemTy", LABELS_HIR_ONLY),
370 // An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
371 HirItem::Enum(..) => ("ItemEnum", LABELS_ADT),
373 // A struct definition, e.g. `struct Foo<A> {x: A}`
374 HirItem::Struct(..) => ("ItemStruct", LABELS_ADT),
376 // A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
377 HirItem::Union(..) => ("ItemUnion", LABELS_ADT),
379 // Represents a Trait Declaration
380 // FIXME(michaelwoerister): trait declaration is buggy because sometimes some of
381 // the depnodes don't exist (because they legitametely didn't need to be
384 // michaelwoerister and vitiral came up with a possible solution,
385 // to just do this before every query
387 // ::rustc::ty::query::plumbing::force_from_dep_node(tcx, dep_node)
390 // However, this did not seem to work effectively and more bugs were hit.
391 // Nebie @vitiral gave up :)
393 //HirItem::Trait(..) => ("ItemTrait", LABELS_TRAIT),
395 // An implementation, eg `impl<A> Trait for Foo { .. }`
396 HirItem::Impl(..) => ("ItemKind::Impl", LABELS_IMPL),
398 _ => self.tcx.sess.span_fatal(
401 "clean/dirty auto-assertions not yet defined \
402 for Node::Item.node={:?}",
408 HirNode::TraitItem(item) => {
410 TraitItemKind::Method(..) => ("Node::TraitItem", LABELS_FN_IN_TRAIT),
411 TraitItemKind::Const(..) => ("NodeTraitConst", LABELS_CONST_IN_TRAIT),
412 TraitItemKind::Type(..) => ("NodeTraitType", LABELS_CONST_IN_TRAIT),
415 HirNode::ImplItem(item) => {
417 ImplItemKind::Method(..) => ("Node::ImplItem", LABELS_FN_IN_IMPL),
418 ImplItemKind::Const(..) => ("NodeImplConst", LABELS_CONST_IN_IMPL),
419 ImplItemKind::Type(..) => ("NodeImplType", LABELS_CONST_IN_IMPL),
420 ImplItemKind::Existential(..) => ("NodeImplType", LABELS_CONST_IN_IMPL),
423 _ => self.tcx.sess.span_fatal(
426 "clean/dirty auto-assertions not yet defined for {:?}",
431 let labels = Labels::from_iter(
432 labels.iter().flat_map(|s| s.iter().map(|l| l.to_string()))
437 fn resolve_labels(&self, item: &NestedMetaItem, value: &str) -> Labels {
438 let mut out = Labels::default();
439 for label in value.split(',') {
440 let label = label.trim();
441 if DepNode::has_label_string(label) {
442 if out.contains(label) {
443 self.tcx.sess.span_fatal(
445 &format!("dep-node label `{}` is repeated", label));
447 out.insert(label.to_string());
449 self.tcx.sess.span_fatal(
451 &format!("dep-node label `{}` not recognized", label));
461 ) -> impl Iterator<Item = DepNode> + 'l {
462 let def_path_hash = self.tcx.def_path_hash(def_id);
466 match DepNode::from_label_string(label, def_path_hash) {
467 Ok(dep_node) => dep_node,
468 Err(()) => unreachable!(),
473 fn dep_node_str(&self, dep_node: &DepNode) -> String {
474 if let Some(def_id) = dep_node.extract_def_id(self.tcx) {
477 self.tcx.item_path_str(def_id))
479 format!("{:?}({:?})", dep_node.kind, dep_node.hash)
483 fn assert_dirty(&self, item_span: Span, dep_node: DepNode) {
484 debug!("assert_dirty({:?})", dep_node);
486 let dep_node_index = self.tcx.dep_graph.dep_node_index_of(&dep_node);
487 let current_fingerprint = self.tcx.dep_graph.fingerprint_of(dep_node_index);
488 let prev_fingerprint = self.tcx.dep_graph.prev_fingerprint_of(&dep_node);
490 if Some(current_fingerprint) == prev_fingerprint {
491 let dep_node_str = self.dep_node_str(&dep_node);
492 self.tcx.sess.span_err(
494 &format!("`{}` should be dirty but is not", dep_node_str));
498 fn assert_clean(&self, item_span: Span, dep_node: DepNode) {
499 debug!("assert_clean({:?})", dep_node);
501 let dep_node_index = self.tcx.dep_graph.dep_node_index_of(&dep_node);
502 let current_fingerprint = self.tcx.dep_graph.fingerprint_of(dep_node_index);
503 let prev_fingerprint = self.tcx.dep_graph.prev_fingerprint_of(&dep_node);
505 if Some(current_fingerprint) != prev_fingerprint {
506 let dep_node_str = self.dep_node_str(&dep_node);
507 self.tcx.sess.span_err(
509 &format!("`{}` should be clean but is not", dep_node_str));
513 fn check_item(&mut self, item_id: ast::NodeId, item_span: Span) {
514 let def_id = self.tcx.hir().local_def_id(item_id);
515 for attr in self.tcx.get_attrs(def_id).iter() {
516 let assertion = match self.assertion_maybe(item_id, attr) {
520 self.checked_attrs.insert(attr.id);
521 for dep_node in self.dep_nodes(&assertion.clean, def_id) {
522 self.assert_clean(item_span, dep_node);
524 for dep_node in self.dep_nodes(&assertion.dirty, def_id) {
525 self.assert_dirty(item_span, dep_node);
531 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'a, 'tcx> {
532 fn visit_item(&mut self, item: &'tcx hir::Item) {
533 self.check_item(item.id, item.span);
536 fn visit_trait_item(&mut self, item: &hir::TraitItem) {
537 self.check_item(item.id, item.span);
540 fn visit_impl_item(&mut self, item: &hir::ImplItem) {
541 self.check_item(item.id, item.span);
545 /// Given a `#[rustc_dirty]` or `#[rustc_clean]` attribute, scan
546 /// for a `cfg="foo"` attribute and check whether we have a cfg
547 /// flag called `foo`.
549 /// Also make sure that the `label` and `except` fields do not
551 fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool {
552 debug!("check_config(attr={:?})", attr);
553 let config = &tcx.sess.parse_sess.config;
554 debug!("check_config: config={:?}", config);
555 let (mut cfg, mut except, mut label) = (None, false, false);
556 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
557 if item.check_name(CFG) {
558 let value = expect_associated_value(tcx, &item);
559 debug!("check_config: searching for cfg {:?}", value);
560 cfg = Some(config.contains(&(value, None)));
562 if item.check_name(LABEL) {
565 if item.check_name(EXCEPT) {
573 "must specify only one of: `label`, `except`"
578 None => tcx.sess.span_fatal(
586 fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name {
587 if let Some(value) = item.value_str() {
590 let msg = if let Some(name) = item.name() {
591 format!("associated value expected for `{}`", name)
593 "expected an associated value".to_string()
596 tcx.sess.span_fatal(item.span, &msg);
600 // A visitor that collects all #[rustc_dirty]/#[rustc_clean] attributes from
601 // the HIR. It is used to verfiy that we really ran checks for all annotated
603 pub struct FindAllAttrs<'a, 'tcx:'a> {
604 tcx: TyCtxt<'a, 'tcx, 'tcx>,
605 attr_names: Vec<&'static str>,
606 found_attrs: Vec<&'tcx Attribute>,
609 impl<'a, 'tcx> FindAllAttrs<'a, 'tcx> {
611 fn is_active_attr(&mut self, attr: &Attribute) -> bool {
612 for attr_name in &self.attr_names {
613 if attr.check_name(attr_name) && check_config(self.tcx, attr) {
621 fn report_unchecked_attrs(&self, checked_attrs: &FxHashSet<ast::AttrId>) {
622 for attr in &self.found_attrs {
623 if !checked_attrs.contains(&attr.id) {
624 self.tcx.sess.span_err(attr.span, &format!("found unchecked \
625 #[rustc_dirty]/#[rustc_clean] attribute"));
631 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'a, 'tcx> {
632 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
633 intravisit::NestedVisitorMap::All(&self.tcx.hir())
636 fn visit_attribute(&mut self, attr: &'tcx Attribute) {
637 if self.is_active_attr(attr) {
638 self.found_attrs.push(attr);