basic-oop 0.8.3

Simple OOP for Rust.
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
#![feature(macro_metavar_expr_concat)]

#![deny(warnings)]
#![doc(test(attr(deny(warnings))))]
#![doc(test(attr(allow(dead_code))))]
#![doc(test(attr(allow(unused_variables))))]
#![allow(clippy::needless_doctest_main)]

//! The crate provides basic tools for writing object-oriented code in Rust.
//! Very basic: no multiply inheritance, no generics, no interfaces
//! (but this can be added in future in a limited form), no incapsulation.
//! All classes in hierarchy should have distinct names even if they are located in different modules.
//!
//! # How to define a class
//!
//! First you need to _import_ the parent class. All classes should be derived from some parent
//! class. The only class not having any parent is `Obj` defined in `basic_oop::obj` module. It contains
//! no fields or methods. Lets import it:
//!
//! ```ignore
//! import! { pub test_class:
//!     use [obj basic_oop::obj];
//! }
//! ```
//!
//! Here `test_class` correspond to our new class name.
//! (Although it is possible to use different names in the import section and in the class definition,
//! doing so is not recommended to avoid confusion among users of the class.)
//!
//! The pub keyword means that our class will be public. In case of a private class, it should be omitted.
//!
//! All types that we plan to use in the method signatures of our class
//! should also be imported as unique names. For example:
//!
//! ```ignore
//! import! { pub test_class:
//!     use [obj basic_oop::obj];
//!     use std::rc::Rc;
//!     use std::rc::Weak as rc_Weak;
//! }
//! ```
//! 
//! Now we can start to define our class using [`class_unsafe`] macro.
//!
//! Classes defined with the [`class_unsafe`] macro are intended for use either with the [`Rc`](alloc::rc::Rc)
//! smart pointer or with the [`Arc`](alloc::sync::Arc) smart pointer.
//!
//! Suppose we don't need reference counter atomicity. Then our class
//! definition will be the next:
//!
//! ```ignore
//! #[class_unsafe(inherits_Obj)]
//! pub struct TestClass { }
//! ```
//!
//! Each class should have two constructors: one for creating this particular class
//! and one for calling it from the constructor of the inheritor:
//!
//! ```ignore
//! impl TestClass {
//!     pub fn new() -> Rc<dyn IsTestClass> {
//!         Rc::new(unsafe { Self::new_raw(TEST_CLASS_VTABLE.as_ptr()) })
//!     }
//!
//!     pub unsafe fn new_raw(vtable: Vtable) -> Self {
//!         TestClass { obj: unsafe { Obj::new_raw(vtable) } }
//!     }
//! }
//! ```
//!
//! # Fields
//!
//! To add a field to class, we just write it in ordinar way:
//!
//! ```ignore
//! #[class_unsafe(inherits_Obj)]
//! pub struct TestClass {
//!     field: RefCell<Rc<String>>,
//! }
//!
//! impl TestClass {
//!     pub fn new(field: Rc<String>) -> Rc<dyn IsTestClass> {
//!         Rc::new(unsafe { Self::new_raw(field, TEST_CLASS_VTABLE.as_ptr()) })
//!     }
//!
//!     pub unsafe fn new_raw(field: Rc<String>, vtable: Vtable) -> Self {
//!         TestClass {
//!             obj: unsafe { Obj::new_raw(vtable) },
//!             field: RefCell::new(field),
//!         }
//!     }
//! }
//! ```
//!
//! # Non-virtual methods
//!
//! To add a method, it is needed to specify a fictive field with `#[non_virt]` attribute and
//! function type:
//!
//! ```ignore
//! #[class_unsafe(inherits_Obj)]
//! pub struct TestClass {
//!     ...
//!     #[non_virt]
//!     get_field: fn() -> Rc<String>,
//! }
//! ```
//!
//! Then `TestClassExt` extension trait will be generated contained appropriate function calling
//! `TestClass::get_field_impl`. We must provide this implementing function:
//!
//! ```ignore
//! impl TestClass {
//!     fn get_field_impl(this: &Rc<dyn IsTestClass>) -> Rc<String> {
//!         this.test_class().field.borrow().clone()
//!     }
//! }
//! ```
//!
//! # Virtual methods
//!
//! Adding a virtual method is no different from adding a non-virtual method only this time
//! we use `virt`:
//!
//! ```ignore
//! #[class_unsafe(inherits_Obj)]
//! pub struct TestClass {
//!     ...
//!     #[virt]
//!     set_field: fn(value: Rc<String>),
//! }
//!
//! impl TestClass {
//!     fn set_field_impl(this: &Rc<dyn IsTestClass>, value: Rc<String>) {
//!         *this.test_class().field.borrow_mut() = value;
//!     }
//! }
//! ```
//!
//! # Derived class. Method overriding.
//!
//! Lets import our class and derive another one from it:
//!
//! ```ignore
//! import! { pub derived_class:
//!     use [test_class crate::test_class];
//! }
//!
//! #[class_unsafe(inherits_TestClass)]
//! pub struct DerivedClass {
//! }
//! ```
//!
//! Now we wants to override `set_field`, how we do it? Simple:
//!
//! ```ignore
//! #[class_unsafe(inherits_TestClass)]
//! pub struct DerivedClass {
//!     #[over]
//!     set_field: (),
//! }
//!
//! impl DerivedClass {
//!     pub fn set_field_impl(this: &Rc<dyn IsTestClass>, value: Rc<String>) {
//!         let value = /* coerce value */;
//!         TestClass::set_field_impl(this, value);
//!     }
//! }
//! ```
//!
//! The type of the overridden function is already known from the base class definition,
//! so there is no need to re-write it, which is why the type of the phony field is specified as `()`.
//!
//! # Using the class.
//!
//! We can create instance of derived class:
//!
//! ```ignore
//! let class = DerivedClass::new(Rc::new("initial".to_string()));
//! ```
//!
//! We can cast it to base class:
//!
//! ```ignore
//! let base_class: Rc<dyn IsTestClass> = dyn_cast_rc(class).unwrap();
//! ```
//!
//! We can call both virtual and non-virtual methods:
//!
//! ```ignore
//! assert_eq!(base_class.get_field().as_ref(), "initial");
//! base_class.set_field(Rc::new("changed".to_string()));
//! assert_eq!(base_class.get_field().as_ref(), "changed coerced");
//! ```
//!
//! See full working example in README.md
//!
//! # Arc-based classes
//!
//! To get a class based on [`Arc`](alloc::sync::Arc) instead of [`Rc`](alloc::rc::Rc),
//! use use [`ObjSync`](obj_sync::ObjSync) instead of [`Obj`](obj::Obj):
//!
//! ```ignore
//! import! { pub test_class:
//!     use [obj_sync basic_oop::obj_sync];
//!     ...
//! }
//! #[class_unsafe(inherits_ObjSync)]
//! pub struct TestClass { }
//! ```

