Skip to main content

basic_oop/
lib.rs

1#![feature(macro_metavar_expr_concat)]
2
3#![deny(warnings)]
4#![doc(test(attr(deny(warnings))))]
5#![doc(test(attr(allow(dead_code))))]
6#![doc(test(attr(allow(unused_variables))))]
7#![allow(clippy::needless_doctest_main)]
8
9//! The crate provides basic tools for writing object-oriented code in Rust.
10//! Very basic: no multiply inheritance, no generics, no interfaces
11//! (but this can be added in future in a limited form), no incapsulation.
12//! All classes in hierarchy should have distinct names even if they are located in different modules.
13//!
14//! # How to define a class
15//!
16//! First you need to _import_ the parent class. All classes should be derived from some parent
17//! class. The only class not having any parent is `Obj` defined in `basic_oop::obj` module. It contains
18//! no fields or methods. Lets import it:
19//!
20//! ```ignore
21//! import! { pub test_class:
22//!     use [obj basic_oop::obj];
23//! }
24//! ```
25//!
26//! Here `test_class` correspond to our new class name.
27//! (Although it is possible to use different names in the import section and in the class definition,
28//! doing so is not recommended to avoid confusion among users of the class.)
29//!
30//! The pub keyword means that our class will be public. In case of a private class, it should be omitted.
31//!
32//! All types that we plan to use in the method signatures of our class
33//! should also be imported as unique names. For example:
34//!
35//! ```ignore
36//! import! { pub test_class:
37//!     use [obj basic_oop::obj];
38//!     use std::rc::Rc;
39//!     use std::rc::Weak as rc_Weak;
40//! }
41//! ```
42//! 
43//! Now we can start to define our class using [`class_unsafe`] macro.
44//!
45//! Classes defined with the [`class_unsafe`] macro are intended for use either with the [`Rc`](alloc::rc::Rc)
46//! smart pointer or with the [`Arc`](alloc::sync::Arc) smart pointer.
47//!
48//! Suppose we don't need reference counter atomicity. Then our class
49//! definition will be the next:
50//!
51//! ```ignore
52//! #[class_unsafe(inherits_Obj)]
53//! pub struct TestClass { }
54//! ```
55//!
56//! Each class should have two constructors: one for creating this particular class
57//! and one for calling it from the constructor of the inheritor:
58//!
59//! ```ignore
60//! impl TestClass {
61//!     pub fn new() -> Rc<dyn IsTestClass> {
62//!         Rc::new(unsafe { Self::new_raw(TEST_CLASS_VTABLE.as_ptr()) })
63//!     }
64//!
65//!     pub unsafe fn new_raw(vtable: Vtable) -> Self {
66//!         TestClass { obj: unsafe { Obj::new_raw(vtable) } }
67//!     }
68//! }
69//! ```
70//!
71//! # Fields
72//!
73//! To add a field to class, we just write it in ordinar way:
74//!
75//! ```ignore
76//! #[class_unsafe(inherits_Obj)]
77//! pub struct TestClass {
78//!     field: RefCell<Rc<String>>,
79//! }
80//!
81//! impl TestClass {
82//!     pub fn new(field: Rc<String>) -> Rc<dyn IsTestClass> {
83//!         Rc::new(unsafe { Self::new_raw(field, TEST_CLASS_VTABLE.as_ptr()) })
84//!     }
85//!
86//!     pub unsafe fn new_raw(field: Rc<String>, vtable: Vtable) -> Self {
87//!         TestClass {
88//!             obj: unsafe { Obj::new_raw(vtable) },
89//!             field: RefCell::new(field),
90//!         }
91//!     }
92//! }
93//! ```
94//!
95//! # Non-virtual methods
96//!
97//! To add a method, it is needed to specify a fictive field with `#[non_virt]` attribute and
98//! function type:
99//!
100//! ```ignore
101//! #[class_unsafe(inherits_Obj)]
102//! pub struct TestClass {
103//!     ...
104//!     #[non_virt]
105//!     get_field: fn() -> Rc<String>,
106//! }
107//! ```
108//!
109//! Then `TestClassExt` extension trait will be generated contained appropriate function calling
110//! `TestClass::get_field_impl`. We must provide this implementing function:
111//!
112//! ```ignore
113//! impl TestClass {
114//!     fn get_field_impl(this: &Rc<dyn IsTestClass>) -> Rc<String> {
115//!         this.test_class().field.borrow().clone()
116//!     }
117//! }
118//! ```
119//!
120//! # Virtual methods
121//!
122//! Adding a virtual method is no different from adding a non-virtual method only this time
123//! we use `virt`:
124//!
125//! ```ignore
126//! #[class_unsafe(inherits_Obj)]
127//! pub struct TestClass {
128//!     ...
129//!     #[virt]
130//!     set_field: fn(value: Rc<String>),
131//! }
132//!
133//! impl TestClass {
134//!     fn set_field_impl(this: &Rc<dyn IsTestClass>, value: Rc<String>) {
135//!         *this.test_class().field.borrow_mut() = value;
136//!     }
137//! }
138//! ```
139//!
140//! # Derived class. Method overriding.
141//!
142//! Lets import our class and derive another one from it:
143//!
144//! ```ignore
145//! import! { pub derived_class:
146//!     use [test_class crate::test_class];
147//! }
148//!
149//! #[class_unsafe(inherits_TestClass)]
150//! pub struct DerivedClass {
151//! }
152//! ```
153//!
154//! Now we wants to override `set_field`, how we do it? Simple:
155//!
156//! ```ignore
157//! #[class_unsafe(inherits_TestClass)]
158//! pub struct DerivedClass {
159//!     #[over]
160//!     set_field: (),
161//! }
162//!
163//! impl DerivedClass {
164//!     pub fn set_field_impl(this: &Rc<dyn IsTestClass>, value: Rc<String>) {
165//!         let value = /* coerce value */;
166//!         TestClass::set_field_impl(this, value);
167//!     }
168//! }
169//! ```
170//!
171//! The type of the overridden function is already known from the base class definition,
172//! so there is no need to re-write it, which is why the type of the phony field is specified as `()`.
173//!
174//! # Using the class.
175//!
176//! We can create instance of derived class:
177//!
178//! ```ignore
179//! let class = DerivedClass::new(Rc::new("initial".to_string()));
180//! ```
181//!
182//! We can cast it to base class:
183//!
184//! ```ignore
185//! let base_class: Rc<dyn IsTestClass> = dyn_cast_rc(class).unwrap();
186//! ```
187//!
188//! We can call both virtual and non-virtual methods:
189//!
190//! ```ignore
191//! assert_eq!(base_class.get_field().as_ref(), "initial");
192//! base_class.set_field(Rc::new("changed".to_string()));
193//! assert_eq!(base_class.get_field().as_ref(), "changed coerced");
194//! ```
195//!
196//! See full working example in README.md
197//!
198//! # Arc-based classes
199//!
200//! To get a class based on [`Arc`](alloc::sync::Arc) instead of [`Rc`](alloc::rc::Rc),
201//! use use [`ObjSync`](obj_sync::ObjSync) instead of [`Obj`](obj::Obj):
202//!
203//! ```ignore
204//! import! { pub test_class:
205//!     use [obj_sync basic_oop::obj_sync];
206//!     ...
207//! }
208//! #[class_unsafe(inherits_ObjSync)]
209//! pub struct TestClass { }
210//! ```
211
212#![no_std]
213
214extern crate alloc;
215
216#[doc=include_str!("../README.md")]
217type _DocTestReadme = ();
218
219#[doc(hidden)]
220pub use macro_magic;
221
222/// Generates class and appropriate helper types and traits.
223///
224/// Usage:
225///
226/// ```ignore
227/// #[class_unsafe(inherits_ParentClass)]
228/// struct Class {
229///     field: FieldType,
230///     #[non_virt]
231///     non_virtual_method: fn(args: ArgsType) -> ResultType,
232///     #[virt]
233///     virtual_method: fn(args: ArgsType) -> ResultType,
234///     #[over]
235///     parent_virtual_method: (),
236/// }
237///
238/// impl Class {
239///     fn non_virtual_method_impl(this: Rc<dyn IsClass>, args: ArgsType) -> ResultType {
240///         ...
241///     }
242///
243///     fn virtual_method_impl(this: Rc<dyn IsClass>, args: ArgsType) -> ResultType {
244///         ...
245///     }
246///
247///     fn parent_virtual_method_impl(this: Rc<dyn IsParentClass>, args: ArgsType) -> ResultType {
248///         let base_result = ParentClass::parent_virtual_method_impl(this, args);
249///         ...
250///     }
251/// }
252/// ```
253///
254/// For a more detailed overview, please refer to the crate documentation.
255///
256/// # Safety
257///
258/// This macro may produce unsound code if the argument to the macro differs
259/// from `inherits_Obj`/`inherits_Obj_sync` [`import`]ed from the [`obj`] module
260/// and another `inherits_...` generated by this macro for a direct or indirect inheritor of `Obj`.
261///
262/// In other words, it is safe to use this macro as long as you
263/// don't try to manually create something that this macro will accept as a valid argument.
264///
265/// It must also be guaranteed that the generated class cannot be constructed with an invalid vtable,
266/// that is, any vtable other than the one generated by this macro
267/// for this class or its direct or indirect inheritor.
268///
269/// This is usually achieved by providing two constructors:
270/// a safe one that creates a class with a precisely known, guaranteed safe table,
271/// and an unsafe one for inheritors that enforces the specified requirement. For example:
272///
273/// ```ignore
274/// #[class_unsafe(inherits_SomeBaseClass)]
275/// pub struct SomeClass { }
276///
277/// impl SomeClass {
278///     pub fn new(param: ParamType) -> Rc<dyn IsSomeClass> {
279///         Rc::new(unsafe { Self::new_raw(param, SOME_CLASS_VTABLE.as_ptr()) })
280///     }
281///
282///     pub unsafe fn new_raw(param: ParamType, vtable: Vtable) -> Self {
283///         SomeClass { some_base_class: unsafe { SomeBaseClass::new_raw(param, vtable) } }
284///     }
285/// }
286/// ```
287pub use basic_oop_macro::class_unsafe;
288
289#[doc(hidden)]
290pub use alloc::rc::Rc as alloc_rc_Rc;
291#[doc(hidden)]
292pub use alloc::sync::Arc as alloc_sync_Arc;
293#[doc(hidden)]
294pub use core::mem::transmute as core_mem_transmute;
295#[doc(hidden)]
296pub use dynamic_cast::SupportsInterfaces as dynamic_cast_SupportsInterfaces;
297#[doc(hidden)]
298pub use dynamic_cast::impl_supports_interfaces as dynamic_cast_impl_supports_interfaces;
299
300/// The pointer to the table containing pointers to class virtual functions.
301///
302/// Use [`class_unsafe`] macro to generate `Vtable`.
303pub type Vtable = *const *const ();
304
305#[doc(hidden)]
306#[repr(C)]
307pub struct VtableJoin<const A: usize, const B: usize> {
308    pub a: [*const (); A],
309    pub b: [*const (); B],
310}
311
312/// Imports base class into the current scope so that it can be inherited from.
313///
314/// The macro accepts input in the following form:
315///
316/// ```ignore
317/// $vis:vis $class:ident :
318/// use $([$base:ident $path:path])+ ;
319/// $( $(#[$attr:meta])* use $($custom_use:tt)+ ; )*
320/// ```
321///
322/// See module documentation for explanation how to use it.
323#[macro_export]
324macro_rules! import {
325    (
326        $vis:vis $class:ident :
327        use $([$base:ident $($path:tt)*])+ ;
328        $($custom_use:tt)*
329    ) => {
330        $vis mod ${concat($class, _types)} {
331            //! Some reexported types and other things.
332            //!
333            //! Used by the [`import`] macro, not intended for direct use in code.
334            $(
335                #[allow(unused_imports)]
336                pub use $($path)*::*;
337                #[allow(unused_imports)]
338                pub use $($path)*:: ${concat($base, _types)} ::*;
339            )+
340            $crate::import_impl! { @split [] [$($custom_use)*] }
341        }
342        use ${concat($class, _types)} ::*;
343    };
344}
345
346#[doc(hidden)]
347#[macro_export]
348macro_rules! import_impl {
349    (
350        @split [$($t:tt)*] [ ; $($custom_use:tt)*]
351    ) => {
352        $crate::import_impl! { @use [$($t)* ; ] }
353        $crate::import_impl! { @split [] [$($custom_use)*] }
354    };
355    (
356        @split [$($t:tt)*] [$x:tt $($custom_use:tt)*]
357    ) => {
358        $crate::import_impl! { @split [$($t)* $x] [$($custom_use)*] }
359    };
360    (
361        @split [] []
362    ) => {
363    };
364    (
365        @split [$($t:tt)+] []
366    ) => {
367        $crate::import_impl! { @use [$($t)+] }
368    };
369    (
370        @use [$(#[$attr:meta])* use $($list:tt)*]
371    ) => {
372        $(#[$attr])*
373        #[allow(unused_imports)]
374        pub use $($list)*
375    };
376}
377
378pub mod obj {
379    use alloc::rc::Rc;
380    use downcast_rs::{Downcast, impl_downcast};
381    use dynamic_cast::{SupportsInterfaces, impl_supports_interfaces};
382    use macro_magic::export_tokens_no_emit;
383    use crate::Vtable;
384
385    pub mod obj_types {
386        //! Some reexported types and other things.
387        //!
388        //! Used by the [`import`] macro, not intended for direct use in code.
389    }
390
391    #[export_tokens_no_emit]
392    #[non_sync]
393    struct inherits_Obj { __class__: Obj }
394
395    /// Base class, contains no fields or methods. For [`Rc`]-based classes.
396    ///
397    /// Use [`import`] and [`class_unsafe`](crate::class_unsafe) macros
398    /// to define a class inherited from `Obj`:
399    ///
400    /// ```ignore
401    /// #[class_unsafe(inherits_Obj)]
402    /// struct Class { }
403    /// ```
404    #[derive(Debug, Clone)]
405    pub struct Obj {
406        vtable: Vtable,
407    }
408
409    unsafe impl Send for Obj { }
410
411    unsafe impl Sync for Obj { }
412
413    impl Obj {
414        /// Creates new `Obj` class instance, wrapped in [`Rc`] smart pointer.
415        ///
416        /// A rarely used function, since it creates `Obj` itself, not one of its inheritors.
417        #[allow(clippy::new_ret_no_self)]
418        pub fn new() -> Rc<dyn IsObj> {
419            Rc::new(unsafe { Self::new_raw(OBJ_VTABLE.as_ptr()) })
420        }
421
422        /// Creates new `Obj`.
423        ///
424        /// Intended to be called from inheritors constructors to initialize a base type field.
425        ///
426        /// # Safety
427        ///
428        /// Calling this function is safe iff vtable is empty or
429        /// generated using the [`class_unsafe`](crate::class_unsafe) macro on a
430        /// direct or indirect `Obj` inheritor.
431        pub unsafe fn new_raw(vtable: Vtable) -> Self {
432            Obj { vtable }
433        }
434
435        /// Returns vtable, passed to the constructor.
436        pub fn vtable(&self) -> Vtable { self.vtable }
437    }
438
439    /// Represents [`Obj`] or any of its inheritors.
440    ///
441    /// Usually obtained by using
442    /// [`dyn_cast_rc`](dynamic_cast::dyn_cast_rc)
443    /// on a derived trait.
444    pub trait IsObj: SupportsInterfaces + Downcast {
445        /// Returns reference to inner data.
446        fn obj(&self) -> &Obj;
447
448        /// Converts to inner data.
449        fn into_obj(self) -> Obj where Self: Sized;
450    }
451
452    impl_supports_interfaces!(Obj: IsObj);
453
454    impl_downcast!(IsObj);
455
456    impl IsObj for Obj {
457        fn obj(&self) -> &Obj { self }
458
459        fn into_obj(self) -> Obj { self }
460    }
461
462    /// [`Obj`] virtual methods list.
463    ///
464    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
465    #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
466    #[repr(usize)]
467    pub enum ObjVirtMethods {
468        VirtMethodsCount = 0usize,
469    }
470
471    /// [`Obj`] virtual methods table.
472    ///
473    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
474    pub struct ObjVtable(pub [*const (); ObjVirtMethods::VirtMethodsCount as usize]);
475
476    impl ObjVtable {
477        /// Creates [`Obj`] virtual methods table.
478        ///
479        /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
480        #[allow(clippy::new_without_default)]
481        pub const fn new() -> Self {
482            ObjVtable([])
483        }
484    }
485
486    const OBJ_VTABLE: [*const (); ObjVirtMethods::VirtMethodsCount as usize] = ObjVtable::new().0;
487}
488
489pub mod obj_sync {
490    use alloc::sync::Arc;
491    use downcast_rs::{DowncastSync, impl_downcast};
492    use dynamic_cast::{SupportsInterfaces, impl_supports_interfaces};
493    use macro_magic::export_tokens_no_emit;
494    use crate::Vtable;
495
496    pub mod obj_sync_types {
497        //! Some reexported types and other things.
498        //!
499        //! Used by the [`import`] macro, not intended for direct use in code.
500    }
501
502    #[export_tokens_no_emit]
503    #[sync]
504    struct inherits_ObjSync { __class__: ObjSync }
505
506    /// Base class, contains no fields or methods. For [`Arc`]-based classes.
507    ///
508    /// Use [`import`] and [`class_unsafe`](crate::class_unsafe) macros
509    /// to define a class inherited from `ObjSync`:
510    ///
511    /// ```ignore
512    /// #[class_unsafe(inherits_ObjSync)]
513    /// struct Class { }
514    /// ```
515    #[derive(Debug, Clone)]
516    pub struct ObjSync {
517        vtable: Vtable,
518    }
519
520    unsafe impl Send for ObjSync { }
521
522    unsafe impl Sync for ObjSync { }
523
524    impl ObjSync {
525        /// Creates new `ObjSync` class instance, wrapped in [`Arc`] smart pointer.
526        ///
527        /// A rarely used function, since it creates `ObjSync` itself, not one of its inheritors.
528        #[allow(clippy::new_ret_no_self)]
529        pub fn new() -> Arc<dyn IsObjSync> {
530            Arc::new(unsafe { Self::new_raw(OBJ_SYNC_VTABLE.as_ptr()) })
531        }
532
533        /// Creates new `ObjSync`.
534        ///
535        /// Intended to be called from inheritors constructors to initialize a base type field.
536        ///
537        /// # Safety
538        ///
539        /// Calling this function is safe iff vtable is empty or
540        /// generated using the [`class_unsafe`](crate::class_unsafe) macro on a
541        /// direct or indirect `ObjSync` inheritor.
542        pub unsafe fn new_raw(vtable: Vtable) -> Self {
543            ObjSync { vtable }
544        }
545
546        /// Returns vtable, passed to the constructor.
547        pub fn vtable(&self) -> Vtable { self.vtable }
548    }
549
550    /// Represents [`ObjSync`] or any of its inheritors.
551    ///
552    /// Usually obtained by using
553    /// [`dyn_cast_arc`](dynamic_cast::dyn_cast_arc)
554    /// on a derived trait.
555    pub trait IsObjSync: SupportsInterfaces + DowncastSync {
556        /// Returns reference to inner data.
557        fn obj_sync(&self) -> &ObjSync;
558
559        /// Converts to inner data.
560        fn into_obj_sync(self) -> ObjSync where Self: Sized;
561    }
562
563    impl_supports_interfaces!(ObjSync: IsObjSync);
564
565    impl_downcast!(sync IsObjSync);
566
567    impl IsObjSync for ObjSync {
568        fn obj_sync(&self) -> &ObjSync { self }
569
570        fn into_obj_sync(self) -> ObjSync { self }
571    }
572
573    /// [`ObjSync`] virtual methods list.
574    ///
575    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
576    #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
577    #[repr(usize)]
578    pub enum ObjSyncVirtMethods {
579        VirtMethodsCount = 0usize,
580    }
581
582    /// [`ObjSync`] virtual methods table.
583    ///
584    /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
585    pub struct ObjSyncVtable(pub [*const (); ObjSyncVirtMethods::VirtMethodsCount as usize]);
586
587    impl ObjSyncVtable {
588        /// Creates [`ObjSync`] virtual methods table.
589        ///
590        /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
591        #[allow(clippy::new_without_default)]
592        pub const fn new() -> Self {
593            ObjSyncVtable([])
594        }
595    }
596
597    const OBJ_SYNC_VTABLE: [*const (); ObjSyncVirtMethods::VirtMethodsCount as usize] = ObjSyncVtable::new().0;
598}