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.
12 //! This module defines the `DepNode` type which the compiler uses to represent
13 //! nodes in the dependency graph. A `DepNode` consists of a `DepKind` (which
14 //! specifies the kind of thing it represents, like a piece of HIR, MIR, etc)
15 //! and a `Fingerprint`, a 128 bit hash value the exact meaning of which
16 //! depends on the node's `DepKind`. Together, the kind and the fingerprint
17 //! fully identify a dependency node, even across multiple compilation sessions.
18 //! In other words, the value of the fingerprint does not depend on anything
19 //! that is specific to a given compilation session, like an unpredictable
20 //! interning key (e.g. NodeId, DefId, Symbol) or the numeric value of a
21 //! pointer. The concept behind this could be compared to how git commit hashes
22 //! uniquely identify a given commit and has a few advantages:
24 //! * A `DepNode` can simply be serialized to disk and loaded in another session
25 //! without the need to do any "rebasing (like we have to do for Spans and
26 //! NodeIds) or "retracing" like we had to do for `DefId` in earlier
27 //! implementations of the dependency graph.
28 //! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to
29 //! implement `Copy`, `Sync`, `Send`, `Freeze`, etc.
30 //! * Since we just have a bit pattern, `DepNode` can be mapped from disk into
31 //! memory without any post-processing (e.g. "abomination-style" pointer
33 //! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that
34 //! refer to things that do not exist anymore. In previous implementations
35 //! `DepNode` contained a `DefId`. A `DepNode` referring to something that
36 //! had been removed between the previous and the current compilation session
37 //! could not be instantiated because the current compilation session
38 //! contained no `DefId` for thing that had been removed.
40 //! `DepNode` definition happens in the `define_dep_nodes!()` macro. This macro
41 //! defines the `DepKind` enum and a corresponding `DepConstructor` enum. The
42 //! `DepConstructor` enum links a `DepKind` to the parameters that are needed at
43 //! runtime in order to construct a valid `DepNode` fingerprint.
45 //! Because the macro sees what parameters a given `DepKind` requires, it can
46 //! "infer" some properties for each kind of `DepNode`:
48 //! * Whether a `DepNode` of a given kind has any parameters at all. Some
49 //! `DepNode`s, like `Krate`, represent global concepts with only one value.
50 //! * Whether it is possible, in principle, to reconstruct a query key from a
51 //! given `DepNode`. Many `DepKind`s only require a single `DefId` parameter,
52 //! in which case it is possible to map the node's fingerprint back to the
53 //! `DefId` it was computed from. In other cases, too much information gets
54 //! lost during fingerprint computation.
56 //! The `DepConstructor` enum, together with `DepNode::new()` ensures that only
57 //! valid `DepNode` instances can be constructed. For example, the API does not
58 //! allow for constructing parameterless `DepNode`s with anything other
59 //! than a zeroed out fingerprint. More generally speaking, it relieves the
60 //! user of the `DepNode` API of having to know how to compute the expected
61 //! fingerprint for a given set of node parameters.
63 use mir::interpret::GlobalId;
64 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
65 use hir::map::DefPathHash;
66 use hir::{HirId, ItemLocalId};
68 use ich::{Fingerprint, StableHashingContext};
69 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
72 use syntax_pos::symbol::InternedString;
75 CanonicalProjectionGoal, CanonicalTyGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpSubtypeGoal,
76 CanonicalPredicateGoal, CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpNormalizeGoal,
78 use ty::{TyCtxt, FnSig, Instance, InstanceDef,
79 ParamEnv, ParamEnvAnd, Predicate, PolyFnSig, PolyTraitRef, Ty};
80 use ty::subst::Substs;
82 // erase!() just makes tokens go away. It's used to specify which macro argument
83 // is repeated (i.e. which sub-expression of the macro we are in) but don't need
84 // to actually use any of the arguments.
89 macro_rules! replace {
90 ($x:tt with $($y:tt)*) => ($($y)*)
93 macro_rules! is_anon_attr {
95 ($attr:ident) => (false);
98 macro_rules! is_input_attr {
100 ($attr:ident) => (false);
103 macro_rules! is_eval_always_attr {
104 (eval_always) => (true);
105 ($attr:ident) => (false);
108 macro_rules! contains_anon_attr {
109 ($($attr:ident),*) => ({$(is_anon_attr!($attr) | )* false});
112 macro_rules! contains_input_attr {
113 ($($attr:ident),*) => ({$(is_input_attr!($attr) | )* false});
116 macro_rules! contains_eval_always_attr {
117 ($($attr:ident),*) => ({$(is_eval_always_attr!($attr) | )* false});
120 macro_rules! define_dep_nodes {
124 $variant:ident $(( $tuple_arg_ty:ty $(,)* ))*
125 $({ $($struct_arg_name:ident : $struct_arg_ty:ty),* })*
128 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
129 RustcEncodable, RustcDecodable)]
135 #[allow(unreachable_code)]
137 pub fn can_reconstruct_query_key<$tcx>(&self) -> bool {
140 DepKind :: $variant => {
141 if contains_anon_attr!($($attr),*) {
147 return <$tuple_arg_ty as DepNodeParams>
148 ::CAN_RECONSTRUCT_QUERY_KEY;
154 return <( $($struct_arg_ty,)* ) as DepNodeParams>
155 ::CAN_RECONSTRUCT_QUERY_KEY;
165 pub fn is_anon(&self) -> bool {
168 DepKind :: $variant => { contains_anon_attr!($($attr),*) }
174 pub fn is_input(&self) -> bool {
177 DepKind :: $variant => { contains_input_attr!($($attr),*) }
183 pub fn is_eval_always(&self) -> bool {
186 DepKind :: $variant => { contains_eval_always_attr!($($attr), *) }
191 #[allow(unreachable_code)]
193 pub fn has_params(&self) -> bool {
196 DepKind :: $variant => {
199 erase!($tuple_arg_ty);
205 $(erase!($struct_arg_name);)*
216 pub enum DepConstructor<$tcx> {
218 $variant $(( $tuple_arg_ty ))*
219 $({ $($struct_arg_name : $struct_arg_ty),* })*
223 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
224 RustcEncodable, RustcDecodable)]
227 pub hash: Fingerprint,
231 #[allow(unreachable_code, non_snake_case)]
232 pub fn new<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
233 dep: DepConstructor<'gcx>)
235 where 'gcx: 'a + 'tcx,
240 DepConstructor :: $variant $(( replace!(($tuple_arg_ty) with arg) ))*
241 $({ $($struct_arg_name),* })*
246 erase!($tuple_arg_ty);
247 let hash = DepNodeParams::to_fingerprint(&arg, tcx);
248 let dep_node = DepNode {
249 kind: DepKind::$variant,
253 if cfg!(debug_assertions) &&
254 !dep_node.kind.can_reconstruct_query_key() &&
255 (tcx.sess.opts.debugging_opts.incremental_info ||
256 tcx.sess.opts.debugging_opts.query_dep_graph)
258 tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
259 arg.to_debug_str(tcx)
268 let tupled_args = ( $($struct_arg_name,)* );
269 let hash = DepNodeParams::to_fingerprint(&tupled_args,
271 let dep_node = DepNode {
272 kind: DepKind::$variant,
276 if cfg!(debug_assertions) &&
277 !dep_node.kind.can_reconstruct_query_key() &&
278 (tcx.sess.opts.debugging_opts.incremental_info ||
279 tcx.sess.opts.debugging_opts.query_dep_graph)
281 tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
282 tupled_args.to_debug_str(tcx)
290 kind: DepKind::$variant,
291 hash: Fingerprint::ZERO,
298 /// Construct a DepNode from the given DepKind and DefPathHash. This
299 /// method will assert that the given DepKind actually requires a
300 /// single DefId/DefPathHash parameter.
302 pub fn from_def_path_hash(kind: DepKind,
303 def_path_hash: DefPathHash)
305 assert!(kind.can_reconstruct_query_key() && kind.has_params());
308 hash: def_path_hash.0,
312 /// Create a new, parameterless DepNode. This method will assert
313 /// that the DepNode corresponding to the given DepKind actually
314 /// does not require any parameters.
316 pub fn new_no_params(kind: DepKind) -> DepNode {
317 assert!(!kind.has_params());
320 hash: Fingerprint::ZERO,
324 /// Extract the DefId corresponding to this DepNode. This will work
325 /// if two conditions are met:
327 /// 1. The Fingerprint of the DepNode actually is a DefPathHash, and
328 /// 2. the item that the DefPath refers to exists in the current tcx.
330 /// Condition (1) is determined by the DepKind variant of the
331 /// DepNode. Condition (2) might not be fulfilled if a DepNode
332 /// refers to something from the previous compilation session that
333 /// has been removed.
335 pub fn extract_def_id(&self, tcx: TyCtxt<'_, '_, '_>) -> Option<DefId> {
336 if self.kind.can_reconstruct_query_key() {
337 let def_path_hash = DefPathHash(self.hash);
338 tcx.def_path_hash_to_def_id.as_ref()?
339 .get(&def_path_hash).cloned()
346 pub fn from_label_string(label: &str,
347 def_path_hash: DefPathHash)
348 -> Result<DepNode, ()> {
349 let kind = match label {
351 stringify!($variant) => DepKind::$variant,
356 if !kind.can_reconstruct_query_key() {
360 if kind.has_params() {
361 Ok(def_path_hash.to_dep_node(kind))
363 Ok(DepNode::new_no_params(kind))
368 pub fn has_label_string(label: &str) -> bool {
371 stringify!($variant) => true,
378 /// Contains variant => str representations for constructing
379 /// DepNode groups for tests.
380 #[allow(dead_code, non_upper_case_globals)]
383 pub const $variant: &'static str = stringify!($variant);
389 impl fmt::Debug for DepNode {
390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391 write!(f, "{:?}", self.kind)?;
393 if !self.kind.has_params() && !self.kind.is_anon() {
399 ::ty::tls::with_opt(|opt_tcx| {
400 if let Some(tcx) = opt_tcx {
401 if let Some(def_id) = self.extract_def_id(tcx) {
402 write!(f, "{}", tcx.def_path_debug_str(def_id))?;
403 } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*self) {
406 write!(f, "{}", self.hash)?;
409 write!(f, "{}", self.hash)?;
421 pub fn to_dep_node(self, kind: DepKind) -> DepNode {
422 DepNode::from_def_path_hash(kind, self)
428 pub fn to_dep_node(self, tcx: TyCtxt<'_, '_, '_>, kind: DepKind) -> DepNode {
429 DepNode::from_def_path_hash(kind, tcx.def_path_hash(self))
435 pub fn fingerprint_needed_for_crate_hash(self) -> bool {
438 DepKind::Krate => true,
444 define_dep_nodes!( <'tcx>
445 // We use this for most things when incr. comp. is turned off.
448 // Represents the `Krate` as a whole (the `hir::Krate` value) (as
449 // distinct from the krate module). This is basically a hash of
450 // the entire krate, so if you read from `Krate` (e.g., by calling
451 // `tcx.hir.krate()`), we will have to assume that any change
452 // means that you need to be recompiled. This is because the
453 // `Krate` value gives you access to all other items. To avoid
454 // this fate, do not call `tcx.hir.krate()`; instead, prefer
455 // wrappers like `tcx.visit_all_items_in_krate()`. If there is no
456 // suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain
457 // access to the krate, but you must remember to add suitable
458 // edges yourself for the individual items that you read.
461 // Represents the body of a function or method. The def-id is that of the
463 [input] HirBody(DefId),
465 // Represents the HIR node with the given node-id
468 // Represents metadata from an extern crate.
469 [input] CrateMetadata(CrateNum),
471 // Represents different phases in the compiler.
472 [] RegionScopeTree(DefId),
473 [eval_always] Coherence,
474 [eval_always] CoherenceInherentImplOverlapCheck,
475 [] CoherenceCheckTrait(DefId),
476 [eval_always] PrivacyAccessLevels(CrateNum),
478 // Represents the MIR for a fn; also used as the task node for
479 // things read/modify that MIR.
480 [] MirConstQualif(DefId),
483 [] MirValidated(DefId),
484 [] MirOptimized(DefId),
485 [] MirShim { instance_def: InstanceDef<'tcx> },
488 [] BorrowCheck(DefId),
489 [] MirBorrowCheck(DefId),
490 [] UnsafetyCheckResult(DefId),
491 [] UnsafeDeriveOnReprPacked(DefId),
495 [eval_always] CrateVariances,
497 // Nodes representing bits of computed IR in the tcx. Each shared
498 // table in the tcx (or elsewhere) maps to one of these
500 [] AssociatedItems(DefId),
501 [] TypeOfItem(DefId),
502 [] GenericsOfItem(DefId),
503 [] PredicatesOfItem(DefId),
504 [] ExplicitPredicatesOfItem(DefId),
505 [] PredicatesDefinedOnItem(DefId),
506 [] InferredOutlivesOf(DefId),
507 [] InferredOutlivesCrate(CrateNum),
508 [] SuperPredicatesOfItem(DefId),
509 [] TraitDefOfItem(DefId),
510 [] AdtDefOfItem(DefId),
511 [] ImplTraitRef(DefId),
512 [] ImplPolarity(DefId),
513 [] FnSignature(DefId),
514 [] CoerceUnsizedInfo(DefId),
516 [] ItemVarianceConstraints(DefId),
517 [] ItemVariances(DefId),
519 [] IsPromotableConstFn(DefId),
520 [] IsForeignItem(DefId),
521 [] TypeParamPredicates { item_id: DefId, param_id: DefId },
522 [] SizedConstraint(DefId),
523 [] DtorckConstraint(DefId),
524 [] AdtDestructor(DefId),
525 [] AssociatedItemDefIds(DefId),
526 [eval_always] InherentImpls(DefId),
527 [] TypeckBodiesKrate,
528 [] TypeckTables(DefId),
529 [] UsedTraitImports(DefId),
530 [] HasTypeckTables(DefId),
531 [] ConstEval { param_env: ParamEnvAnd<'tcx, GlobalId<'tcx>> },
532 [] CheckMatch(DefId),
533 [] SymbolName(DefId),
534 [] InstanceSymbolName { instance: Instance<'tcx> },
535 [] SpecializationGraph(DefId),
536 [] ObjectSafety(DefId),
537 [] FulfillObligation { param_env: ParamEnv<'tcx>, trait_ref: PolyTraitRef<'tcx> },
538 [] VtableMethods { trait_ref: PolyTraitRef<'tcx> },
540 [] IsCopy { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
541 [] IsSized { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
542 [] IsFreeze { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
543 [] NeedsDrop { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
544 [] Layout { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
546 // The set of impls for a given trait.
547 [] TraitImpls(DefId),
549 [input] AllLocalTraitImpls,
554 [] Environment(DefId),
555 [] DescribeDef(DefId),
557 // FIXME(mw): DefSpans are not really inputs since they are derived from
558 // HIR. But at the moment HIR hashing still contains some hacks that allow
559 // to make type debuginfo to be source location independent. Declaring
560 // DefSpan an input makes sure that changes to these are always detected
561 // regardless of HIR hashing.
562 [input] DefSpan(DefId),
563 [] LookupStability(DefId),
564 [] LookupDeprecationEntry(DefId),
565 [] ConstIsRvaluePromotableToStatic(DefId),
566 [] RvaluePromotableMap(DefId),
567 [] ImplParent(DefId),
568 [] TraitOfItem(DefId),
569 [] IsReachableNonGeneric(DefId),
570 [] IsUnreachableLocalDefinition(DefId),
571 [] IsMirAvailable(DefId),
573 [] CodegenFnAttrs(DefId),
574 [] FnArgNames(DefId),
575 [] RenderedConst(DefId),
576 [] DylibDepFormats(CrateNum),
577 [] IsPanicRuntime(CrateNum),
578 [] IsCompilerBuiltins(CrateNum),
579 [] HasGlobalAllocator(CrateNum),
580 [] HasPanicHandler(CrateNum),
581 [input] ExternCrate(DefId),
582 [eval_always] LintLevels,
583 [] Specializes { impl1: DefId, impl2: DefId },
584 [input] InScopeTraits(DefIndex),
585 [input] ModuleExports(DefId),
586 [] IsSanitizerRuntime(CrateNum),
587 [] IsProfilerRuntime(CrateNum),
588 [] GetPanicStrategy(CrateNum),
589 [] IsNoBuiltins(CrateNum),
590 [] ImplDefaultness(DefId),
591 [] CheckItemWellFormed(DefId),
592 [] CheckTraitItemWellFormed(DefId),
593 [] CheckImplItemWellFormed(DefId),
594 [] ReachableNonGenerics(CrateNum),
595 [] NativeLibraries(CrateNum),
596 [] PluginRegistrarFn(CrateNum),
597 [] DeriveRegistrarFn(CrateNum),
598 [input] CrateDisambiguator(CrateNum),
599 [input] CrateHash(CrateNum),
600 [input] OriginalCrateName(CrateNum),
601 [input] ExtraFileName(CrateNum),
603 [] ImplementationsOfTrait { krate: CrateNum, trait_id: DefId },
604 [] AllTraitImplementations(CrateNum),
606 [] DllimportForeignItems(CrateNum),
607 [] IsDllimportForeignItem(DefId),
608 [] IsStaticallyIncludedForeignItem(DefId),
609 [] NativeLibraryKind(DefId),
612 [] ResolveLifetimes(CrateNum),
613 [] NamedRegion(DefIndex),
614 [] IsLateBound(DefIndex),
615 [] ObjectLifetimeDefaults(DefIndex),
617 [] Visibility(DefId),
618 [input] DepKind(CrateNum),
619 [input] CrateName(CrateNum),
620 [] ItemChildren(DefId),
621 [] ExternModStmtCnum(DefId),
622 [eval_always] GetLibFeatures,
623 [] DefinedLibFeatures(CrateNum),
624 [eval_always] GetLangItems,
625 [] DefinedLangItems(CrateNum),
626 [] MissingLangItems(CrateNum),
628 [input] MissingExternCrateItem(CrateNum),
629 [input] UsedCrateSource(CrateNum),
630 [input] PostorderCnums,
632 // These queries are not expected to have inputs -- as a result, they
633 // are not good candidates for "replay" because they are essentially
634 // pure functions of their input (and hence the expectation is that
635 // no caller would be green **apart** from just these
636 // queries). Making them anonymous avoids hashing the result, which
637 // may save a bit of time.
638 [anon] EraseRegionsTy { ty: Ty<'tcx> },
640 [input] Freevars(DefId),
641 [input] MaybeUnusedTraitImport(DefId),
642 [input] MaybeUnusedExternCrates,
643 [eval_always] StabilityIndex,
644 [eval_always] AllTraits,
645 [input] AllCrateNums,
646 [] ExportedSymbols(CrateNum),
647 [eval_always] CollectAndPartitionMonoItems,
648 [] IsCodegenedItem(DefId),
649 [] CodegenUnit(InternedString),
650 [] CompileCodegenUnit(InternedString),
651 [input] OutputFilenames,
652 [] NormalizeProjectionTy(CanonicalProjectionGoal<'tcx>),
653 [] NormalizeTyAfterErasingRegions(ParamEnvAnd<'tcx, Ty<'tcx>>),
654 [] ImpliedOutlivesBounds(CanonicalTyGoal<'tcx>),
655 [] DropckOutlives(CanonicalTyGoal<'tcx>),
656 [] EvaluateObligation(CanonicalPredicateGoal<'tcx>),
657 [] TypeOpEq(CanonicalTypeOpEqGoal<'tcx>),
658 [] TypeOpSubtype(CanonicalTypeOpSubtypeGoal<'tcx>),
659 [] TypeOpProvePredicate(CanonicalTypeOpProvePredicateGoal<'tcx>),
660 [] TypeOpNormalizeTy(CanonicalTypeOpNormalizeGoal<'tcx, Ty<'tcx>>),
661 [] TypeOpNormalizePredicate(CanonicalTypeOpNormalizeGoal<'tcx, Predicate<'tcx>>),
662 [] TypeOpNormalizePolyFnSig(CanonicalTypeOpNormalizeGoal<'tcx, PolyFnSig<'tcx>>),
663 [] TypeOpNormalizeFnSig(CanonicalTypeOpNormalizeGoal<'tcx, FnSig<'tcx>>),
665 [] SubstituteNormalizeAndTestPredicates { key: (DefId, &'tcx Substs<'tcx>) },
667 [input] TargetFeaturesWhitelist,
669 [] InstanceDefSizeEstimate { instance_def: InstanceDef<'tcx> },
673 [] ProgramClausesFor(DefId),
674 [] ProgramClausesForEnv(traits::Environment<'tcx>),
675 [] WasmImportModuleMap(CrateNum),
676 [] ForeignModules(CrateNum),
678 [] UpstreamMonomorphizations(CrateNum),
679 [] UpstreamMonomorphizationsFor(DefId),
682 trait DepNodeParams<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> : fmt::Debug {
683 const CAN_RECONSTRUCT_QUERY_KEY: bool;
685 /// This method turns the parameters of a DepNodeConstructor into an opaque
686 /// Fingerprint to be used in DepNode.
687 /// Not all DepNodeParams support being turned into a Fingerprint (they
688 /// don't need to if the corresponding DepNode is anonymous).
689 fn to_fingerprint(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
690 panic!("Not implemented. Accidentally called on anonymous node?")
693 fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
694 format!("{:?}", self)
698 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a, T> DepNodeParams<'a, 'gcx, 'tcx> for T
699 where T: HashStable<StableHashingContext<'a>> + fmt::Debug
701 default const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
703 default fn to_fingerprint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
704 let mut hcx = tcx.create_stable_hashing_context();
705 let mut hasher = StableHasher::new();
707 self.hash_stable(&mut hcx, &mut hasher);
712 default fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
713 format!("{:?}", *self)
717 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for DefId {
718 const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
720 fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
721 tcx.def_path_hash(*self).0
724 fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
725 tcx.item_path_str(*self)
729 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for DefIndex {
730 const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
732 fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
733 tcx.hir.definitions().def_path_hash(*self).0
736 fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
737 tcx.item_path_str(DefId::local(*self))
741 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for CrateNum {
742 const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
744 fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
747 index: CRATE_DEF_INDEX,
749 tcx.def_path_hash(def_id).0
752 fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
753 tcx.crate_name(*self).as_str().to_string()
757 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefId, DefId) {
758 const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
760 // We actually would not need to specialize the implementation of this
761 // method but it's faster to combine the hashes than to instantiate a full
762 // hashing context and stable-hashing state.
763 fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
764 let (def_id_0, def_id_1) = *self;
766 let def_path_hash_0 = tcx.def_path_hash(def_id_0);
767 let def_path_hash_1 = tcx.def_path_hash(def_id_1);
769 def_path_hash_0.0.combine(def_path_hash_1.0)
772 fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
773 let (def_id_0, def_id_1) = *self;
776 tcx.def_path_debug_str(def_id_0),
777 tcx.def_path_debug_str(def_id_1))
781 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for HirId {
782 const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
784 // We actually would not need to specialize the implementation of this
785 // method but it's faster to combine the hashes than to instantiate a full
786 // hashing context and stable-hashing state.
787 fn to_fingerprint(&self, tcx: TyCtxt<'_, '_, '_>) -> Fingerprint {
790 local_id: ItemLocalId(local_id),
793 let def_path_hash = tcx.def_path_hash(DefId::local(owner));
794 let local_id = Fingerprint::from_smaller_hash(local_id as u64);
796 def_path_hash.0.combine(local_id)
800 /// A "work product" corresponds to a `.o` (or other) file that we
801 /// save in between runs. These ids do not have a DefId but rather
802 /// some independent path or string that persists between runs without
803 /// the need to be mapped or unmapped. (This ensures we can serialize
804 /// them even in the absence of a tcx.)
805 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
806 RustcEncodable, RustcDecodable)]
807 pub struct WorkProductId {
812 pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
813 let mut hasher = StableHasher::new();
814 cgu_name.len().hash(&mut hasher);
815 cgu_name.hash(&mut hasher);
817 hash: hasher.finish()
821 pub fn from_fingerprint(fingerprint: Fingerprint) -> WorkProductId {
828 impl_stable_hash_for!(struct ::dep_graph::WorkProductId {