jude 0.1.2

dynamic reloading of shared libraries
Documentation
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#![feature(trace_macros)]

#[macro_export]
macro_rules! as_item( ($i:item) => ($i) );

#[macro_export]
macro_rules! jude(
    (
        $(#[$attr:meta])*
        $vis:vis
        struct $name:ident $(<$($lifetime:lifetime),+>)* $body:tt
    ) => (
        jude!(parse
            [ $name ]
            [ $vis ]
            [ $(#[$attr])* ]
            [ $(<$($lifetime),+>)* ]
            [] [] [] [] [] [] $body
        );
    );

    // на этом этапе все фуркции и поля были разбиты на блоки поэтому остался только {}
    // передаю все блоки output
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {}
    ) => (
        jude!(output $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
        );
    );

    // парсинг функции с реализацией
    // такие функции обладают телом функции: $body:block
    // их передаю в исходном виде и никак не изменяем
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis $(<$($lifetime:lifetime),+>)*
            fn $name:ident($($tt:tt)*) $(-> $ret:ty)? $body:block, $($t:tt)*
        }
    ) => (
        jude!(parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* $(#[$attr])* $vis $(<$($lifetime),+>)* fn $name($($tt)*) $(-> $ret)? $body ]
            [ $($fn_not_impl)* ]
            { $($t)* }
        );
    );

    // парсинг функций без реализации
    // такие функции нужно разбить на части для корректного добавления в member_impl, field_impl, fn блоки
    // такиим функциям будет дописано тело функции, которое содержит вызов
    // из загруженной динамической библиотеки

    // это парсинг фукнции с &mut self первым аргументом
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis $(<$($lifetime:lifetime),+>)*
            fn $name:ident(&mut self $(,)? $($item:ident:$ty:ty),*) $(-> $ret:ty)?, $($t:tt)*
        }
    ) => (
        jude!(parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            {
                [$(#[$attr])* $vis $(<$($lifetime),+>)*],
                [fn $name],
                [self], [&mut Self,], [&mut self,], [self,],
                [$($item:$ty),*], [$(-> $ret)?], $($t)*
            }
        );
    );

    // это парсинг фукнции с &self первым аргументом
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis $(<$($lifetime:lifetime),+>)*
            fn $name:ident(&self $(,$item:ident:$ty:ty)*) $(-> $ret:ty)?, $($t:tt)*
        }
    ) => (
        jude!( parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            {
                [$(#[$attr])* $vis $(<$($lifetime),+>)*],
                [fn $name],
                [self], [&Self,], [&self,], [self,],
                [$($item:$ty),*], [$(-> $ret)?], $($t)*
            }
        );
    );

    // это парсинг фукнции с self первым аргументом
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis $(<$($lifetime:lifetime),+>)*
            fn $name:ident(self $(,$item:ident:$ty:ty)*) $(-> $ret:ty)?, $($t:tt)*
        }
    ) => (
        jude!( parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            {
                [$(#[$attr])* $vis $(<$($lifetime),+>)*],
                [fn $name],
                [self], [Self,], [self,], [self,],
                [$($item:$ty),*], [$(-> $ret)?], $($t)*
            }
        );
    );

    // это парсинг фукнции без первого аргумента с типами: self, &self, &mut self
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis $(<$($lifetime:lifetime),+>)*
            fn $name:ident($($item:ident:$ty:ty)*) $(-> $ret:ty)?, $($t:tt)*
        }
    ) => (
        jude!( parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            {
                [$(#[$attr])* $vis $(<$($lifetime),+>)*],
                [fn $name],
                [self], [], [&self,], [],
                [$($item:$ty),*], [$(-> $ret)?], $($t)*
            }
        );
    );

    // после парсинга функций без реализации с первым аргументом:: self, &self, &mut self
    // происходит формирование блоков member_impl, field_impl, fn
    // - member_impl - список полей структуры, который будет отображен в блоке struct
    // - field_impl - это выражения через которые заполняются поля указателей через подгрузку динамической библиокети в конструкторе
    // - fn - список функций в struct_impl блоке где происходит вызов функции из динамической библиокеки
    // далее из этих блоков будет составлена struct и struct_impl блоки с полями и функциями
    // функции не имеющие реализацию будут иметь поле указатель (member_impl) с названием этой функции
    // данный указатель будет заполняться в конструкторе через загрузку динамической библиотеки
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            [$fnattr:tt],
            [fn $name:ident],
            [$self:tt],
            [$($member_impl_self:tt)*],
            [$($fn_struct_decl_self:tt)*],
            [$($fn_call_self:tt)*],
            [$($item:ident : $ty:ty),*],
            [$(-> $ret:ty)?],
            $($t:tt)*
        }
    ) => (
        jude!(parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* $name: fn($($member_impl_self)* $($ty),*) $(-> $ret)?, ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* $name, ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* $fnattr fn $name($($fn_struct_decl_self)* $($item:$ty),*) $(-> $ret)? {
                ($self.$name)($($fn_call_self)* $($item),*)
            }]
            { $($t)* }
        );
    );

    // это парсинг полей структуры
    // значения которых вычисляется через выражение с блоком $body:block
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis
            $name:ident: $(<$($lifetime:lifetime),+>)* $typ:ty = $body:block, $($t:tt)*
        }
    ) => (
        jude!(parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* $(#[$attr])* $vis $name: $(<$($lifetime),+>)* $typ, ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* $name: $body, ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            { $($t)* }
        );
    );

    // это парсинг полей структуры
    // значения которых вычисляется через явное назначение литерала
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis
            $name:ident: $(<$($lifetime:lifetime),+>)* $typ:ty = $body:literal, $($t:tt)*
        }
    ) => (
        jude!(parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* $(#[$attr])* $vis $name: $(<$($lifetime),+>)* $typ, ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* $name: $body, ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            { $($t)* }
        );
    );

    // это парсинг полей структуры
    // значения которых вычисляется через явное назначение expr
    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis
            $name:ident: $(<$($lifetime:lifetime),+>)* $typ:ty = $($body:expr)+, $($t:tt)*
        }
    ) => (
        jude!(parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* $(#[$attr])* $vis $name: $(<$($lifetime),+>)* $typ, ]
            [ $($member_not_impl)* ]
            [ $($field_impl)* $name: $($body)+, ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            { $($t)* }
        );
    );

    (
        parse $struct_name:tt $struct_vis:tt $struct_attr:tt $struct_lifetime:tt
        [ $($member_impl:tt)* ]
        [ $($member_not_impl:tt)* ]
        [ $($field_impl:tt)* ]
        [ $($field_not_impl:tt)* ]
        [ $($fn_impl:tt)* ]
        [ $($fn_not_impl:tt)* ]
        {
            $(#[$attr:meta])*
            $vis:vis
            $name:ident: $(<$($lifetime:lifetime),+>)* $typ:ty, $($t:tt)*
        }
    ) => (
        jude!(parse $struct_name $struct_vis $struct_attr $struct_lifetime
            [ $($member_impl)* ]
            [ $($member_not_impl)* $(#[$attr])* $vis $name: $(<$($lifetime),+>)* $typ, ]
            [ $($field_impl)* ]
            [ $($field_not_impl)* ]
            [ $($fn_impl)* ]
            [ $($fn_not_impl)* ]
            { $($t)* }
        );
    );

    // если нет полей и методов без реализации
    // то создаем структуру без _load_from
    (
        output
            [ $struct_name:tt ]
            [ $struct_vis:tt ]
            [ $(#[$struct_attr:meta])* ]
            [ $(<$($struct_lifetime:lifetime),+>)* ]
            [ $($member_impl:tt)* ]
            [ ]
            [ $($field_impl:tt)* ]
            [ ]
            [ $($fn_impl:tt)* ]
            [ ]
    )
    => (
        $crate::as_item!(
            $(#[$struct_attr])*
            $struct_vis struct $struct_name $(<$($struct_lifetime),+>)* {
                $($member_impl)*
            }
        );

        $crate::as_item!(
            impl $(<$($struct_lifetime),+>)* $struct_name $(<$($struct_lifetime),+>)* {
                $($fn_impl)*
            }
        );

        $crate::as_item!(
            impl $(<$($struct_lifetime),+>)* std::default::Default for $struct_name $(<$($struct_lifetime),+>)* {
                fn default() -> Self {
                    Self {
                        $($field_impl)*
                    }
                }
            }
        );
    );

    (
        output
            [ $struct_name:tt ]
            [ $struct_vis:tt ]
            [ $(#[$struct_attr:meta])* ]
            [ $(<$($struct_lifetime:lifetime),+>)* ]
            [ $($member_impl:tt)* ]
            [ $($member_not_impl:tt)* ]
            [ $($field_impl:tt)* ]
            [ $($field_not_impl:tt, )* ]
            [ $($fn_impl:tt)* ]
            [ $($fn_not_impl:tt)* ]
    )
    => (
        $crate::as_item!(
            $(#[$struct_attr])*
            $struct_vis struct $struct_name $(<$($struct_lifetime),+>)* {
                $($member_impl)*
                $($member_not_impl)*
                __from_file: std::ffi::OsString,
                __from_lib: std::sync::Arc<libloading::Library>,
                __modified: std::time::SystemTime,
            }
        );

        $crate::as_item!(
            impl $(<$($struct_lifetime),+>)* $struct_name $(<$($struct_lifetime),+>)* {
                $($fn_impl)*
            }
        );

        $crate::as_item!(
            impl $(<$($struct_lifetime),+>)* $struct_name $(<$($struct_lifetime),+>)* {
                $($fn_not_impl)*

                fn _load_from(file_path: std::ffi::OsString) -> Result<Self, libloading::Error> { //Result<Self, $crate::JudeError> {
                    let lib = unsafe {
                        libloading::Library::new(&file_path)
                    }?;

                    let modified = std::fs::metadata(&file_path).unwrap();
                    let modified = modified.modified().unwrap();

                    let res = Self {
                        $($field_impl)*
                        $(
                            $field_not_impl: {
                                let symbol = unsafe {
                                    lib.get(stringify!($field_not_impl).as_bytes())
                                }?;

                                *symbol
                            },
                        )*
                        __from_file: file_path,
                        __from_lib: std::sync::Arc::new(lib),
                        __modified: modified,
                    };

                    Ok(res)
                }

                fn _reload(&mut self) -> Result<(), libloading::Error> {
                    let n = Self::_load_from(self.__from_file.clone())?;

                    $(
                        self.$field_not_impl = n.$field_not_impl;
                    )*

                    self.__from_lib = n.__from_lib.clone();
                    self.__from_file = n.__from_file.clone();
                    self.__modified = n.__modified.clone();

                    Ok(())
                }

                fn _is_changed(&self) -> Result<bool, std::io::Error> {
                    let modified = std::fs::metadata(&self.__from_file)?;
                    let modified = modified.modified()?;

                    match modified.duration_since(self.__modified) {
                        Ok(x) => {
                            Ok(!x.is_zero())
                        },
                        Err(e) => Ok(false),
                    }
                }
            }
        );
    );
);