]> git.lizzy.rs Git - rust.git/blob - src/librustc/dep_graph/dep_node.rs
Rename is_translated_fn query to is_translated_item and make it support statics.
[rust.git] / src / librustc / dep_graph / dep_node.rs
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.
4 //
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.
10
11
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:
23 //!
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
32 //!   reconstruction).
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.
39 //!
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.
44 //!
45 //! Because the macro sees what parameters a given `DepKind` requires, it can
46 //! "infer" some properties for each kind of `DepNode`:
47 //!
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.
55 //!
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.
62
63 use hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
64 use hir::map::DefPathHash;
65 use hir::{HirId, ItemLocalId};
66
67 use ich::Fingerprint;
68 use ty::{TyCtxt, Instance, InstanceDef, ParamEnv, ParamEnvAnd, PolyTraitRef, Ty};
69 use ty::subst::Substs;
70 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
71 use ich::StableHashingContext;
72 use std::fmt;
73 use std::hash::Hash;
74 use syntax_pos::symbol::InternedString;
75
76 // erase!() just makes tokens go away. It's used to specify which macro argument
77 // is repeated (i.e. which sub-expression of the macro we are in) but don't need
78 // to actually use any of the arguments.
79 macro_rules! erase {
80     ($x:tt) => ({})
81 }
82
83 macro_rules! is_anon_attr {
84     (anon) => (true);
85     ($attr:ident) => (false);
86 }
87
88 macro_rules! is_input_attr {
89     (input) => (true);
90     ($attr:ident) => (false);
91 }
92
93 macro_rules! is_eval_always_attr {
94     (eval_always) => (true);
95     ($attr:ident) => (false);
96 }
97
98 macro_rules! contains_anon_attr {
99     ($($attr:ident),*) => ({$(is_anon_attr!($attr) | )* false});
100 }
101
102 macro_rules! contains_input_attr {
103     ($($attr:ident),*) => ({$(is_input_attr!($attr) | )* false});
104 }
105
106 macro_rules! contains_eval_always_attr {
107     ($($attr:ident),*) => ({$(is_eval_always_attr!($attr) | )* false});
108 }
109
110 macro_rules! define_dep_nodes {
111     (<$tcx:tt>
112     $(
113         [$($attr:ident),* ]
114         $variant:ident $(( $($tuple_arg:tt),* ))*
115                        $({ $($struct_arg_name:ident : $struct_arg_ty:ty),* })*
116       ,)*
117     ) => (
118         #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
119                  RustcEncodable, RustcDecodable)]
120         pub enum DepKind {
121             $($variant),*
122         }
123
124         impl DepKind {
125             #[allow(unreachable_code)]
126             #[inline]
127             pub fn can_reconstruct_query_key<$tcx>(&self) -> bool {
128                 match *self {
129                     $(
130                         DepKind :: $variant => {
131                             if contains_anon_attr!($($attr),*) {
132                                 return false;
133                             }
134
135                             // tuple args
136                             $({
137                                 return <( $($tuple_arg,)* ) as DepNodeParams>
138                                     ::CAN_RECONSTRUCT_QUERY_KEY;
139                             })*
140
141                             // struct args
142                             $({
143
144                                 return <( $($struct_arg_ty,)* ) as DepNodeParams>
145                                     ::CAN_RECONSTRUCT_QUERY_KEY;
146                             })*
147
148                             true
149                         }
150                     )*
151                 }
152             }
153
154             #[inline]
155             pub fn is_anon(&self) -> bool {
156                 match *self {
157                     $(
158                         DepKind :: $variant => { contains_anon_attr!($($attr),*) }
159                     )*
160                 }
161             }
162
163             #[inline]
164             pub fn is_input(&self) -> bool {
165                 match *self {
166                     $(
167                         DepKind :: $variant => { contains_input_attr!($($attr),*) }
168                     )*
169                 }
170             }
171
172             #[inline]
173             pub fn is_eval_always(&self) -> bool {
174                 match *self {
175                     $(
176                         DepKind :: $variant => { contains_eval_always_attr!($($attr), *) }
177                     )*
178                 }
179             }
180
181             #[allow(unreachable_code)]
182             #[inline]
183             pub fn has_params(&self) -> bool {
184                 match *self {
185                     $(
186                         DepKind :: $variant => {
187                             // tuple args
188                             $({
189                                 $(erase!($tuple_arg);)*
190                                 return true;
191                             })*
192
193                             // struct args
194                             $({
195                                 $(erase!($struct_arg_name);)*
196                                 return true;
197                             })*
198
199                             false
200                         }
201                     )*
202                 }
203             }
204         }
205
206         pub enum DepConstructor<$tcx> {
207             $(
208                 $variant $(( $($tuple_arg),* ))*
209                          $({ $($struct_arg_name : $struct_arg_ty),* })*
210             ),*
211         }
212
213         #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
214                  RustcEncodable, RustcDecodable)]
215         pub struct DepNode {
216             pub kind: DepKind,
217             pub hash: Fingerprint,
218         }
219
220         impl DepNode {
221             #[allow(unreachable_code, non_snake_case)]
222             pub fn new<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
223                                        dep: DepConstructor<'gcx>)
224                                        -> DepNode
225                 where 'gcx: 'a + 'tcx,
226                       'tcx: 'a
227             {
228                 match dep {
229                     $(
230                         DepConstructor :: $variant $(( $($tuple_arg),* ))*
231                                                    $({ $($struct_arg_name),* })*
232                             =>
233                         {
234                             // tuple args
235                             $({
236                                 let tupled_args = ( $($tuple_arg,)* );
237                                 let hash = DepNodeParams::to_fingerprint(&tupled_args,
238                                                                          tcx);
239                                 let dep_node = DepNode {
240                                     kind: DepKind::$variant,
241                                     hash
242                                 };
243
244                                 if cfg!(debug_assertions) &&
245                                    !dep_node.kind.can_reconstruct_query_key() &&
246                                    (tcx.sess.opts.debugging_opts.incremental_info ||
247                                     tcx.sess.opts.debugging_opts.query_dep_graph)
248                                 {
249                                     tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
250                                         tupled_args.to_debug_str(tcx)
251                                     });
252                                 }
253
254                                 return dep_node;
255                             })*
256
257                             // struct args
258                             $({
259                                 let tupled_args = ( $($struct_arg_name,)* );
260                                 let hash = DepNodeParams::to_fingerprint(&tupled_args,
261                                                                          tcx);
262                                 let dep_node = DepNode {
263                                     kind: DepKind::$variant,
264                                     hash
265                                 };
266
267                                 if cfg!(debug_assertions) &&
268                                    !dep_node.kind.can_reconstruct_query_key() &&
269                                    (tcx.sess.opts.debugging_opts.incremental_info ||
270                                     tcx.sess.opts.debugging_opts.query_dep_graph)
271                                 {
272                                     tcx.dep_graph.register_dep_node_debug_str(dep_node, || {
273                                         tupled_args.to_debug_str(tcx)
274                                     });
275                                 }
276
277                                 return dep_node;
278                             })*
279
280                             DepNode {
281                                 kind: DepKind::$variant,
282                                 hash: Fingerprint::ZERO,
283                             }
284                         }
285                     )*
286                 }
287             }
288
289             /// Construct a DepNode from the given DepKind and DefPathHash. This
290             /// method will assert that the given DepKind actually requires a
291             /// single DefId/DefPathHash parameter.
292             #[inline]
293             pub fn from_def_path_hash(kind: DepKind,
294                                       def_path_hash: DefPathHash)
295                                       -> DepNode {
296                 assert!(kind.can_reconstruct_query_key() && kind.has_params());
297                 DepNode {
298                     kind,
299                     hash: def_path_hash.0,
300                 }
301             }
302
303             /// Create a new, parameterless DepNode. This method will assert
304             /// that the DepNode corresponding to the given DepKind actually
305             /// does not require any parameters.
306             #[inline]
307             pub fn new_no_params(kind: DepKind) -> DepNode {
308                 assert!(!kind.has_params());
309                 DepNode {
310                     kind,
311                     hash: Fingerprint::ZERO,
312                 }
313             }
314
315             /// Extract the DefId corresponding to this DepNode. This will work
316             /// if two conditions are met:
317             ///
318             /// 1. The Fingerprint of the DepNode actually is a DefPathHash, and
319             /// 2. the item that the DefPath refers to exists in the current tcx.
320             ///
321             /// Condition (1) is determined by the DepKind variant of the
322             /// DepNode. Condition (2) might not be fulfilled if a DepNode
323             /// refers to something from the previous compilation session that
324             /// has been removed.
325             #[inline]
326             pub fn extract_def_id(&self, tcx: TyCtxt) -> Option<DefId> {
327                 if self.kind.can_reconstruct_query_key() {
328                     let def_path_hash = DefPathHash(self.hash);
329                     if let Some(ref def_path_map) = tcx.def_path_hash_to_def_id.as_ref() {
330                         def_path_map.get(&def_path_hash).cloned()
331                     } else {
332                        None
333                     }
334                 } else {
335                     None
336                 }
337             }
338
339             /// Used in testing
340             pub fn from_label_string(label: &str,
341                                      def_path_hash: DefPathHash)
342                                      -> Result<DepNode, ()> {
343                 let kind = match label {
344                     $(
345                         stringify!($variant) => DepKind::$variant,
346                     )*
347                     _ => return Err(()),
348                 };
349
350                 if !kind.can_reconstruct_query_key() {
351                     return Err(());
352                 }
353
354                 if kind.has_params() {
355                     Ok(def_path_hash.to_dep_node(kind))
356                 } else {
357                     Ok(DepNode::new_no_params(kind))
358                 }
359             }
360
361             /// Used in testing
362             pub fn has_label_string(label: &str) -> bool {
363                 match label {
364                     $(
365                         stringify!($variant) => true,
366                     )*
367                     _ => false,
368                 }
369             }
370         }
371
372         /// Contains variant => str representations for constructing
373         /// DepNode groups for tests.
374         #[allow(dead_code, non_upper_case_globals)]
375         pub mod label_strs {
376            $(
377                 pub const $variant: &'static str = stringify!($variant);
378             )*
379         }
380     );
381 }
382
383 impl fmt::Debug for DepNode {
384     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
385         write!(f, "{:?}", self.kind)?;
386
387         if !self.kind.has_params() && !self.kind.is_anon() {
388             return Ok(());
389         }
390
391         write!(f, "(")?;
392
393         ::ty::tls::with_opt(|opt_tcx| {
394             if let Some(tcx) = opt_tcx {
395                 if let Some(def_id) = self.extract_def_id(tcx) {
396                     write!(f, "{}", tcx.def_path_debug_str(def_id))?;
397                 } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*self) {
398                     write!(f, "{}", s)?;
399                 } else {
400                     write!(f, "{}", self.hash)?;
401                 }
402             } else {
403                 write!(f, "{}", self.hash)?;
404             }
405             Ok(())
406         })?;
407
408         write!(f, ")")
409     }
410 }
411
412
413 impl DefPathHash {
414     #[inline]
415     pub fn to_dep_node(self, kind: DepKind) -> DepNode {
416         DepNode::from_def_path_hash(kind, self)
417     }
418 }
419
420 impl DefId {
421     #[inline]
422     pub fn to_dep_node(self, tcx: TyCtxt, kind: DepKind) -> DepNode {
423         DepNode::from_def_path_hash(kind, tcx.def_path_hash(self))
424     }
425 }
426
427 impl DepKind {
428     #[inline]
429     pub fn fingerprint_needed_for_crate_hash(self) -> bool {
430         match self {
431             DepKind::HirBody |
432             DepKind::Krate => true,
433             _ => false,
434         }
435     }
436 }
437
438 define_dep_nodes!( <'tcx>
439     // Represents the `Krate` as a whole (the `hir::Krate` value) (as
440     // distinct from the krate module). This is basically a hash of
441     // the entire krate, so if you read from `Krate` (e.g., by calling
442     // `tcx.hir.krate()`), we will have to assume that any change
443     // means that you need to be recompiled. This is because the
444     // `Krate` value gives you access to all other items. To avoid
445     // this fate, do not call `tcx.hir.krate()`; instead, prefer
446     // wrappers like `tcx.visit_all_items_in_krate()`.  If there is no
447     // suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain
448     // access to the krate, but you must remember to add suitable
449     // edges yourself for the individual items that you read.
450     [input] Krate,
451
452     // Represents the body of a function or method. The def-id is that of the
453     // function/method.
454     [input] HirBody(DefId),
455
456     // Represents the HIR node with the given node-id
457     [input] Hir(DefId),
458
459     // Represents metadata from an extern crate.
460     [input] CrateMetadata(CrateNum),
461
462     // Represents different phases in the compiler.
463     [] RegionScopeTree(DefId),
464     [eval_always] Coherence,
465     [eval_always] CoherenceInherentImplOverlapCheck,
466     [] CoherenceCheckTrait(DefId),
467     [eval_always] PrivacyAccessLevels(CrateNum),
468
469     // Represents the MIR for a fn; also used as the task node for
470     // things read/modify that MIR.
471     [] MirConstQualif(DefId),
472     [] MirBuilt(DefId),
473     [] MirConst(DefId),
474     [] MirValidated(DefId),
475     [] MirOptimized(DefId),
476     [] MirShim { instance_def: InstanceDef<'tcx> },
477
478     [] BorrowCheckKrate,
479     [] BorrowCheck(DefId),
480     [] MirBorrowCheck(DefId),
481     [] UnsafetyCheckResult(DefId),
482     [] UnsafeDeriveOnReprPacked(DefId),
483
484     [] Reachability,
485     [] MirKeys,
486     [eval_always] CrateVariances,
487
488     // Nodes representing bits of computed IR in the tcx. Each shared
489     // table in the tcx (or elsewhere) maps to one of these
490     // nodes.
491     [] AssociatedItems(DefId),
492     [] TypeOfItem(DefId),
493     [] GenericsOfItem(DefId),
494     [] PredicatesOfItem(DefId),
495     [] InferredOutlivesOf(DefId),
496     [] SuperPredicatesOfItem(DefId),
497     [] TraitDefOfItem(DefId),
498     [] AdtDefOfItem(DefId),
499     [] ImplTraitRef(DefId),
500     [] ImplPolarity(DefId),
501     [] FnSignature(DefId),
502     [] CoerceUnsizedInfo(DefId),
503
504     [] ItemVarianceConstraints(DefId),
505     [] ItemVariances(DefId),
506     [] IsConstFn(DefId),
507     [] IsForeignItem(DefId),
508     [] TypeParamPredicates { item_id: DefId, param_id: DefId },
509     [] SizedConstraint(DefId),
510     [] DtorckConstraint(DefId),
511     [] AdtDestructor(DefId),
512     [] AssociatedItemDefIds(DefId),
513     [eval_always] InherentImpls(DefId),
514     [] TypeckBodiesKrate,
515     [] TypeckTables(DefId),
516     [] UsedTraitImports(DefId),
517     [] HasTypeckTables(DefId),
518     [] ConstEval { param_env: ParamEnvAnd<'tcx, (DefId, &'tcx Substs<'tcx>)> },
519     [] CheckMatch(DefId),
520     [] SymbolName(DefId),
521     [] InstanceSymbolName { instance: Instance<'tcx> },
522     [] SpecializationGraph(DefId),
523     [] ObjectSafety(DefId),
524     [] FulfillObligation { param_env: ParamEnv<'tcx>, trait_ref: PolyTraitRef<'tcx> },
525     [] VtableMethods { trait_ref: PolyTraitRef<'tcx> },
526
527     [] IsCopy { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
528     [] IsSized { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
529     [] IsFreeze { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
530     [] NeedsDrop { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
531     [] Layout { param_env: ParamEnvAnd<'tcx, Ty<'tcx>> },
532
533     // The set of impls for a given trait.
534     [] TraitImpls(DefId),
535
536     [input] AllLocalTraitImpls,
537
538     [anon] TraitSelect,
539
540     [] ParamEnv(DefId),
541     [] DescribeDef(DefId),
542
543     // FIXME(mw): DefSpans are not really inputs since they are derived from
544     // HIR. But at the moment HIR hashing still contains some hacks that allow
545     // to make type debuginfo to be source location independent. Declaring
546     // DefSpan an input makes sure that changes to these are always detected
547     // regardless of HIR hashing.
548     [input] DefSpan(DefId),
549     [] LookupStability(DefId),
550     [] LookupDeprecationEntry(DefId),
551     [] ItemBodyNestedBodies(DefId),
552     [] ConstIsRvaluePromotableToStatic(DefId),
553     [] RvaluePromotableMap(DefId),
554     [] ImplParent(DefId),
555     [] TraitOfItem(DefId),
556     [] IsExportedSymbol(DefId),
557     [] IsMirAvailable(DefId),
558     [] ItemAttrs(DefId),
559     [] FnArgNames(DefId),
560     [] DylibDepFormats(CrateNum),
561     [] IsPanicRuntime(CrateNum),
562     [] IsCompilerBuiltins(CrateNum),
563     [] HasGlobalAllocator(CrateNum),
564     [input] ExternCrate(DefId),
565     [eval_always] LintLevels,
566     [] Specializes { impl1: DefId, impl2: DefId },
567     [input] InScopeTraits(DefIndex),
568     [input] ModuleExports(DefId),
569     [] IsSanitizerRuntime(CrateNum),
570     [] IsProfilerRuntime(CrateNum),
571     [] GetPanicStrategy(CrateNum),
572     [] IsNoBuiltins(CrateNum),
573     [] ImplDefaultness(DefId),
574     [] ExportedSymbolIds(CrateNum),
575     [] NativeLibraries(CrateNum),
576     [] PluginRegistrarFn(CrateNum),
577     [] DeriveRegistrarFn(CrateNum),
578     [input] CrateDisambiguator(CrateNum),
579     [input] CrateHash(CrateNum),
580     [input] OriginalCrateName(CrateNum),
581
582     [] ImplementationsOfTrait { krate: CrateNum, trait_id: DefId },
583     [] AllTraitImplementations(CrateNum),
584
585     [] IsDllimportForeignItem(DefId),
586     [] IsStaticallyIncludedForeignItem(DefId),
587     [] NativeLibraryKind(DefId),
588     [input] LinkArgs,
589
590     [] ResolveLifetimes(CrateNum),
591     [] NamedRegion(DefIndex),
592     [] IsLateBound(DefIndex),
593     [] ObjectLifetimeDefaults(DefIndex),
594
595     [] Visibility(DefId),
596     [input] DepKind(CrateNum),
597     [input] CrateName(CrateNum),
598     [] ItemChildren(DefId),
599     [] ExternModStmtCnum(DefId),
600     [input] GetLangItems,
601     [] DefinedLangItems(CrateNum),
602     [] MissingLangItems(CrateNum),
603     [] ExternConstBody(DefId),
604     [] VisibleParentMap,
605     [input] MissingExternCrateItem(CrateNum),
606     [input] UsedCrateSource(CrateNum),
607     [input] PostorderCnums,
608     [input] HasCloneClosures(CrateNum),
609     [input] HasCopyClosures(CrateNum),
610
611     // This query is not expected to have inputs -- as a result, it's
612     // not a good candidate for "replay" because it's essentially a
613     // pure function of its input (and hence the expectation is that
614     // no caller would be green **apart** from just this
615     // query). Making it anonymous avoids hashing the result, which
616     // may save a bit of time.
617     [anon] EraseRegionsTy { ty: Ty<'tcx> },
618
619     [input] Freevars(DefId),
620     [input] MaybeUnusedTraitImport(DefId),
621     [input] MaybeUnusedExternCrates,
622     [eval_always] StabilityIndex,
623     [input] AllCrateNums,
624     [] ExportedSymbols(CrateNum),
625     [eval_always] CollectAndPartitionTranslationItems,
626     [] ExportName(DefId),
627     [] ContainsExternIndicator(DefId),
628     [] IsTranslatedItem(DefId),
629     [] CodegenUnit(InternedString),
630     [] CompileCodegenUnit(InternedString),
631     [input] OutputFilenames,
632     [anon] NormalizeTy,
633     // We use this for most things when incr. comp. is turned off.
634     [] Null,
635
636     [] SubstituteNormalizeAndTestPredicates { key: (DefId, &'tcx Substs<'tcx>) },
637
638     [input] TargetFeaturesWhitelist,
639     [] TargetFeaturesEnabled(DefId),
640
641     [] InstanceDefSizeEstimate { instance_def: InstanceDef<'tcx> },
642
643     [] GetSymbolExportLevel(DefId),
644
645 );
646
647 trait DepNodeParams<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> : fmt::Debug {
648     const CAN_RECONSTRUCT_QUERY_KEY: bool;
649
650     /// This method turns the parameters of a DepNodeConstructor into an opaque
651     /// Fingerprint to be used in DepNode.
652     /// Not all DepNodeParams support being turned into a Fingerprint (they
653     /// don't need to if the corresponding DepNode is anonymous).
654     fn to_fingerprint(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
655         panic!("Not implemented. Accidentally called on anonymous node?")
656     }
657
658     fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
659         format!("{:?}", self)
660     }
661 }
662
663 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a, T> DepNodeParams<'a, 'gcx, 'tcx> for T
664     where T: HashStable<StableHashingContext<'gcx>> + fmt::Debug
665 {
666     default const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
667
668     default fn to_fingerprint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Fingerprint {
669         let mut hcx = tcx.create_stable_hashing_context();
670         let mut hasher = StableHasher::new();
671
672         self.hash_stable(&mut hcx, &mut hasher);
673
674         hasher.finish()
675     }
676
677     default fn to_debug_str(&self, _: TyCtxt<'a, 'gcx, 'tcx>) -> String {
678         format!("{:?}", *self)
679     }
680 }
681
682 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefId,) {
683     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
684
685     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
686         tcx.def_path_hash(self.0).0
687     }
688
689     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
690         tcx.item_path_str(self.0)
691     }
692 }
693
694 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefIndex,) {
695     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
696
697     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
698         tcx.hir.definitions().def_path_hash(self.0).0
699     }
700
701     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
702         tcx.item_path_str(DefId::local(self.0))
703     }
704 }
705
706 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (CrateNum,) {
707     const CAN_RECONSTRUCT_QUERY_KEY: bool = true;
708
709     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
710         let def_id = DefId {
711             krate: self.0,
712             index: CRATE_DEF_INDEX,
713         };
714         tcx.def_path_hash(def_id).0
715     }
716
717     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
718         tcx.crate_name(self.0).as_str().to_string()
719     }
720 }
721
722 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (DefId, DefId) {
723     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
724
725     // We actually would not need to specialize the implementation of this
726     // method but it's faster to combine the hashes than to instantiate a full
727     // hashing context and stable-hashing state.
728     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
729         let (def_id_0, def_id_1) = *self;
730
731         let def_path_hash_0 = tcx.def_path_hash(def_id_0);
732         let def_path_hash_1 = tcx.def_path_hash(def_id_1);
733
734         def_path_hash_0.0.combine(def_path_hash_1.0)
735     }
736
737     fn to_debug_str(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> String {
738         let (def_id_0, def_id_1) = *self;
739
740         format!("({}, {})",
741                 tcx.def_path_debug_str(def_id_0),
742                 tcx.def_path_debug_str(def_id_1))
743     }
744 }
745
746 impl<'a, 'gcx: 'tcx + 'a, 'tcx: 'a> DepNodeParams<'a, 'gcx, 'tcx> for (HirId,) {
747     const CAN_RECONSTRUCT_QUERY_KEY: bool = false;
748
749     // We actually would not need to specialize the implementation of this
750     // method but it's faster to combine the hashes than to instantiate a full
751     // hashing context and stable-hashing state.
752     fn to_fingerprint(&self, tcx: TyCtxt) -> Fingerprint {
753         let (HirId {
754             owner,
755             local_id: ItemLocalId(local_id),
756         },) = *self;
757
758         let def_path_hash = tcx.def_path_hash(DefId::local(owner));
759         let local_id = Fingerprint::from_smaller_hash(local_id as u64);
760
761         def_path_hash.0.combine(local_id)
762     }
763 }
764
765 /// A "work product" corresponds to a `.o` (or other) file that we
766 /// save in between runs. These ids do not have a DefId but rather
767 /// some independent path or string that persists between runs without
768 /// the need to be mapped or unmapped. (This ensures we can serialize
769 /// them even in the absence of a tcx.)
770 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
771          RustcEncodable, RustcDecodable)]
772 pub struct WorkProductId {
773     hash: Fingerprint
774 }
775
776 impl WorkProductId {
777     pub fn from_cgu_name(cgu_name: &str) -> WorkProductId {
778         let mut hasher = StableHasher::new();
779         cgu_name.len().hash(&mut hasher);
780         cgu_name.hash(&mut hasher);
781         WorkProductId {
782             hash: hasher.finish()
783         }
784     }
785
786     pub fn from_fingerprint(fingerprint: Fingerprint) -> WorkProductId {
787         WorkProductId {
788             hash: fingerprint
789         }
790     }
791 }
792
793 impl_stable_hash_for!(struct ::dep_graph::WorkProductId {
794     hash
795 });