Skip to main content

rustc_incremental/persist/
clean.rs

1//! Debugging code to test fingerprints computed for query results. For each node marked with
2//! `#[rustc_clean]` we will compare the fingerprint from the current and from the previous
3//! compilation session as appropriate:
4//!
5//! - `#[rustc_clean(cfg="rev2", except="typeck")]` if we are
6//!   in `#[cfg(rev2)]`, then the fingerprints associated with
7//!   `DepNode::typeck(X)` must be DIFFERENT (`X` is the `DefId` of the
8//!   current node).
9//! - `#[rustc_clean(cfg="rev2")]` same as above, except that the
10//!   fingerprints must be the SAME (along with all other fingerprints).
11//!
12//! - `#[rustc_clean(cfg="rev2", loaded_from_disk="typeck")]` asserts that
13//!   the query result for `DepNode::typeck(X)` was actually
14//!   loaded from disk (not just marked green). This can be useful
15//!   to ensure that a test is actually exercising the deserialization
16//!   logic for a particular query result. This can be combined with
17//!   `except`
18//!
19//! Errors are reported if we are in the suitable configuration but
20//! the required condition is not met.
21
22use rustc_data_structures::fx::FxHashSet;
23use rustc_data_structures::unord::UnordSet;
24use rustc_hir::attrs::{AttributeKind, RustcCleanAttribute};
25use rustc_hir::def_id::LocalDefId;
26use rustc_hir::{
27    Attribute, ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind, find_attr,
28    intravisit,
29};
30use rustc_middle::dep_graph::{DepKind, DepNode, dep_kind_from_label};
31use rustc_middle::hir::nested_filter;
32use rustc_middle::ty::TyCtxt;
33use rustc_span::{Span, Symbol};
34use tracing::debug;
35
36use crate::diagnostics;
37
38// Base and Extra labels to build up the labels
39
40/// For typedef, constants, and statics
41const BASE_CONST: &[DepKind] = &[DepKind::type_of];
42
43/// DepNodes for functions + methods
44const BASE_FN: &[DepKind] = &[
45    // Callers will depend on the signature of these items, so we better test
46    DepKind::fn_sig,
47    DepKind::generics_of,
48    DepKind::clauses_of,
49    DepKind::type_of,
50    // And a big part of compilation (that we eventually want to cache) is type inference
51    // information:
52    DepKind::typeck_root,
53];
54
55/// DepNodes for Hir, which is pretty much everything
56const BASE_HIR: &[DepKind] = &[
57    // hir_owner should be computed for all nodes
58    DepKind::hir_owner,
59];
60
61/// `impl` implementation of struct/trait
62const BASE_IMPL: &[DepKind] =
63    &[DepKind::associated_item_def_ids, DepKind::generics_of, DepKind::impl_trait_header];
64
65/// DepNodes for exported mir bodies, which is relevant in "executable"
66/// code, i.e., functions+methods
67const BASE_MIR: &[DepKind] = &[DepKind::optimized_mir, DepKind::promoted_mir];
68
69/// Struct, Enum and Union DepNodes
70///
71/// Note that changing the type of a field does not change the type of the struct or enum, but
72/// adding/removing fields or changing a fields name or visibility does.
73const BASE_STRUCT: &[DepKind] = &[DepKind::generics_of, DepKind::clauses_of, DepKind::type_of];
74
75/// Trait definition `DepNode`s.
76/// Extra `DepNode`s for functions and methods.
77const EXTRA_ASSOCIATED: &[DepKind] = &[DepKind::associated_item];
78
79const EXTRA_TRAIT: &[DepKind] = &[];
80
81// Fully Built Labels
82
83const LABELS_CONST: &[&[DepKind]] = &[BASE_HIR, BASE_CONST];
84
85/// Constant/Typedef in an impl
86const LABELS_CONST_IN_IMPL: &[&[DepKind]] = &[BASE_HIR, BASE_CONST, EXTRA_ASSOCIATED];
87
88/// Trait-Const/Typedef DepNodes
89const LABELS_CONST_IN_TRAIT: &[&[DepKind]] = &[BASE_HIR, BASE_CONST, EXTRA_ASSOCIATED, EXTRA_TRAIT];
90
91/// Function `DepNode`s.
92const LABELS_FN: &[&[DepKind]] = &[BASE_HIR, BASE_MIR, BASE_FN];
93
94/// Method `DepNode`s.
95const LABELS_FN_IN_IMPL: &[&[DepKind]] = &[BASE_HIR, BASE_MIR, BASE_FN, EXTRA_ASSOCIATED];
96
97/// Trait method `DepNode`s.
98const LABELS_FN_IN_TRAIT: &[&[DepKind]] =
99    &[BASE_HIR, BASE_MIR, BASE_FN, EXTRA_ASSOCIATED, EXTRA_TRAIT];
100
101/// For generic cases like inline-assembly, modules, etc.
102const LABELS_HIR_ONLY: &[&[DepKind]] = &[BASE_HIR];
103
104/// Impl `DepNode`s.
105const LABELS_TRAIT: &[&[DepKind]] =
106    &[BASE_HIR, &[DepKind::associated_item_def_ids, DepKind::clauses_of, DepKind::generics_of]];
107
108/// Impl `DepNode`s.
109const LABELS_IMPL: &[&[DepKind]] = &[BASE_HIR, BASE_IMPL];
110
111/// Abstract data type (struct, enum, union) `DepNode`s.
112const LABELS_ADT: &[&[DepKind]] = &[BASE_HIR, BASE_STRUCT];
113
114// FIXME: Struct/Enum/Unions Fields (there is currently no way to attach these)
115//
116// Fields are kind of separate from their containers, as they can change independently from
117// them. We should at least check
118//
119//     type_of for these.
120
121type Labels = UnordSet<String>;
122
123/// Represents the requested configuration by rustc_clean
124struct Assertion {
125    clean: Labels,
126    dirty: Labels,
127    loaded_from_disk: Labels,
128}
129
130pub(crate) fn check_clean_annotations(tcx: TyCtxt<'_>) {
131    if !tcx.sess.opts.unstable_opts.query_dep_graph {
132        return;
133    }
134
135    // can't add `#[rustc_clean]` etc without opting into this feature
136    if !tcx.features().rustc_attrs() {
137        return;
138    }
139
140    tcx.dep_graph.with_ignore(|| {
141        let mut clean_visitor = CleanVisitor { tcx, checked_attrs: Default::default() };
142
143        let crate_items = tcx.hir_crate_items(());
144
145        for id in crate_items.free_items() {
146            clean_visitor.check_item(id.owner_id.def_id);
147        }
148
149        for id in crate_items.trait_items() {
150            clean_visitor.check_item(id.owner_id.def_id);
151        }
152
153        for id in crate_items.impl_items() {
154            clean_visitor.check_item(id.owner_id.def_id);
155        }
156
157        for id in crate_items.foreign_items() {
158            clean_visitor.check_item(id.owner_id.def_id);
159        }
160
161        let mut all_attrs = FindAllAttrs { tcx, found_attrs: ::alloc::vec::Vec::new()vec![] };
162        tcx.hir_walk_attributes(&mut all_attrs);
163
164        // Note that we cannot use the existing "unused attribute"-infrastructure
165        // here, since that is running before codegen. This is also the reason why
166        // all codegen-specific attributes are `AssumedUsed` in rustc_ast::feature_gate.
167        all_attrs.report_unchecked_attrs(clean_visitor.checked_attrs);
168    })
169}
170
171struct CleanVisitor<'tcx> {
172    tcx: TyCtxt<'tcx>,
173    checked_attrs: FxHashSet<Span>,
174}
175
176impl<'tcx> CleanVisitor<'tcx> {
177    /// Convert the attribute to an [`Assertion`] if the relevant cfg is active
178    fn assertion_maybe(
179        &mut self,
180        item_id: LocalDefId,
181        attr: &RustcCleanAttribute,
182    ) -> Option<Assertion> {
183        self.tcx.sess.config.contains(&(attr.cfg, None)).then(|| self.assertion_auto(item_id, attr))
184    }
185
186    /// Gets the "auto" assertion on pre-validated attr, along with the `except` labels.
187    fn assertion_auto(&mut self, item_id: LocalDefId, attr: &RustcCleanAttribute) -> Assertion {
188        let (name, mut auto) = self.auto_labels(item_id, attr.span);
189        let except = self.except(attr);
190        let loaded_from_disk = self.loaded_from_disk(attr);
191        for e in except.items().into_sorted_stable_ord() {
192            if !auto.remove(e) {
193                self.tcx.dcx().emit_fatal(diagnostics::AssertionAuto { span: attr.span, name, e });
194            }
195        }
196        Assertion { clean: auto, dirty: except, loaded_from_disk }
197    }
198
199    /// `loaded_from_disk=` attribute value
200    fn loaded_from_disk(&self, attr: &RustcCleanAttribute) -> Labels {
201        attr.loaded_from_disk
202            .as_ref()
203            .map(|queries| self.resolve_labels(&queries.entries, queries.span))
204            .unwrap_or_default()
205    }
206
207    /// `except=` attribute value
208    fn except(&self, attr: &RustcCleanAttribute) -> Labels {
209        attr.except
210            .as_ref()
211            .map(|queries| self.resolve_labels(&queries.entries, queries.span))
212            .unwrap_or_default()
213    }
214
215    /// Return all DepNode labels that should be asserted for this item.
216    /// index=0 is the "name" used for error messages
217    fn auto_labels(&mut self, item_id: LocalDefId, span: Span) -> (&'static str, Labels) {
218        let node = self.tcx.hir_node_by_def_id(item_id);
219        let (name, labels) = match node {
220            HirNode::Item(item) => {
221                match item.kind {
222                    // note: these are in the same order as hir::Item_;
223                    // FIXME(michaelwoerister): do commented out ones
224
225                    // // An `extern crate` item, with optional original crate name,
226                    // HirItem::ExternCrate(..),  // intentionally no assertions
227
228                    // // `use foo::bar::*;` or `use foo::bar::baz as quux;`
229                    // HirItem::Use(..),  // intentionally no assertions
230
231                    // A `static` item
232                    HirItem::Static(..) => ("ItemStatic", LABELS_CONST),
233
234                    // A `const` item
235                    HirItem::Const(..) => ("ItemConst", LABELS_CONST),
236
237                    // A function declaration
238                    HirItem::Fn { .. } => ("ItemFn", LABELS_FN),
239
240                    // // A module
241                    HirItem::Mod(..) => ("ItemMod", LABELS_HIR_ONLY),
242
243                    // // An external module
244                    HirItem::ForeignMod { .. } => ("ItemForeignMod", LABELS_HIR_ONLY),
245
246                    // Module-level inline assembly (from global_asm!)
247                    HirItem::GlobalAsm { .. } => ("ItemGlobalAsm", LABELS_HIR_ONLY),
248
249                    // A type alias, e.g., `type Foo = Bar<u8>`
250                    HirItem::TyAlias(..) => ("ItemTy", LABELS_HIR_ONLY),
251
252                    // An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`
253                    HirItem::Enum(..) => ("ItemEnum", LABELS_ADT),
254
255                    // A struct definition, e.g., `struct Foo<A> {x: A}`
256                    HirItem::Struct(..) => ("ItemStruct", LABELS_ADT),
257
258                    // A union definition, e.g., `union Foo<A, B> {x: A, y: B}`
259                    HirItem::Union(..) => ("ItemUnion", LABELS_ADT),
260
261                    // Represents a Trait Declaration
262                    HirItem::Trait { .. } => ("ItemTrait", LABELS_TRAIT),
263
264                    // An implementation, eg `impl<A> Trait for Foo { .. }`
265                    HirItem::Impl { .. } => ("ItemKind::Impl", LABELS_IMPL),
266
267                    _ => self.tcx.dcx().emit_fatal(diagnostics::UndefinedCleanDirtyItem {
268                        span,
269                        kind: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", item.kind))
    })format!("{:?}", item.kind),
270                    }),
271                }
272            }
273            HirNode::TraitItem(item) => match item.kind {
274                TraitItemKind::Fn(..) => ("Node::TraitItem", LABELS_FN_IN_TRAIT),
275                TraitItemKind::Const(..) => ("NodeTraitConst", LABELS_CONST_IN_TRAIT),
276                TraitItemKind::Type(..) => ("NodeTraitType", LABELS_CONST_IN_TRAIT),
277            },
278            HirNode::ImplItem(item) => match item.kind {
279                ImplItemKind::Fn(..) => ("Node::ImplItem", LABELS_FN_IN_IMPL),
280                ImplItemKind::Const(..) => ("NodeImplConst", LABELS_CONST_IN_IMPL),
281                ImplItemKind::Type(..) => ("NodeImplType", LABELS_CONST_IN_IMPL),
282            },
283            _ => self
284                .tcx
285                .dcx()
286                .emit_fatal(diagnostics::UndefinedCleanDirty { span, kind: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", node))
    })format!("{node:?}") }),
