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
/// A macro to generate a struct containing a list of fields that may be locked.
/// This allows for more intuitive concurrency, by abstracting away the lock-unlock logic
/// and potential lock mishaps.
///
/// # Examples
/// ```
/// struct HelloWorldObject {
///     message: &'static str
/// }
///
/// struct Output {
///     message: Option<&'static str>
/// }
///
/// use covalent::lock_data;
/// use covalent::events::{Event, EventHandler};
/// lock_data! {
///     HelloWorldData
///
///     hello_world: read HelloWorldObject,
///     output: write Output
/// }
///
/// fn create_locks() {
///     use std::sync::*;
///     use covalent::scene::{Event, EventHandler};
///
///     let hello_world = Arc::new(RwLock::new(HelloWorldObject { message: "Hello, world!" }));
///     let output = Arc::new(RwLock::new(Output { message: None }));
///
///     let data = Arc::new(RwLock::new(HelloWorldData {
///         hello_world: Arc::downgrade(&hello_world),
///         output: Arc::downgrade(&output)
///     }));
///
///     struct HelloWorldEvent {}
///     impl Event for HelloWorldEvent {}
///     let event_handler = Arc::new(RwLock::new(EventHandler::<HelloWorldEvent>::new()));
///
///     HelloWorldData::listen(&data, &event_handler, |event, hello_world, output| {
///         output.message = Some(hello_world.message);
///     });
/// }
/// ```
#[macro_export]
macro_rules! lock_data {
    ($struct_name:ident $($name:ident : $mutability:ident $data_type:ty),+) => {
        struct $struct_name {
        // Populate the fields of the struct.
            $(
                $name : std::sync::Weak<std::sync::RwLock<$data_type>>,
            )*
        }

        // Implement the listen function.
        impl $struct_name {
            fn listen<'a, E, F>(data: &std::sync::Arc<std::sync::RwLock<Self>>, handler: &std::sync::Arc<std::sync::RwLock<$crate::events::EventHandler<E>>>, func: F)
                where E: $crate::events::Event,
                      F: Fn(&E
                          $(
                          , $crate::lock_data!(@ generate parameter $mutability $data_type)
                          )*
                      ),
                      F: Send + Sync + 'static {
                let copy = std::sync::Arc::clone(data);
                let l = $crate::events::Listener {
                    id: handler.write().unwrap().new_id(),
                    func: Box::new(move |event| {
                        let self_var = copy.read().unwrap();
                        $crate::lock_data!{ @ generate locks self_var, func, event, $($name, $mutability, $data_type),+ }
                    })
                };
                handler.write().unwrap().insert(l);
            }
        }
    };

    (@ generate parameter read $data_type:ty) => { &$data_type };
    (@ generate parameter write $data_type:ty) => { &mut $data_type };
    (@ generate parameter $mutability:ident $data_type:ty) => {
        compile_error!("This macro requires the mutability of a variable to be 'read' or 'write'")
    };

    (@ generate locks $s:ident, $f:ident, $e:ident,
        $name0:ident, $mutability0:ident, $data_type0: ty | $($mutability1:ident)* | $($guard1:ident)*
        ) => {

        if let Some(arc) = std::sync::Weak::upgrade(&$s.$name0) {
            match $crate::lock_data!( @ generate try mutability $mutability0 arc ) {
                Ok($crate::lock_data!( @ generate mutability $mutability0 guard )) => {
                    $f($e, $($crate::lock_data!( @ generate mutability $mutability1 &$guard1)),*, $crate::lock_data!( @ generate mutability $mutability0 &guard));
                    Ok(())
                },
                _ => Err($crate::events::ListenError::LockUnavailable)
            }
        } else {
            Err($crate::events::ListenError::RequirementDeleted)
        }
    };

    // A single-argument version
    (@ generate locks $s:ident, $f:ident, $e:ident,
        $name0:ident, $mutability0:ident, $data_type0: ty
        ) => {

        if let Some(arc) = std::sync::Weak::upgrade(&$s.$name0) {
            match $crate::lock_data!( @ generate try mutability $mutability0 arc ) {
                Ok($crate::lock_data!( @ generate mutability $mutability0 guard )) => {
                    $f($e, $crate::lock_data!( @ generate mutability $mutability0 &guard));
                    Ok(())
                },
                _ => Err($crate::events::ListenError::LockUnavailable)
            }
        } else {
            Err($crate::events::ListenError::RequirementDeleted)
        }
    };

    // We need to capture the `self` variable due to Rust's variable hygiene.
    // It's in the variable `s` here.
    // We also need to capture the `func` that must be called, and the `event`.
    // We'll also need to pass a reference to the `guard` we made, for the same reason.
    (@ generate locks $s:ident, $f:ident, $e:ident,
        $name0:ident, $mutability0:ident, $data_type0: ty,
        $($tail:tt)* | $($mutability1:ident),* | $($guard1:ident),*
        ) => {

        if let Some(arc) = std::sync::Weak::upgrade(&$s.$name0) {
            match $crate::lock_data!( @ generate try mutability $mutability0 arc ) {
                Ok($crate::lock_data!( @ generate mutability $mutability0 guard)) => {
                    $crate::lock_data!{ @ generate locks $s, $f, $e, $($tail)* | $($mutability1),*, $mutability0 | $($guard1),*, guard }
                },
                _ => Err($crate::events::ListenError::LockUnavailable)
            }
        } else {
            Err($crate::events::ListenError::RequirementDeleted)
        }
    };

    // Another copy of the above function that doesn't have the guard variables at the end.
    (@ generate locks $s:ident, $f:ident, $e:ident,
        $name0:ident, $mutability0:ident, $data_type0: ty,
        $($tail:tt)*
        ) => {

        if let Some(arc) = std::sync::Weak::upgrade(&$s.$name0) {
            match $crate::lock_data!( @ generate try mutability $mutability0 arc ) {
                Ok($crate::lock_data!( @ generate mutability $mutability0 guard)) => {
                    $crate::lock_data!{ @ generate locks $s, $f, $e, $($tail)* | $mutability0 | guard }
                },
                _ => Err($crate::events::ListenError::LockUnavailable)
            }
        } else {
            Err($crate::events::ListenError::RequirementDeleted)
        }
    };

    (@ generate mutability read $thing:ident) => { $thing };
    (@ generate mutability write $thing:ident) => { mut $thing };
    (@ generate mutability read &$thing:ident) => { &$thing };
    (@ generate mutability write &$thing:ident) => { &mut $thing };
    (@ generate try mutability read $rwlock:ident) => { $rwlock.try_read() };
    (@ generate try mutability write $rwlock:ident) => { $rwlock.try_write() };
}