zng_unique_id/
hot_reload.rs

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
// # Full API
//
// The full API is implemented in `zng-ext-hot-reload`, `HOT_STATICS` and `hot_static` are declared
// in this crate to only to be reachable in more workspace crates.

/// Declares a patchable static.
///
/// In builds with Cargo feature `hot_reload` this generates an unsafe static double reference that can be addressed by name and
/// patched in a dynamically loaded build of the exact same crate.
///
/// Use [`hot_static_ref!`] to safely reference the static, attempting to access the variable in any other way is undefined behavior.
///
/// Note that you can only declare private static items, this is by design, you can share the [`hot_static_ref!`] output at
/// a higher visibility.
///
/// See `zng::hot_reload` for more details and links to the full API. This macro is declared on the `zng-unique-id` crate
/// only to avoid circular dependencies in the Zng workspace.
///
/// [`hot_static_ref!`]: crate::hot_static_ref!
#[macro_export]
macro_rules! hot_static {
    (
        static $IDENT:ident: $Ty:ty = $init:expr;
    ) => {
        $crate::hot_reload::hot_static_impl! {
            static $IDENT: $Ty = $init;
        }
    };
}

/// Static reference to a [`hot_static!`].
///
/// [`hot_static!`]: crate::hot_static!
#[macro_export]
macro_rules! hot_static_ref {
    ($PATH:path) => {
        $crate::hot_reload::hot_static_ref_impl!($PATH)
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! hot_static_not_patchable {
    (
        static $IDENT:ident: $Ty:ty = $init:expr;
    ) => {
        static $IDENT: $Ty = $init;
    };
}
#[doc(hidden)]
#[macro_export]
macro_rules! hot_static_patchable {
    (
        $vis:vis static $IDENT:ident: $Ty:ty = $init:expr;
    ) => {
        $crate::paste! {
            struct [<_K $IDENT:camel>];
            impl $crate::hot_reload::PatchKey for [<_K $IDENT:camel>] {
                fn id(&'static self) -> &'static str {
                    std::any::type_name::<[<_K $IDENT:camel>]>()
                }
            }

            static [<$IDENT _COLD>] : $Ty = $init;
            #[allow(non_camel_case_types)]
            static mut $IDENT: &$Ty = &[<$IDENT _COLD>];
            #[allow(non_snake_case)]
            unsafe fn [<$IDENT _INIT>](static_ptr: *const ()) -> *const () {
                $crate::hot_reload::init_static(&mut $IDENT, static_ptr)
            }

            // expanded from:
            // #[linkme::distributed_slice(HOT_STATICS)]
            // static _HOT_STATICS: fn(&FooArgs) = _foo;
            // so that users don't need to depend on linkme just to call this macro.
            #[used]
            #[cfg_attr(
                any(
                    target_os = "none",
                    target_os = "linux",
                    target_os = "android",
                    target_os = "fuchsia",
                    target_os = "psp"
                ),
                unsafe(link_section = "linkme_HOT_STATICS")
            )]
            #[cfg_attr(
                any(target_os = "macos", target_os = "ios", target_os = "tvos"),
                unsafe(link_section = "__DATA,__linkmeAGDMMOwP,regular,no_dead_strip")
            )]
            #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe(link_section = ".linkme_HOT_STATICS$b"))]
            #[cfg_attr(target_os = "illumos", unsafe(link_section = "set_linkme_HOT_STATICS"))]
            #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe(link_section = "linkme_HOT_STATICS"))]
            #[doc(hidden)]
            static [<$IDENT _REGISTER>]: (&'static dyn $crate::hot_reload::PatchKey, unsafe fn(*const ()) -> *const ()) = (
                &[<_K $IDENT:camel>],
                [<$IDENT _INIT>]
            );

        }
    };
}

#[doc(hidden)]
pub unsafe fn init_static<T>(s: &mut &'static T, static_ptr: *const ()) -> *const () {
    if static_ptr.is_null() {
        *s as *const T as *const ()
    } else {
        *s = &*(static_ptr as *const T);
        std::ptr::null()
    }
}

use std::{any::Any, fmt, ops};

#[doc(hidden)]
#[cfg(not(feature = "hot_reload"))]
pub use crate::hot_static_not_patchable as hot_static_impl;

#[doc(hidden)]
#[cfg(feature = "hot_reload")]
pub use crate::hot_static_patchable as hot_static_impl;

