]> git.lizzy.rs Git - rust.git/blob - src/librustc_query_system/cache.rs
Provide a better diagnostic if ninja isn't installed
[rust.git] / src / librustc_query_system / cache.rs
1 //! Cache for candidate selection.
2
3 use crate::dep_graph::DepNodeIndex;
4 use crate::query::QueryContext;
5
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::sync::HashMapExt;
8 use rustc_data_structures::sync::Lock;
9
10 use std::hash::Hash;
11
12 #[derive(Clone)]
13 pub struct Cache<Key, Value> {
14     hashmap: Lock<FxHashMap<Key, WithDepNode<Value>>>,
15 }
16
17 impl<Key, Value> Default for Cache<Key, Value> {
18     fn default() -> Self {
19         Self { hashmap: Default::default() }
20     }
21 }
22
23 impl<Key, Value> Cache<Key, Value> {
24     /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
25     pub fn clear(&self) {
26         *self.hashmap.borrow_mut() = Default::default();
27     }
28 }
29
30 impl<Key: Eq + Hash, Value: Clone> Cache<Key, Value> {
31     pub fn get<CTX: QueryContext>(&self, key: &Key, tcx: CTX) -> Option<Value> {
32         Some(self.hashmap.borrow().get(key)?.get(tcx))
33     }
34
35     pub fn insert(&self, key: Key, dep_node: DepNodeIndex, value: Value) {
36         self.hashmap.borrow_mut().insert(key, WithDepNode::new(dep_node, value));
37     }
38
39     pub fn insert_same(&self, key: Key, dep_node: DepNodeIndex, value: Value)
40     where
41         Value: Eq,
42     {
43         self.hashmap.borrow_mut().insert_same(key, WithDepNode::new(dep_node, value));
44     }
45 }
46
47 #[derive(Clone, Eq, PartialEq)]
48 pub struct WithDepNode<T> {
49     dep_node: DepNodeIndex,
50     cached_value: T,
51 }
52
53 impl<T: Clone> WithDepNode<T> {
54     pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
55         WithDepNode { dep_node, cached_value }
56     }
57
58     pub fn get<CTX: QueryContext>(&self, tcx: CTX) -> T {
59         tcx.dep_graph().read_index(self.dep_node);
60         self.cached_value.clone()
61     }
62 }