287        };
288        let labels =
289            Labels::from_iter(labels.iter().flat_map(|s| s.iter().map(|l| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", l))
    })format!("{l:?}"))));
290        (name, labels)
291    }
292
293    fn resolve_labels(&self, values: &[Symbol], span: Span) -> Labels {
294        let mut out = Labels::default();
295        for label in values {
296            let label_str = label.as_str();
297            if DepNode::has_label_string(label_str) {
298                if out.contains(label_str) {
299                    self.tcx
300                        .dcx()
301                        .emit_fatal(diagnostics::RepeatedDepNodeLabel { span, label: label_str });
302                }
303                out.insert(label_str.to_string());
304            } else {
305                self.tcx
306                    .dcx()
307                    .emit_fatal(diagnostics::UnrecognizedDepNodeLabel { span, label: label_str });
308            }
309        }
310        out
311    }
312
313    fn dep_node_str(&self, dep_node: &DepNode) -> String {
314        if let Some(def_id) = dep_node.extract_def_id(self.tcx) {
315            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}({1})", dep_node.kind,
                self.tcx.def_path_str(def_id)))
    })format!("{:?}({})", dep_node.kind, self.tcx.def_path_str(def_id))
316        } else {
317            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}({1:?})", dep_node.kind,
                dep_node.key_fingerprint))
    })format!("{:?}({:?})", dep_node.kind, dep_node.key_fingerprint)
