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
324
325
326
327
328
329
330
331
332
333
334
335
336
use std::collections::HashMap;
use std::mem::MaybeUninit;
use std::sync::Once;

#[macro_export]
macro_rules! resolve_object {
    ($args:ident, $idx:expr, $err_msg:expr, $rt:ty, $le:expr) => {{
        match $args.get($idx).expect(&$err_msg) {
            ResolvedNandoArgument::Object(o) => match o {
                ObjectArgument::RWObject(o) => {
                    $le.borrow_mut()
                        .add_object_to_read_set(o.get_id(), o.get_version());
                    let inner = unsafe {
                        o.read_into::<$rt>(None)
                            .expect("failed to resolve RW object")
                            .as_mut()
                    }
                    .unwrap();
                    o.maybe_set_inner_allocator(inner);
                    inner
                }
                _ => panic!("Could not resolve nando object arg {}", $idx),
            },
            o @ _ => panic!("Could not resolve nando object arg {}", $idx),
        }
    }};
}

#[macro_export]
macro_rules! resolve_read_only_object {
    ($args:ident, $idx:expr, $err_msg:expr, $rt:ty, $le:expr) => {{
        match $args.get($idx).expect(&$err_msg) {
            ResolvedNandoArgument::Object(o) => match o {
                ObjectArgument::RWObject(o) => {
                    $le.borrow_mut()
                        .add_object_to_read_set(o.get_id(), o.get_version());
                    unsafe {
                        &*o.read_into::<$rt>(None)
                            .expect("failed to resolve RW object as RO object")
                    }
                }
                ObjectArgument::ROObject(o) => {
                    $le.borrow_mut()
                        .add_object_to_read_set(o.get_id(), o.get_version());
                    o.read_into::<$rt>()
                }
                _ => panic!("Could not resolve nando object arg {}", $idx),
            },
            o @ _ => panic!("Could not resolve read-only nando object arg {}", $idx),
        }
    }};
}

#[macro_export]
macro_rules! resolve_objects {
    ($args:ident, $idx:expr, $err_msg:expr, $rt:ty, $le:expr) => {{
        match $args.get($idx).expect(&$err_msg) {
            ResolvedNandoArgument::Objects(ref os) => {
                let mut resolved_objects = Vec::with_capacity(os.len());
                for o in os {
                    match o {
                        ObjectArgument::RWObject(o) => {
                            $le.borrow_mut()
                                .add_object_to_read_set(o.get_id(), o.get_version());
                            let inner = unsafe {
                                o.read_into::<$rt>(None)
                                    .expect("failed to resolve RW object")
                                    .as_mut()
                            }
                            .unwrap();
                            o.maybe_set_inner_allocator(inner);
                            resolved_objects.push(inner);
                        }
                        _ => panic!("Could not resolve vec ref arg {}: {:?}", $idx, o),
                    }
                }
                resolved_objects
            }
            o @ _ => panic!(
                "Could not resolve vec ref arg, not vec ref {}: {:?}",
                $idx, o
            ),
        }
    }};
}

#[macro_export]
macro_rules! resolve_read_only_objects {
    ($args:ident, $idx:expr, $err_msg:expr, $rt:ty, $le:expr) => {{
        match $args.get($idx).expect(&$err_msg) {
            ResolvedNandoArgument::Objects(ref os) => {
                let mut resolved_objects = Vec::with_capacity(os.len());
                for o in os {
                    let resolved_object = match o {
                        ObjectArgument::RWObject(o) => {
                            $le.borrow_mut()
                                .add_object_to_read_set(o.get_id(), o.get_version());
                            unsafe {
                                &*o.read_into::<$rt>(None)
                                    .expect("failed to resolve RW object as RO object")
                            }
                        }
                        ObjectArgument::ROObject(o) => {
                            $le.borrow_mut()
                                .add_object_to_read_set(o.get_id(), o.get_version());
                            o.read_into::<$rt>()
                        }
                        _ => panic!("Could not resolve vec ref arg {}: {:?}", $idx, o),
                    };
                    resolved_objects.push(resolved_object);
                }

                resolved_objects
            }
            o @ _ => panic!(
                "Could not resolve vec ref arg, not vec ref {}: {:?}",
                $idx, o
            ),
        }
    }};
}

pub fn get_name_cache() -> &'static mut HashMap<String, String> {
    static mut INSTANCE: MaybeUninit<HashMap<String, String>> = MaybeUninit::uninit();
    static mut ONCE: Once = Once::new();
    unsafe {
        ONCE.call_once(|| {
            INSTANCE.as_mut_ptr().write(HashMap::with_capacity(64));
        });
    }
    unsafe { &mut *INSTANCE.as_mut_ptr() }
}

pub fn strip_trailing_generics(intent_name: &str) -> String {
    let name_cache = get_name_cache();

    match name_cache.get(intent_name) {
        Some(s) => s.clone(),
        None => {
            let stripped = match intent_name.contains("::") {
                false => intent_name.to_string(),
                true => match intent_name.ends_with('>') {
                    false => intent_name.to_string(),
                    true => {
                        let split_intent_name: Vec<&str> = intent_name.split("::").collect();
                        split_intent_name[0..split_intent_name.len() - 1].join("::")
                    }
                },
            };

            name_cache.insert(intent_name.to_string(), stripped.clone());
            stripped
        }
    }
}

