1 //! Debugging code to test fingerprints computed for query results.
2 //! For each node marked with `#[rustc_clean]` or `#[rustc_dirty]`,
3 //! we will compare the fingerprint from the current and from the previous
4 //! compilation session as appropriate:
6 //! - `#[rustc_clean(cfg="rev2", except="TypeckTables")]` if we are
7 //! in `#[cfg(rev2)]`, then the fingerprints associated with
8 //! `DepNode::TypeckTables(X)` must be DIFFERENT (`X` is the def-id of the
10 //! - `#[rustc_clean(cfg="rev2")]` same as above, except that the
11 //! fingerprints must be the SAME (along with all other fingerprints).
13 //! Errors are reported if we are in the suitable configuration but
14 //! the required condition is not met.
17 use std::iter::FromIterator;
19 use rustc::dep_graph::{DepNode, label_strs};
21 use rustc::hir::{ItemKind as HirItem, ImplItemKind, TraitItemKind};
22 use rustc::hir::Node as HirNode;
23 use rustc::hir::def_id::DefId;
24 use rustc::hir::itemlikevisit::ItemLikeVisitor;
25 use rustc::hir::intravisit;
26 use rustc::ich::{ATTR_DIRTY, ATTR_CLEAN};
27 use syntax::ast::{self, Attribute, NestedMetaItem};
28 use rustc_data_structures::fx::FxHashSet;
30 use rustc::ty::TyCtxt;
32 const EXCEPT: &str = "except";
33 const LABEL: &str = "label";
34 const CFG: &str = "cfg";
36 // Base and Extra labels to build up the labels
38 /// For typedef, constants, and statics
39 const BASE_CONST: &[&str] = &[
40 label_strs::TypeOfItem,
43 /// DepNodes for functions + methods
44 const BASE_FN: &[&str] = &[
45 // Callers will depend on the signature of these items, so we better test
46 label_strs::FnSignature,
47 label_strs::GenericsOfItem,
48 label_strs::PredicatesOfItem,
49 label_strs::TypeOfItem,
51 // And a big part of compilation (that we eventually want to cache) is type inference
53 label_strs::TypeckTables,
56 /// DepNodes for Hir, which is pretty much everything
57 const BASE_HIR: &[&str] = &[
58 // Hir and HirBody should be computed for all nodes
63 /// `impl` implementation of struct/trait
64 const BASE_IMPL: &[&str] = &[
65 label_strs::AssociatedItemDefIds,
66 label_strs::GenericsOfItem,
67 label_strs::ImplTraitRef,
70 /// DepNodes for MirBuilt/Optimized, which is relevant in "executable"
71 /// code, i.e., functions+methods
72 const BASE_MIR: &[&str] = &[
73 label_strs::MirOptimized,
77 /// Struct, Enum and Union DepNodes
79 /// Note that changing the type of a field does not change the type of the struct or enum, but
80 /// adding/removing fields or changing a fields name or visibility does.
81 const BASE_STRUCT: &[&str] = &[
82 label_strs::GenericsOfItem,
83 label_strs::PredicatesOfItem,
84 label_strs::TypeOfItem,
87 /// Trait Definition DepNodes
88 const BASE_TRAIT_DEF: &[&str] = &[
89 label_strs::AssociatedItemDefIds,
90 label_strs::GenericsOfItem,
91 label_strs::ObjectSafety,
92 label_strs::PredicatesOfItem,
93 label_strs::SpecializationGraph,
94 label_strs::TraitDefOfItem,
95 label_strs::TraitImpls,
98 /// extra DepNodes for methods (+fn)
99 const EXTRA_ASSOCIATED: &[&str] = &[
100 label_strs::AssociatedItems,
103 const EXTRA_TRAIT: &[&str] = &[
104 label_strs::TraitOfItem,
107 // Fully Built Labels
109 const LABELS_CONST: &[&[&str]] = &[
114 /// Constant/Typedef in an impl
115 const LABELS_CONST_IN_IMPL: &[&[&str]] = &[
121 /// Trait-Const/Typedef DepNodes
122 const LABELS_CONST_IN_TRAIT: &[&[&str]] = &[
130 const LABELS_FN: &[&[&str]] = &[
137 const LABELS_FN_IN_IMPL: &[&[&str]] = &[
144 /// Trait-Method DepNodes
145 const LABELS_FN_IN_TRAIT: &[&[&str]] = &[
153 /// For generic cases like inline-assembly/mod/etc
154 const LABELS_HIR_ONLY: &[&[&str]] = &[
159 const LABELS_IMPL: &[&[&str]] = &[
164 /// Abstract Data Type (Struct, Enum, Unions) DepNodes
165 const LABELS_ADT: &[&[&str]] = &[
170 /// Trait Definition DepNodes
172 const LABELS_TRAIT: &[&[&str]] = &[
178 // FIXME: Struct/Enum/Unions Fields (there is currently no way to attach these)
180 // Fields are kind of separate from their containers, as they can change independently from
181 // them. We should at least check
183 // TypeOfItem for these.
185 type Labels = FxHashSet<String>;
187 /// Represents the requested configuration by rustc_clean/dirty
194 fn from_clean_labels(labels: Labels) -> Assertion {
197 dirty: Labels::default(),
201 fn from_dirty_labels(labels: Labels) -> Assertion {
203 clean: Labels::default(),
209 pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
210 // can't add `#[rustc_dirty]` etc without opting in to this feature
211 if !tcx.features().rustc_attrs {
215 tcx.dep_graph.with_ignore(|| {
216 let krate = tcx.hir().krate();
217 let mut dirty_clean_visitor = DirtyCleanVisitor {
219 checked_attrs: Default::default(),
221 krate.visit_all_item_likes(&mut dirty_clean_visitor);
223 let mut all_attrs = FindAllAttrs {
225 attr_names: vec![ATTR_DIRTY, ATTR_CLEAN],
228 intravisit::walk_crate(&mut all_attrs, krate);
230 // Note that we cannot use the existing "unused attribute"-infrastructure
231 // here, since that is running before codegen. This is also the reason why
232 // all codegen-specific attributes are `Whitelisted` in syntax::feature_gate.
233 all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs);
237 pub struct DirtyCleanVisitor<'a, 'tcx:'a> {
238 tcx: TyCtxt<'a, 'tcx, 'tcx>,
239 checked_attrs: FxHashSet<ast::AttrId>,
242 impl<'a, 'tcx> DirtyCleanVisitor<'a, 'tcx> {
244 /// Possibly "deserialize" the attribute into a clean/dirty assertion
245 fn assertion_maybe(&mut self, item_id: ast::NodeId, attr: &Attribute)
248 let is_clean = if attr.check_name(ATTR_DIRTY) {
250 } else if attr.check_name(ATTR_CLEAN) {
253 // skip: not rustc_clean/dirty
256 if !check_config(self.tcx, attr) {
257 // skip: not the correct `cfg=`
260 let assertion = if let Some(labels) = self.labels(attr) {
262 Assertion::from_clean_labels(labels)
264 Assertion::from_dirty_labels(labels)
267 self.assertion_auto(item_id, attr, is_clean)
272 /// Get the "auto" assertion on pre-validated attr, along with the `except` labels
273 fn assertion_auto(&mut self, item_id: ast::NodeId, attr: &Attribute, is_clean: bool)
276 let (name, mut auto) = self.auto_labels(item_id, attr);
277 let except = self.except(attr);
278 for e in except.iter() {
281 "`except` specified DepNodes that can not be affected for \"{}\": \"{}\"",
285 self.tcx.sess.span_fatal(attr.span, &msg);
301 fn labels(&self, attr: &Attribute) -> Option<Labels> {
302 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
303 if item.check_name(LABEL) {
304 let value = expect_associated_value(self.tcx, &item);
305 return Some(self.resolve_labels(&item, value.as_str().as_ref()));
311 /// `except=` attribute value
312 fn except(&self, attr: &Attribute) -> Labels {
313 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
314 if item.check_name(EXCEPT) {
315 let value = expect_associated_value(self.tcx, &item);
316 return self.resolve_labels(&item, value.as_str().as_ref());
319 // if no `label` or `except` is given, only the node's group are asserted
323 /// Return all DepNode labels that should be asserted for this item.
324 /// index=0 is the "name" used for error messages
325 fn auto_labels(&mut self, item_id: ast::NodeId, attr: &Attribute) -> (&'static str, Labels) {
326 let node = self.tcx.hir().get(item_id);
327 let (name, labels) = match node {
328 HirNode::Item(item) => {
330 // note: these are in the same order as hir::Item_;
331 // FIXME(michaelwoerister): do commented out ones
333 // // An `extern crate` item, with optional original crate name,
334 // HirItem::ExternCrate(..), // intentionally no assertions
336 // // `use foo::bar::*;` or `use foo::bar::baz as quux;`
337 // HirItem::Use(..), // intentionally no assertions
340 HirItem::Static(..) => ("ItemStatic", LABELS_CONST),
343 HirItem::Const(..) => ("ItemConst", LABELS_CONST),
345 // A function declaration
346 HirItem::Fn(..) => ("ItemFn", LABELS_FN),
349 HirItem::Mod(..) =>("ItemMod", LABELS_HIR_ONLY),
351 // // An external module
352 HirItem::ForeignMod(..) => ("ItemForeignMod", LABELS_HIR_ONLY),
354 // Module-level inline assembly (from global_asm!)
355 HirItem::GlobalAsm(..) => ("ItemGlobalAsm", LABELS_HIR_ONLY),
357 // A type alias, e.g., `type Foo = Bar<u8>`
358 HirItem::Ty(..) => ("ItemTy", LABELS_HIR_ONLY),
360 // An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
361 HirItem::Enum(..) => ("ItemEnum", LABELS_ADT),
363 // A struct definition, e.g., `struct Foo<A> {x: A}`
364 HirItem::Struct(..) => ("ItemStruct", LABELS_ADT),
366 // A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
367 HirItem::Union(..) => ("ItemUnion", LABELS_ADT),
369 // Represents a Trait Declaration
370 // FIXME(michaelwoerister): trait declaration is buggy because sometimes some of
371 // the depnodes don't exist (because they legitametely didn't need to be
374 // michaelwoerister and vitiral came up with a possible solution,
375 // to just do this before every query
377 // ::rustc::ty::query::plumbing::force_from_dep_node(tcx, dep_node)
380 // However, this did not seem to work effectively and more bugs were hit.
381 // Nebie @vitiral gave up :)
383 //HirItem::Trait(..) => ("ItemTrait", LABELS_TRAIT),
385 // An implementation, eg `impl<A> Trait for Foo { .. }`
386 HirItem::Impl(..) => ("ItemKind::Impl", LABELS_IMPL),
388 _ => self.tcx.sess.span_fatal(
391 "clean/dirty auto-assertions not yet defined \
392 for Node::Item.node={:?}",
398 HirNode::TraitItem(item) => {
400 TraitItemKind::Method(..) => ("Node::TraitItem", LABELS_FN_IN_TRAIT),
401 TraitItemKind::Const(..) => ("NodeTraitConst", LABELS_CONST_IN_TRAIT),
402 TraitItemKind::Type(..) => ("NodeTraitType", LABELS_CONST_IN_TRAIT),
405 HirNode::ImplItem(item) => {
407 ImplItemKind::Method(..) => ("Node::ImplItem", LABELS_FN_IN_IMPL),
408 ImplItemKind::Const(..) => ("NodeImplConst", LABELS_CONST_IN_IMPL),
409 ImplItemKind::Type(..) => ("NodeImplType", LABELS_CONST_IN_IMPL),
410 ImplItemKind::Existential(..) => ("NodeImplType", LABELS_CONST_IN_IMPL),
413 _ => self.tcx.sess.span_fatal(
416 "clean/dirty auto-assertions not yet defined for {:?}",
421 let labels = Labels::from_iter(
422 labels.iter().flat_map(|s| s.iter().map(|l| l.to_string()))
427 fn resolve_labels(&self, item: &NestedMetaItem, value: &str) -> Labels {
428 let mut out = Labels::default();
429 for label in value.split(',') {
430 let label = label.trim();
431 if DepNode::has_label_string(label) {
432 if out.contains(label) {
433 self.tcx.sess.span_fatal(
435 &format!("dep-node label `{}` is repeated", label));
437 out.insert(label.to_string());
439 self.tcx.sess.span_fatal(
441 &format!("dep-node label `{}` not recognized", label));
451 ) -> impl Iterator<Item = DepNode> + 'l {
452 let def_path_hash = self.tcx.def_path_hash(def_id);
456 match DepNode::from_label_string(label, def_path_hash) {
457 Ok(dep_node) => dep_node,
458 Err(()) => unreachable!(),
463 fn dep_node_str(&self, dep_node: &DepNode) -> String {
464 if let Some(def_id) = dep_node.extract_def_id(self.tcx) {
467 self.tcx.item_path_str(def_id))
469 format!("{:?}({:?})", dep_node.kind, dep_node.hash)
473 fn assert_dirty(&self, item_span: Span, dep_node: DepNode) {
474 debug!("assert_dirty({:?})", dep_node);
476 let dep_node_index = self.tcx.dep_graph.dep_node_index_of(&dep_node);
477 let current_fingerprint = self.tcx.dep_graph.fingerprint_of(dep_node_index);
478 let prev_fingerprint = self.tcx.dep_graph.prev_fingerprint_of(&dep_node);
480 if Some(current_fingerprint) == prev_fingerprint {
481 let dep_node_str = self.dep_node_str(&dep_node);
482 self.tcx.sess.span_err(
484 &format!("`{}` should be dirty but is not", dep_node_str));
488 fn assert_clean(&self, item_span: Span, dep_node: DepNode) {
489 debug!("assert_clean({:?})", dep_node);
491 let dep_node_index = self.tcx.dep_graph.dep_node_index_of(&dep_node);
492 let current_fingerprint = self.tcx.dep_graph.fingerprint_of(dep_node_index);
493 let prev_fingerprint = self.tcx.dep_graph.prev_fingerprint_of(&dep_node);
495 if Some(current_fingerprint) != prev_fingerprint {
496 let dep_node_str = self.dep_node_str(&dep_node);
497 self.tcx.sess.span_err(
499 &format!("`{}` should be clean but is not", dep_node_str));
503 fn check_item(&mut self, item_id: ast::NodeId, item_span: Span) {
504 let def_id = self.tcx.hir().local_def_id(item_id);
505 for attr in self.tcx.get_attrs(def_id).iter() {
506 let assertion = match self.assertion_maybe(item_id, attr) {
510 self.checked_attrs.insert(attr.id);
511 for dep_node in self.dep_nodes(&assertion.clean, def_id) {
512 self.assert_clean(item_span, dep_node);
514 for dep_node in self.dep_nodes(&assertion.dirty, def_id) {
515 self.assert_dirty(item_span, dep_node);
521 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'a, 'tcx> {
522 fn visit_item(&mut self, item: &'tcx hir::Item) {
523 self.check_item(item.id, item.span);
526 fn visit_trait_item(&mut self, item: &hir::TraitItem) {
527 self.check_item(item.id, item.span);
530 fn visit_impl_item(&mut self, item: &hir::ImplItem) {
531 self.check_item(item.id, item.span);
535 /// Given a `#[rustc_dirty]` or `#[rustc_clean]` attribute, scan
536 /// for a `cfg="foo"` attribute and check whether we have a cfg
537 /// flag called `foo`.
539 /// Also make sure that the `label` and `except` fields do not
541 fn check_config(tcx: TyCtxt<'_, '_, '_>, attr: &Attribute) -> bool {
542 debug!("check_config(attr={:?})", attr);
543 let config = &tcx.sess.parse_sess.config;
544 debug!("check_config: config={:?}", config);
545 let (mut cfg, mut except, mut label) = (None, false, false);
546 for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
547 if item.check_name(CFG) {
548 let value = expect_associated_value(tcx, &item);
549 debug!("check_config: searching for cfg {:?}", value);
550 cfg = Some(config.contains(&(value, None)));
552 if item.check_name(LABEL) {
555 if item.check_name(EXCEPT) {
563 "must specify only one of: `label`, `except`"
568 None => tcx.sess.span_fatal(
576 fn expect_associated_value(tcx: TyCtxt<'_, '_, '_>, item: &NestedMetaItem) -> ast::Name {
577 if let Some(value) = item.value_str() {
580 let msg = if let Some(name) = item.name() {
581 format!("associated value expected for `{}`", name)
583 "expected an associated value".to_string()
586 tcx.sess.span_fatal(item.span, &msg);
590 // A visitor that collects all #[rustc_dirty]/#[rustc_clean] attributes from
591 // the HIR. It is used to verfiy that we really ran checks for all annotated
593 pub struct FindAllAttrs<'a, 'tcx:'a> {
594 tcx: TyCtxt<'a, 'tcx, 'tcx>,
595 attr_names: Vec<&'static str>,
596 found_attrs: Vec<&'tcx Attribute>,
599 impl<'a, 'tcx> FindAllAttrs<'a, 'tcx> {
601 fn is_active_attr(&mut self, attr: &Attribute) -> bool {
602 for attr_name in &self.attr_names {
603 if attr.check_name(attr_name) && check_config(self.tcx, attr) {
611 fn report_unchecked_attrs(&self, checked_attrs: &FxHashSet<ast::AttrId>) {
612 for attr in &self.found_attrs {
613 if !checked_attrs.contains(&attr.id) {
614 self.tcx.sess.span_err(attr.span, &format!("found unchecked \
615 #[rustc_dirty]/#[rustc_clean] attribute"));
621 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'a, 'tcx> {
622 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
623 intravisit::NestedVisitorMap::All(&self.tcx.hir())
626 fn visit_attribute(&mut self, attr: &'tcx Attribute) {
627 if self.is_active_attr(attr) {
628 self.found_attrs.push(attr);