#[doc(hidden)]
#[macro_export]
macro_rules! hot_static_ref_not_patchable {
    ($PATH:path) => {
        &$PATH
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! hot_static_ref_patchable {
    ($PATH:path) => {
        // SAFETY: hot_static does not mutate after dylib init.
        unsafe { $PATH }
    };
}

#[doc(hidden)]
#[cfg(not(feature = "hot_reload"))]
pub use crate::hot_static_ref_not_patchable as hot_static_ref_impl;

#[doc(hidden)]
#[cfg(feature = "hot_reload")]
pub use crate::hot_static_ref_patchable as hot_static_ref_impl;

#[doc(hidden)]
#[cfg(feature = "hot_reload")]
#[linkme::distributed_slice]
pub static HOT_STATICS: [(&'static dyn PatchKey, unsafe fn(*const ()) -> *const ())];

#[doc(hidden)]
pub trait PatchKey: Send + Sync + Any {
    fn id(&'static self) -> &'static str;
}
impl PartialEq for &'static dyn PatchKey {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}
impl Eq for &'static dyn PatchKey {}
impl std::hash::Hash for &'static dyn PatchKey {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        std::hash::Hash::hash(self.id(), state)
    }
}
impl fmt::Debug for &'static dyn PatchKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.id(), f)
    }
}

#[doc(hidden)]
pub use once_cell::sync::OnceCell as OnceCellLazy;

#[doc(hidden)]
pub struct Lazy<T: 'static> {
    #[cfg(feature = "hot_reload")]
    inner: fn(&mut Option<T>) -> &'static T,
    #[cfg(not(feature = "hot_reload"))]
    inner: (OnceCellLazy<T>, fn() -> T),
}

impl<T: 'static> Lazy<T> {
    #[doc(hidden)]
    #[cfg(feature = "hot_reload")]
    pub const fn new(inner: fn(&mut Option<T>) -> &'static T) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[cfg(not(feature = "hot_reload"))]
    pub const fn new(init: fn() -> T) -> Self {
        Self {
            inner: (OnceCellLazy::new(), init),
        }
    }
}
impl<T: 'static> ops::Deref for Lazy<T> {
    type Target = T;

    #[cfg(feature = "hot_reload")]
    fn deref(&self) -> &Self::Target {
        (self.inner)(&mut None)
    }

    #[cfg(not(feature = "hot_reload"))]
    fn deref(&self) -> &Self::Target {
        self.inner.0.get_or_init(|| (self.inner.1)())
    }
}

/// Initializes a [`lazy_static!`] with a custom value if it is not yet inited.
///
/// [`lazy_static!`]: crate::lazy_static
pub fn lazy_static_init<T>(lazy_static: &'static Lazy<T>, value: T) -> Result<&'static T, T> {
    let mut value = Some(value);

    #[cfg(feature = "hot_reload")]
    let r = (lazy_static.inner)(&mut value);
    #[cfg(not(feature = "hot_reload"))]
    let r = {
        let (lazy, _) = &lazy_static.inner;
        lazy.get_or_init(|| value.take().unwrap())
    };

    match value {
        Some(v) => Err(v),
        None => Ok(r),
    }
}

#[doc(hidden)]
#[cfg(feature = "hot_reload")]
pub fn lazy_static_ref<T>(lazy_static: &'static OnceCellLazy<T>, init: fn() -> T, override_init: &mut Option<T>) -> &'static T {
    lazy_static.get_or_init(|| match override_init.take() {
        Some(o) => o,
        None => init(),
    })
}

/// Implementation of `lazy_static!` that supports hot reloading.
///
/// The syntax is similar to the [`lazy_static`](https://docs.rs/lazy_static) crate,
/// but the generated code uses the [`once_cell::sync::Lazy`](https://docs.rs/once_cell/once_cell/sync/struct.Lazy.html)
/// type internally.
#[macro_export]
macro_rules! lazy_static {
    ($(
        $(#[$attr:meta])*
        $vis:vis static ref $N:ident : $T:ty = $e:expr;
    )+) => {
        $(
           $crate::hot_reload::lazy_static_impl! {
                $(#[$attr])*
                $vis static ref $N : $T = $e;
           }
        )+
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! lazy_static_patchable {
    (
        $(#[$attr:meta])*
        $vis:vis static ref $N:ident : $T:ty = $e:expr;
    ) => {
        $crate::paste! {
            fn [<_ $N:lower _hot>](__override: &mut Option<$T>) -> &'static $T {
                fn __init() -> $T {
                    $e
                }
                $crate::hot_static! {
                    static IMPL: $crate::hot_reload::OnceCellLazy<$T> = $crate::hot_reload::OnceCellLazy::new();
                }
                $crate::hot_reload::lazy_static_ref($crate::hot_static_ref!(IMPL), __init, __override)
            }

            $(#[$attr])*
            $vis static $N: $crate::hot_reload::Lazy<$T> = $crate::hot_reload::Lazy::new([<_ $N:lower _hot>]);
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! lazy_static_not_patchable {
    (
        $(#[$attr:meta])*
        $vis:vis static ref $N:ident : $T:ty = $e:expr;
    ) => {
        $crate::paste! {
            fn [<_ $N:lower _init>]() -> $T {
                $e
            }

            $(#[$attr])*
            $vis static $N: $crate::hot_reload::Lazy<$T> = $crate::hot_reload::Lazy::new([<_ $N:lower _init>]);
        }
    };
}

#[doc(hidden)]
#[cfg(not(feature = "hot_reload"))]
pub use crate::lazy_static_not_patchable as lazy_static_impl;

#[doc(hidden)]
#[cfg(feature = "hot_reload")]
pub use crate::lazy_static_patchable as lazy_static_impl;