#![no_std]

extern crate alloc;

#[doc=include_str!("../README.md")]
type _DocTestReadme = ();

#[doc(hidden)]
pub use macro_magic;

/// Generates class and appropriate helper types and traits.
///
/// Usage:
///
/// ```ignore
/// #[class_unsafe(inherits_ParentClass)]
/// struct Class {
///     field: FieldType,
///     #[non_virt]
///     non_virtual_method: fn(args: ArgsType) -> ResultType,
///     #[virt]
///     virtual_method: fn(args: ArgsType) -> ResultType,
///     #[over]
///     parent_virtual_method: (),
/// }
///
/// impl Class {
///     fn non_virtual_method_impl(this: Rc<dyn IsClass>, args: ArgsType) -> ResultType {
///         ...
///     }
///
///     fn virtual_method_impl(this: Rc<dyn IsClass>, args: ArgsType) -> ResultType {
///         ...
///     }
///
///     fn parent_virtual_method_impl(this: Rc<dyn IsParentClass>, args: ArgsType) -> ResultType {
///         let base_result = ParentClass::parent_virtual_method_impl(this, args);
///         ...
///     }
/// }
/// ```
///
/// For a more detailed overview, please refer to the crate documentation.
///
/// # Safety
///
/// This macro may produce unsound code if the argument to the macro differs
/// from `inherits_Obj`/`inherits_Obj_sync` [`import`]ed from the [`obj`] module
/// and another `inherits_...` generated by this macro for a direct or indirect inheritor of `Obj`.
///
/// In other words, it is safe to use this macro as long as you
/// don't try to manually create something that this macro will accept as a valid argument.
///
/// It must also be guaranteed that the generated class cannot be constructed with an invalid vtable,
/// that is, any vtable other than the one generated by this macro
/// for this class or its direct or indirect inheritor.
///
/// This is usually achieved by providing two constructors:
/// a safe one that creates a class with a precisely known, guaranteed safe table,
/// and an unsafe one for inheritors that enforces the specified requirement. For example:
///
/// ```ignore
/// #[class_unsafe(inherits_SomeBaseClass)]
/// pub struct SomeClass { }
///
/// impl SomeClass {
///     pub fn new(param: ParamType) -> Rc<dyn IsSomeClass> {
///         Rc::new(unsafe { Self::new_raw(param, SOME_CLASS_VTABLE.as_ptr()) })
///     }
///
///     pub unsafe fn new_raw(param: ParamType, vtable: Vtable) -> Self {
///         SomeClass { some_base_class: unsafe { SomeBaseClass::new_raw(param, vtable) } }
///     }
/// }
/// ```
pub use basic_oop_macro::class_unsafe;

