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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//! Provable, composable, compile-time deadlock-freedom.
//!
//! # How to Use `locktree`
//!
//! This crate revolves around a macro: `locktree`.
//!
//! # How `locktree` Works (TODO: update with latest format)
//!
//! `locktree` (ab)uses Rust's type system to guarantee that locks are always
//! taken in the same order. Locks under `locktree`'s management are organized
//! into a linear sequence. Locks can only be acquired by moving forward into
//! this sequence, and locks must be released when moving back. Thus it is
//! statically impossible for two threads to acquire the same set of locks in
//! different orders, and so deadlocks are impossible *as long as all locks are
//! managed by `locktree`*.
//!
//! To achieve this, `locktree` relies on a mix of aliasing rules for mutable
//! references, lifetimes, and separate types for each point in the sequence.
//! In the simplest case with a single lock:
//!
//! ```
//! # use locktree::locktree;
//! locktree! {
//!   Main {
//!     main: StdMutex<String>,
//!   }
//! }
//! ```
//!
//! The macro will generate an "entry point" with which you can lock anything
//! (only `main` in this case, with explicit lifetimes for illustration
//! purposes):
//!
//! ```
//! struct MainLockTree {
//!   main: ::std::sync::Mutex<String>,
//! }
//!
//! impl MainLockTree {
//!   fn lock_main<'a>(
//!     &'a mut self
//!   ) -> (::std::sync::MutexGuard<'a, String>, MainLockTreeMain<'a>) {
//!     // ...
//!     # unimplemented!()
//!   }
//! }
//! # struct MainLockTreeMain<'a>(std::marker::PhantomData<&'a ()>);
//! ```
//!
//! All lock functions take `&mut self` and return the appropriate lock and a
//! *forward locktree*. Both are tied through their lifetimes to the
//! `MainLockTree` instance, and thus it is impossible (in safe Rust) to use
//! that instance to lock anything else. Further locking can only happen
//! through the forward locktree. In this case, the `MainLockTreeMain` is
//! completely empty and thus no further locks can be acquired:
//!
//! ```
//! # struct MainLockTreeMain<'a>(::std::marker::PhantomData<&'a ()>);
//! impl<'b> MainLockTreeMain<'b> {}
//! ```
//!
//! This happens because there are no further locks after `main`. If instead we
//! had two locks:
//!
//! ```
//! # use locktree::locktree;
//! locktree! {
//!   Main {
//!     first: StdMutex<String>,
//!     second: StdRwLock<Vec<usize>>,
//!   }
//! }
//! ```
//!
//! We would be able to lock any of those from the entry point:
//!
//! ```
//! struct MainLockTree {
//!   first: ::std::sync::Mutex<String>,
//!   second: ::std::sync::RwLock<Vec<usize>>,
//! }
//!
//! impl MainLockTree {
//!   fn lock_first<'a>(
//!     &'a mut self
//!   ) -> (::std::sync::MutexGuard<'a, String>, MainLockTreeFirst<'a>) {
//!     // ...
//!     # unimplemented!()
//!   }
//!
//!   fn read_second<'a>(
//!     &'a mut self
//!   ) -> (::std::sync::RwLockReadGuard<'a, Vec<usize>>, MainLockTreeSecond<'a>) {
//!     // ...
//!     # unimplemented!()
//!   }
//!
//!   fn write_second<'a>(
//!     &'a mut self
//!   ) -> (::std::sync::RwLockWriteGuard<'a, Vec<usize>>, MainLockTreeSecond<'a>) {
//!     // ...
//!     # unimplemented!()
//!   }
//! }
//! ```
//!
//! `MainLockTreeSecond` is again empty since it is the last in the sequence.
//! However, `MainLockTreeFirst` allows `second` (but not `fist`) to be locked
//! in sequence:
//!
//! ```
//! struct MainLockTreeSecond<'a>(&'a MainLockTree);
//!
//! impl MainLockTree {
//!   fn read_second<'a>(
//!     &'a mut self
//!   ) -> (::std::sync::RwLockReadGuard<'a, Vec<usize>>, MainLockTreeSecond<'a>) {
//!     // ...
//!     # unimplemented!()
//!   }
//!
//!   fn write_second<'a>(
//!     &'a mut self
//!   ) -> (::std::sync::RwLockWriteGuard<'a, Vec<usize>>, MainLockTreeSecond<'a>) {
//!     // ...
//!     # unimplemented!()
//!   }
//! }
//! ```
//!
//! And thus a proper locking sequence is enforced. Note that you can choose
//! not to lock anything between the current state and a target lock, but that
//! will have to be dropped and reacquired if your code needs to lock anything
//! that was skipped.
//!
//! # Composing
//!
//! TODO

use crate::plug::*;
#[cfg(feature = "async")]
use std::future::Future;
use std::pin::Pin;

/// `locktree!` macro. See the module-level documentation for details.
pub use locktree_derive::locktree;

pub mod plug;

pub type PluggedGuard<'a, T> = <T as PlugLifetime<'a>>::Type;

pub type PluggedMutexGuard<'a, T> = PluggedGuard<'a, <T as Mutex>::Guard>;

pub type PluggedRwLockReadGuard<'a, T> =
    PluggedGuard<'a, <T as RwLock>::ReadGuard>;

