File: mod.rs

package info (click to toggle)
rust-salsa 0.23.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,424 kB
  • sloc: sh: 12; makefile: 2; javascript: 1
file content (207 lines) | stat: -rw-r--r-- 5,354 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//! Utility for tests that lets us log when notable events happen.

#![allow(dead_code, unused_imports)]

use std::sync::{Arc, Mutex};

use salsa::{Database, Storage};

/// Logging userdata: provides [`LogDatabase`][] trait.
///
/// If you wish to use it along with other userdata,
/// you can also embed it in another struct and implement [`HasLogger`][] for that struct.
#[derive(Clone, Default)]
pub struct Logger {
    logs: Arc<Mutex<Vec<String>>>,
}

impl Logger {
    pub fn push_log(&self, string: String) {
        self.logs.lock().unwrap().push(string);
    }
}

/// Trait implemented by databases that lets them log events.
pub trait HasLogger {
    /// Return a reference to the logger from the database.
    fn logger(&self) -> &Logger;
}

#[salsa::db]
pub trait LogDatabase: HasLogger + Database {
    /// Log an event from inside a tracked function.
    fn push_log(&self, string: String) {
        self.logger().logs.lock().unwrap().push(string);
    }

    /// Asserts what the (formatted) logs should look like,
    /// clearing the logged events. This takes `&mut self` because
    /// it is meant to be run from outside any tracked functions.
    fn assert_logs(&self, expected: expect_test::Expect) {
        let logs = std::mem::take(&mut *self.logger().logs.lock().unwrap());
        expected.assert_eq(&format!("{logs:#?}"));
    }

    /// Asserts the length of the logs,
    /// clearing the logged events. This takes `&mut self` because
    /// it is meant to be run from outside any tracked functions.
    fn assert_logs_len(&self, expected: usize) {
        let logs = std::mem::take(&mut *self.logger().logs.lock().unwrap());
        assert_eq!(logs.len(), expected, "Actual logs: {logs:#?}");
    }
}

#[salsa::db]
impl<Db: HasLogger + Database> LogDatabase for Db {}

/// Database that provides logging but does not log salsa event.
#[salsa::db]
#[derive(Clone, Default)]
pub struct LoggerDatabase {
    storage: Storage<Self>,
    logger: Logger,
}

impl HasLogger for LoggerDatabase {
    fn logger(&self) -> &Logger {
        &self.logger
    }
}

#[salsa::db]
impl Database for LoggerDatabase {}

/// Database that provides logging and logs salsa events.
#[salsa::db]
#[derive(Clone)]
pub struct EventLoggerDatabase {
    storage: Storage<Self>,
    logger: Logger,
}

impl Default for EventLoggerDatabase {
    fn default() -> Self {
        let logger = Logger::default();
        Self {
            storage: Storage::new(Some(Box::new({
                let logger = logger.clone();
                move |event| logger.push_log(format!("{:?}", event.kind))
            }))),
            logger,
        }
    }
}

#[salsa::db]
impl Database for EventLoggerDatabase {}

impl HasLogger for EventLoggerDatabase {
    fn logger(&self) -> &Logger {
        &self.logger
    }
}

#[salsa::db]
#[derive(Clone)]
pub struct DiscardLoggerDatabase {
    storage: Storage<Self>,
    logger: Logger,
}

impl Default for DiscardLoggerDatabase {
    fn default() -> Self {
        let logger = Logger::default();
        Self {
            storage: Storage::new(Some(Box::new({
                let logger = logger.clone();
                move |event| match event.kind {
                    salsa::EventKind::WillDiscardStaleOutput { .. }
                    | salsa::EventKind::DidDiscard { .. } => {
                        logger.push_log(format!("salsa_event({:?})", event.kind));
                    }
                    _ => {}
                }
            }))),
            logger,
        }
    }
}

#[salsa::db]
impl Database for DiscardLoggerDatabase {}

impl HasLogger for DiscardLoggerDatabase {
    fn logger(&self) -> &Logger {
        &self.logger
    }
}

#[salsa::db]
#[derive(Clone)]
pub struct ExecuteValidateLoggerDatabase {
    storage: Storage<Self>,
    logger: Logger,
}

impl Default for ExecuteValidateLoggerDatabase {
    fn default() -> Self {
        let logger = Logger::default();
        Self {
            storage: Storage::new(Some(Box::new({
                let logger = logger.clone();
                move |event| match event.kind {
                    salsa::EventKind::WillExecute { .. }
                    | salsa::EventKind::WillIterateCycle { .. }
                    | salsa::EventKind::DidValidateMemoizedValue { .. } => {
                        logger.push_log(format!("salsa_event({:?})", event.kind));
                    }
                    _ => {}
                }
            }))),
            logger,
        }
    }
}
impl Database for ExecuteValidateLoggerDatabase {}

impl HasLogger for ExecuteValidateLoggerDatabase {
    fn logger(&self) -> &Logger {
        &self.logger
    }
}

/// Trait implemented by databases that lets them provide a fixed u32 value.
pub trait HasValue {
    fn get_value(&self) -> u32;
}

#[salsa::db]
pub trait ValueDatabase: HasValue + Database {}

#[salsa::db]
impl<Db: HasValue + Database> ValueDatabase for Db {}

#[salsa::db]
#[derive(Clone, Default)]
pub struct DatabaseWithValue {
    storage: Storage<Self>,
    value: u32,
}

impl HasValue for DatabaseWithValue {
    fn get_value(&self) -> u32 {
        self.value
    }
}

#[salsa::db]
impl Database for DatabaseWithValue {}

impl DatabaseWithValue {
    pub fn new(value: u32) -> Self {
        Self {
            storage: Default::default(),
            value,
        }
    }
}