318        }
319    }
320
321    fn assert_dirty(&self, item_span: Span, dep_node: DepNode) {
322        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_incremental/src/persist/clean.rs:322",
                        "rustc_incremental::persist::clean",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_incremental/src/persist/clean.rs"),
                        ::tracing_core::__macro_support::Option::Some(322u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::clean"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("assert_dirty({0:?})",
                                                    dep_node) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("assert_dirty({:?})", dep_node);
323
324        if self.tcx.dep_graph.is_green(&dep_node) {
325            let dep_node_str = self.dep_node_str(&dep_node);
326            self.tcx
327                .dcx()
328                .emit_err(diagnostics::NotDirty { span: item_span, dep_node_str: &dep_node_str });
329        }
330    }
331
332    fn assert_clean(&self, item_span: Span, dep_node: DepNode) {
333        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_incremental/src/persist/clean.rs:333",
                        "rustc_incremental::persist::clean",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_incremental/src/persist/clean.rs"),
                        ::tracing_core::__macro_support::Option::Some(333u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::clean"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("assert_clean({0:?})",
                                                    dep_node) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("assert_clean({:?})", dep_node);
334
335        if self.tcx.dep_graph.is_red(&dep_node) {
336            let dep_node_str = self.dep_node_str(&dep_node);
337            self.tcx
338                .dcx()
339                .emit_err(diagnostics::NotClean { span: item_span, dep_node_str: &dep_node_str });
340        }
341    }
342
343    fn check_item(&mut self, item_id: LocalDefId) {
344        let item_span = self.tcx.def_span(item_id.to_def_id());
345        let def_path_hash = self.tcx.def_path_hash(item_id.to_def_id());
346
347        let Some(clean_attrs) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(item_id, &self.tcx)
                {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcClean(attr)) => {
                        break 'done Some(attr);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(self.tcx, item_id, RustcClean(attr) => attr) else {
348            return;
349        };
350
351        for attr in clean_attrs {
352            let Some(assertion) = self.assertion_maybe(item_id, attr) else {
353                continue;
354            };
355            self.checked_attrs.insert(attr.span);
356            for label in assertion.clean.items().into_sorted_stable_ord() {
357                let dep_node = DepNode::from_label_string(self.tcx, label, def_path_hash).unwrap();
358                self.assert_clean(item_span, dep_node);
359            }
360            for label in assertion.dirty.items().into_sorted_stable_ord() {
361                let dep_node = DepNode::from_label_string(self.tcx, label, def_path_hash).unwrap();
362                self.assert_dirty(item_span, dep_node);
363            }
364            for label in assertion.loaded_from_disk.items().into_sorted_stable_ord() {
365                match DepNode::from_label_string(self.tcx, label, def_path_hash) {
366                    Ok(dep_node) => {
367                        if !self.tcx.dep_graph.debug_was_loaded_from_disk(dep_node) {
368                            let dep_node_str = self.dep_node_str(&dep_node);
369                            self.tcx.dcx().emit_err(diagnostics::NotLoaded {
370                                span: item_span,
371                                dep_node_str: &dep_node_str,
372                            });
373                        }
374                    }
375                    // Opaque/unit hash, we only know the dep kind
376                    Err(()) => {
377                        let dep_kind = dep_kind_from_label(label);
378                        if !self.tcx.dep_graph.debug_dep_kind_was_loaded_from_disk(dep_kind) {
379                            self.tcx.dcx().emit_err(diagnostics::NotLoaded {
380                                span: item_span,
381                                dep_node_str: &label,
382                            });
383                        }
384                    }
385                }
386            }
387        }
388    }
389}
390
391/// A visitor that collects all `#[rustc_clean]` attributes from
392/// the HIR. It is used to verify that we really ran checks for all annotated
393/// nodes.
394struct FindAllAttrs<'tcx> {
395    tcx: TyCtxt<'tcx>,
396    found_attrs: Vec<&'tcx RustcCleanAttribute>,
397}
398
399impl<'tcx> FindAllAttrs<'tcx> {
400    fn is_active_attr(&self, attr: &RustcCleanAttribute) -> bool {
401        self.tcx.sess.config.contains(&(attr.cfg, None))
402    }
403
404    fn report_unchecked_attrs(&self, mut checked_attrs: FxHashSet<Span>) {
405        for attr in &self.found_attrs {
406            if !checked_attrs.contains(&attr.span) {
407                self.tcx.dcx().emit_err(diagnostics::UncheckedClean { span: attr.span });
408                checked_attrs.insert(attr.span);
409            }
410        }
411    }
412}
413
414impl<'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'tcx> {
415    type NestedFilter = nested_filter::All;
416
417    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
418        self.tcx
419    }
420
421    fn visit_attribute(&mut self, attr: &'tcx Attribute) {
422        if let Attribute::Parsed(AttributeKind::RustcClean(attrs)) = attr {
423            for attr in attrs {
424                if self.is_active_attr(attr) {
425                    self.found_attrs.push(attr);
426                }
427            }
428        }
429    }
430}