pub type PluggedRwLockWriteGuard<'a, T> =
    PluggedGuard<'a, <T as RwLock>::WriteGuard>;

#[cfg(feature = "async")]
pub type PluggedAsyncGuard<'a, T> =
    Pin<Box<dyn Future<Output = <T as PlugLifetime<'a>>::Type> + 'a>>;

#[cfg(feature = "async")]
pub type PluggedAsyncMutexGuard<'a, T> =
    PluggedAsyncGuard<'a, <T as AsyncMutex>::Guard>;

#[cfg(feature = "async")]
pub type PluggedAsyncRwLockReadGuard<'a, T> =
    PluggedAsyncGuard<'a, <T as AsyncRwLock>::ReadGuard>;

#[cfg(feature = "async")]
pub type PluggedAsyncRwLockWriteGuard<'a, T> =
    PluggedAsyncGuard<'a, <T as AsyncRwLock>::WriteGuard>;

pub trait New<T> {
    fn new(value: T) -> Self;
}

impl<T> New<T> for ::std::sync::Mutex<T> {
    fn new(value: T) -> Self {
        Self::new(value)
    }
}

impl<T> New<T> for ::std::sync::RwLock<T> {
    fn new(value: T) -> Self {
        Self::new(value)
    }
}

#[cfg(feature = "tokio")]
impl<T> New<T> for ::tokio::sync::Mutex<T> {
    fn new(value: T) -> Self {
        Self::new(value)
    }
}

#[cfg(feature = "tokio")]
impl<T> New<T> for ::tokio::sync::RwLock<T> {
    fn new(value: T) -> Self {
        Self::new(value)
    }
}

pub trait Mutex {
    type Guard: for<'a> PlugLifetime<'a>;

    fn lock(&self) -> PluggedGuard<Self::Guard>;
}

impl<T> Mutex for std::sync::Mutex<T>
where
    T: 'static,
{
    type Guard = H1MutexLockGuard<T>;

    fn lock(&self) -> PluggedGuard<Self::Guard> {
        std::sync::Mutex::<T>::lock(self).unwrap()
    }
}

#[cfg(feature = "async")]
pub trait AsyncMutex {
    type Guard: for<'a> PlugLifetime<'a>;

    fn lock(&self) -> PluggedAsyncGuard<Self::Guard>;
}

#[cfg(feature = "tokio")]
impl<T> AsyncMutex for tokio::sync::Mutex<T>
where
    T: 'static,
{
    type Guard = H1TokioMutexLockGuard<T>;

    fn lock(&self) -> PluggedAsyncGuard<Self::Guard> {
        Box::pin(tokio::sync::Mutex::<T>::lock(self))
    }
}

pub trait RwLock {
    type ReadGuard: for<'a> PlugLifetime<'a>;
    type WriteGuard: for<'a> PlugLifetime<'a>;

    fn read(&self) -> PluggedGuard<Self::ReadGuard>;
    fn write(&self) -> PluggedGuard<Self::WriteGuard>;
}

impl<T> RwLock for std::sync::RwLock<T>
where
    T: 'static,
{
    type ReadGuard = H1RwLockReadGuard<T>;
    type WriteGuard = H1RwLockWriteGuard<T>;

    fn read(&self) -> PluggedGuard<Self::ReadGuard> {
        std::sync::RwLock::<T>::read(self).unwrap()
    }

    fn write(&self) -> PluggedGuard<Self::WriteGuard> {
        std::sync::RwLock::<T>::write(self).unwrap()
    }
}

impl<T> RwLock for T
where
    T: Mutex,
{
    type ReadGuard = T::Guard;
    type WriteGuard = T::Guard;

    fn read(&self) -> PluggedGuard<Self::ReadGuard> {
        self.lock()
    }

    fn write(&self) -> PluggedGuard<Self::WriteGuard> {
        self.lock()
    }
}

#[cfg(feature = "async")]
pub trait AsyncRwLock {
    type ReadGuard: for<'a> PlugLifetime<'a>;
    type WriteGuard: for<'a> PlugLifetime<'a>;

    fn read(&self) -> PluggedAsyncGuard<Self::ReadGuard>;
    fn write(&self) -> PluggedAsyncGuard<Self::WriteGuard>;
}

#[cfg(feature = "tokio")]
impl<T> AsyncRwLock for tokio::sync::RwLock<T>
where
    T: 'static,
{
    type ReadGuard = H1TokioRwLockReadGuard<T>;
    type WriteGuard = H1TokioRwLockWriteGuard<T>;

    fn read(&self) -> PluggedAsyncGuard<Self::ReadGuard> {
        Box::pin(tokio::sync::RwLock::<T>::read(self))
    }

    fn write(&self) -> PluggedAsyncGuard<Self::WriteGuard> {
        Box::pin(tokio::sync::RwLock::<T>::write(self))
    }
}

#[cfg(feature = "async")]
impl<T> AsyncRwLock for T
where
    T: AsyncMutex,
{
    type ReadGuard = T::Guard;
    type WriteGuard = T::Guard;

    fn read(&self) -> PluggedAsyncGuard<Self::ReadGuard> {
        self.lock()
    }

    fn write(&self) -> PluggedAsyncGuard<Self::WriteGuard> {
        self.lock()
    }
}