#[doc(hidden)]
pub use alloc::rc::Rc as alloc_rc_Rc;
#[doc(hidden)]
pub use alloc::sync::Arc as alloc_sync_Arc;
#[doc(hidden)]
pub use core::mem::transmute as core_mem_transmute;
#[doc(hidden)]
pub use dynamic_cast::SupportsInterfaces as dynamic_cast_SupportsInterfaces;
#[doc(hidden)]
pub use dynamic_cast::impl_supports_interfaces as dynamic_cast_impl_supports_interfaces;

/// The pointer to the table containing pointers to class virtual functions.
///
/// Use [`class_unsafe`] macro to generate `Vtable`.
pub type Vtable = *const *const ();

#[doc(hidden)]
#[repr(C)]
pub struct VtableJoin<const A: usize, const B: usize> {
    pub a: [*const (); A],
    pub b: [*const (); B],
}

/// Imports base class into the current scope so that it can be inherited from.
///
/// The macro accepts input in the following form:
///
/// ```ignore
/// $vis:vis $class:ident :
/// use $([$base:ident $path:path])+ ;
/// $( $(#[$attr:meta])* use $($custom_use:tt)+ ; )*
/// ```
///
/// See module documentation for explanation how to use it.
#[macro_export]
macro_rules! import {
    (
        $vis:vis $class:ident :
        use $([$base:ident $($path:tt)*])+ ;
        $($custom_use:tt)*
    ) => {
        $vis mod ${concat($class, _types)} {
            //! Some reexported types and other things.
            //!
            //! Used by the [`import`] macro, not intended for direct use in code.
            $(
                #[allow(unused_imports)]
                pub use $($path)*::*;
                #[allow(unused_imports)]
                pub use $($path)*:: ${concat($base, _types)} ::*;
            )+
            $crate::import_impl! { @split [] [$($custom_use)*] }
        }
        use ${concat($class, _types)} ::*;
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! import_impl {
    (
        @split [$($t:tt)*] [ ; $($custom_use:tt)*]
    ) => {
        $crate::import_impl! { @use [$($t)* ; ] }
        $crate::import_impl! { @split [] [$($custom_use)*] }
    };
    (
        @split [$($t:tt)*] [$x:tt $($custom_use:tt)*]
    ) => {
        $crate::import_impl! { @split [$($t)* $x] [$($custom_use)*] }
    };
    (
        @split [] []
    ) => {
    };
    (
        @split [$($t:tt)+] []
    ) => {
        $crate::import_impl! { @use [$($t)+] }
    };
    (
        @use [$(#[$attr:meta])* use $($list:tt)*]
    ) => {
        $(#[$attr])*
        #[allow(unused_imports)]
        pub use $($list)*
    };
}

pub mod obj {
    use alloc::rc::Rc;
    use downcast_rs::{Downcast, impl_downcast};
    use dynamic_cast::{SupportsInterfaces, impl_supports_interfaces};
    use macro_magic::export_tokens_no_emit;
    use crate::Vtable;

    pub mod obj_types {
        //! Some reexported types and other things.
        //!
        //! Used by the [`import`] macro, not intended for direct use in code.
    }

    #[export_tokens_no_emit]
    #[non_sync]
    struct inherits_Obj { __class__: Obj }

    /// Base class, contains no fields or methods. For [`Rc`]-based classes.
    ///
    /// Use [`import`] and [`class_unsafe`](crate::class_unsafe) macros
    /// to define a class inherited from `Obj`:
    ///
    /// ```ignore
    /// #[class_unsafe(inherits_Obj)]
    /// struct Class { }
    /// ```
    #[derive(Debug, Clone)]
    pub struct Obj {
        vtable: Vtable,
    }

    unsafe impl Send for Obj { }

    unsafe impl Sync for Obj { }

    impl Obj {
        /// Creates new `Obj` class instance, wrapped in [`Rc`] smart pointer.
        ///
        /// A rarely used function, since it creates `Obj` itself, not one of its inheritors.
        #[allow(clippy::new_ret_no_self)]
        pub fn new() -> Rc<dyn IsObj> {
            Rc::new(unsafe { Self::new_raw(OBJ_VTABLE.as_ptr()) })
        }

        /// Creates new `Obj`.
        ///
        /// Intended to be called from inheritors constructors to initialize a base type field.
        ///
        /// # Safety
        ///
        /// Calling this function is safe iff vtable is empty or
        /// generated using the [`class_unsafe`](crate::class_unsafe) macro on a
        /// direct or indirect `Obj` inheritor.
        pub unsafe fn new_raw(vtable: Vtable) -> Self {
            Obj { vtable }
        }

        /// Returns vtable, passed to the constructor.
        pub fn vtable(&self) -> Vtable { self.vtable }
    }

    /// Represents [`Obj`] or any of its inheritors.
    ///
    /// Usually obtained by using
    /// [`dyn_cast_rc`](dynamic_cast::dyn_cast_rc)
    /// on a derived trait.
    pub trait IsObj: SupportsInterfaces + Downcast {
        /// Returns reference to inner data.
        fn obj(&self) -> &Obj;

        /// Converts to inner data.
        fn into_obj(self) -> Obj where Self: Sized;
    }

    impl_supports_interfaces!(Obj: IsObj);

    impl_downcast!(IsObj);

    impl IsObj for Obj {
        fn obj(&self) -> &Obj { self }

        fn into_obj(self) -> Obj { self }
    }

    /// [`Obj`] virtual methods list.
    ///
    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
    #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
    #[repr(usize)]
    pub enum ObjVirtMethods {
        VirtMethodsCount = 0usize,
    }

    /// [`Obj`] virtual methods table.
    ///
    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
    pub struct ObjVtable(pub [*const (); ObjVirtMethods::VirtMethodsCount as usize]);

    impl ObjVtable {
        /// Creates [`Obj`] virtual methods table.
        ///
        /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
        #[allow(clippy::new_without_default)]
        pub const fn new() -> Self {
            ObjVtable([])
        }
    }

    const OBJ_VTABLE: [*const (); ObjVirtMethods::VirtMethodsCount as usize] = ObjVtable::new().0;
}

pub mod obj_sync {
    use alloc::sync::Arc;
    use downcast_rs::{DowncastSync, impl_downcast};
    use dynamic_cast::{SupportsInterfaces, impl_supports_interfaces};
    use macro_magic::export_tokens_no_emit;
    use crate::Vtable;

    pub mod obj_sync_types {
        //! Some reexported types and other things.
        //!
        //! Used by the [`import`] macro, not intended for direct use in code.
    }

    #[export_tokens_no_emit]
    #[sync]
    struct inherits_ObjSync { __class__: ObjSync }

    /// Base class, contains no fields or methods. For [`Arc`]-based classes.
    ///
    /// Use [`import`] and [`class_unsafe`](crate::class_unsafe) macros
    /// to define a class inherited from `ObjSync`:
    ///
    /// ```ignore
    /// #[class_unsafe(inherits_ObjSync)]
    /// struct Class { }
    /// ```
    #[derive(Debug, Clone)]
    pub struct ObjSync {
        vtable: Vtable,
    }

    unsafe impl Send for ObjSync { }

    unsafe impl Sync for ObjSync { }

    impl ObjSync {
        /// Creates new `ObjSync` class instance, wrapped in [`Arc`] smart pointer.
        ///
        /// A rarely used function, since it creates `ObjSync` itself, not one of its inheritors.
        #[allow(clippy::new_ret_no_self)]
        pub fn new() -> Arc<dyn IsObjSync> {
            Arc::new(unsafe { Self::new_raw(OBJ_SYNC_VTABLE.as_ptr()) })
        }

        /// Creates new `ObjSync`.
        ///
        /// Intended to be called from inheritors constructors to initialize a base type field.
        ///
        /// # Safety
        ///
        /// Calling this function is safe iff vtable is empty or
        /// generated using the [`class_unsafe`](crate::class_unsafe) macro on a
        /// direct or indirect `ObjSync` inheritor.
        pub unsafe fn new_raw(vtable: Vtable) -> Self {
            ObjSync { vtable }
        }

        /// Returns vtable, passed to the constructor.
        pub fn vtable(&self) -> Vtable { self.vtable }
    }

    /// Represents [`ObjSync`] or any of its inheritors.
    ///
    /// Usually obtained by using
    /// [`dyn_cast_arc`](dynamic_cast::dyn_cast_arc)
    /// on a derived trait.
    pub trait IsObjSync: SupportsInterfaces + DowncastSync {
        /// Returns reference to inner data.
        fn obj_sync(&self) -> &ObjSync;

        /// Converts to inner data.
        fn into_obj_sync(self) -> ObjSync where Self: Sized;
    }

    impl_supports_interfaces!(ObjSync: IsObjSync);

    impl_downcast!(sync IsObjSync);

    impl IsObjSync for ObjSync {
        fn obj_sync(&self) -> &ObjSync { self }

        fn into_obj_sync(self) -> ObjSync { self }
    }

    /// [`ObjSync`] virtual methods list.
    ///
    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
    #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
    #[repr(usize)]
    pub enum ObjSyncVirtMethods {
        VirtMethodsCount = 0usize,
    }

    /// [`ObjSync`] virtual methods table.
    ///
    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
    pub struct ObjSyncVtable(pub [*const (); ObjSyncVirtMethods::VirtMethodsCount as usize]);

    impl ObjSyncVtable {
        /// Creates [`ObjSync`] virtual methods table.
        ///
        /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
        #[allow(clippy::new_without_default)]
        pub const fn new() -> Self {
            ObjSyncVtable([])
        }
    }

    const OBJ_SYNC_VTABLE: [*const (); ObjSyncVirtMethods::VirtMethodsCount as usize] = ObjSyncVtable::new().0;
}