#[macro_export]
macro_rules! format_intent_name {
    ($id:literal) => {{
        let base_id = nando_support::strip_trailing_generics($id);
        let namespace = object_lib::tls::get_current_namespace();
        match namespace.len() {
            0 => base_id.to_string(),
            _ => format!("{}::{}", namespace, base_id),
        }
    }};
}

#[macro_export]
macro_rules! nando_spawn {
    ($id:literal, $($arg:tt),*) => {{
        let mut spawn_intent = $crate::NandoActivationIntent {
            host_idx: None, name: $id.into(), args: vec![
                $($arg.into(),)*
            ],
        };
        object_lib::tls::add_new_pending_intent(spawn_intent)
    }};
}

#[macro_export]
macro_rules! nando_spawn_polymorphic {
    ($id:literal, $($arg:tt),*) => {{
        let namespaced_name = format_intent_name!($id);
        let mut spawn_intent = $crate::NandoActivationIntent {
            host_idx: None, name: namespaced_name, args: vec![
                $($arg.into(),)*
            ],
        };
        object_lib::tls::add_new_pending_intent(spawn_intent)
    }};
}

#[macro_export]
macro_rules! nando_yield {
    ($id:literal, $($arg:tt),*) => {{
        let mut continuation_intent = $crate::NandoActivationIntent {
            host_idx: None, name: $id.into(), args: vec![
                $($arg.into(),)*
            ],
        };
        object_lib::tls::add_continuation_intent(continuation_intent)
    }};
}

#[macro_export]
macro_rules! nando_yield_polymorphic {
    ($id:literal, $($arg:tt),*) => {{
        let namespaced_name = format_intent_name!($id);
        let mut continuation_intent = $crate::NandoActivationIntent {
            host_idx: None, name: namespaced_name, args: vec![
                $($arg.into(),)*
            ],
        };
        object_lib::tls::add_continuation_intent(continuation_intent)
    }};
}

#[macro_export]
macro_rules! nando_spawn_sink {
    ($id:literal, $($arg:tt),*) => {{
        let mut spawn_intent = $crate::NandoActivationIntent {
            host_idx: None, name: $id.into(), args: vec![
                $($arg.into(),)*
            ],
        };
        object_lib::tls::add_pending_with_control_dependencies(spawn_intent)
    }};
}

#[macro_export]
macro_rules! nando_yield_sink {
    ($id:literal, $deps:expr, $($arg:tt),*) => {{
        let mut spawn_intent = $crate::NandoActivationIntent {
            host_idx: None, name: $id.into(), args: vec![
                $($arg.into(),)*
            ],
        };
        object_lib::tls::add_continuation_with_control_dependencies(spawn_intent, $deps)
    }};
}

#[macro_export]
macro_rules! nando_yield_sink_polymorphic {
    ($id:literal, $deps:expr, $($arg:tt),*) => {{
        let namespaced_name = format_intent_name!($id);
        let mut spawn_intent = $crate::NandoActivationIntent {
            host_idx: None, name: namespaced_name, args: vec![
                $($arg.into(),)*
            ],
        };
        object_lib::tls::add_continuation_with_control_dependencies(spawn_intent, $deps)
    }};
}

#[macro_export]
macro_rules! bump_if_changed {
    ($obj:ident, $log_entry:expr) => {{
        match $obj {
            ObjectArgument::RWObject(o) => {
                let mut log_entry = $log_entry.borrow_mut();
                if log_entry.object_was_modified(o.get_id()) {
                    o.bump_version().expect("failed to bump object version");

                    #[cfg(debug_assertions)]
                    println!(
                        "bumped object {} to version {}",
                        o.get_id(),
                        o.get_version()
                    );

                    log_entry.add_object_to_write_set(o.get_id(), o.get_version());
                } else {
                    // Assume object was only read, update read counter. This only works for "real" objects
                    // -- for `MaterializedObject` instances, the backing object's read-access counter is
                    // updated at resolution time.
                    o.mark_read_access();
                }
            },
            _ => {},
        }
    }};
}

#[macro_export]
macro_rules! allocate_and_init {
    ($ot:ident, $ty:ty) => {{
        let obj = $ot
            .allocate(mem_size_of::<$ty>(), None)
            .expect("failed to allocate object");
        let inner_obj = obj.allocate::<$ty>().unwrap();
        obj.set_inner_allocator(inner_obj);

        #[cfg(debug_assertions)]
        println!(
            "[DEBUG] just allocated {} with type {}",
            obj.id,
            std::any::type_name::<$ty>()
        );

        obj
    }};
    ($ot:ident, $ty:ty, $id:expr) => {{
        let obj = $ot
            .allocate(mem_size_of::<$ty>(), $id)
            .expect("failed to allocate object with id {:?}", $id);
        let inner_obj = obj.allocate::<$ty>().unwrap();
        obj.set_inner_allocator(inner_obj);

        #[cfg(debug_assertions)]
        println!(
            "[DEBUG] just allocated {} (supplied id) with type {}",
            obj.id,
            std::any::type_name::<$ty>()
        );
        obj
    }};
}

#[macro_export]
macro_rules! iptr_of_ref {
    ($re:expr) => {{
        object_lib_tls::iptr_of(unit_ptr_of!($re)).unwrap()
    }};
}

#[macro_export]
macro_rules! register_initial {
    ($obj:ident, $obj_tracker:ident) => {{
        let _ = $obj.bump_version();
        if $obj.object_is_mv_enabled() {
            $obj_tracker.push_initial_version($obj.id, (&*$obj).into());
        }
        ownership_tracker_tls::mark_object_owned($obj.id);
    }};
}