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 pub use $($list)*
374 };
375}
376
377pub mod obj {
378 use alloc::rc::Rc;
379 use downcast_rs::{Downcast, impl_downcast};
380 use dynamic_cast::{SupportsInterfaces, impl_supports_interfaces};
381 use macro_magic::export_tokens_no_emit;
382 use crate::Vtable;
383
384 pub mod obj_types {
385 //! Some reexported types and other things.
386 //!
387 //! Used by the [`import`] macro, not intended for direct use in code.
388 }
389
390 #[export_tokens_no_emit]
391 #[non_sync]
392 struct inherits_Obj { __class__: Obj }
393
394 /// Base class, contains no fields or methods. For [`Rc`]-based classes.
395 ///
396 /// Use [`import`] and [`class_unsafe`](crate::class_unsafe) macros
397 /// to define a class inherited from `Obj`:
398 ///
399 /// ```ignore
400 /// #[class_unsafe(inherits_Obj)]
401 /// struct Class { }
402 /// ```
403 #[derive(Debug, Clone)]
404 pub struct Obj {
405 vtable: Vtable,
406 }
407
408 unsafe impl Send for Obj { }
409
410 unsafe impl Sync for Obj { }
411
412 impl Obj {
413 /// Creates new `Obj` class instance, wrapped in [`Rc`] smart pointer.
414 ///
415 /// A rarely used function, since it creates `Obj` itself, not one of its inheritors.
416 #[allow(clippy::new_ret_no_self)]
417 pub fn new() -> Rc<dyn IsObj> {
418 Rc::new(unsafe { Self::new_raw(OBJ_VTABLE.as_ptr()) })
419 }
420
421 /// Creates new `Obj`.
422 ///
423 /// Intended to be called from inheritors constructors to initialize a base type field.
424 ///
425 /// # Safety
426 ///
427 /// Calling this function is safe iff vtable is empty or
428 /// generated using the [`class_unsafe`](crate::class_unsafe) macro on a
429 /// direct or indirect `Obj` inheritor.
430 pub unsafe fn new_raw(vtable: Vtable) -> Self {
431 Obj { vtable }
432 }
433
434 /// Returns vtable, passed to the constructor.
435 pub fn vtable(&self) -> Vtable { self.vtable }
436 }
437
438 /// Represents [`Obj`] or any of its inheritors.
439 ///
440 /// Usually obtained by using
441 /// [`dyn_cast_rc`](dynamic_cast::dyn_cast_rc)
442 /// on a derived trait.
443 pub trait IsObj: SupportsInterfaces + Downcast {
444 /// Returns reference to inner data.
445 fn obj(&self) -> &Obj;
446
447 /// Converts to inner data.
448 fn into_obj(self) -> Obj where Self: Sized;
449 }
450
451 impl_supports_interfaces!(Obj: IsObj);
452
453 impl_downcast!(IsObj);
454
455 impl IsObj for Obj {
456 fn obj(&self) -> &Obj { self }
457
458 fn into_obj(self) -> Obj { self }
459 }
460
461 /// [`Obj`] virtual methods list.
462 ///
463 /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
464 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
465 #[repr(usize)]
466 pub enum ObjVirtMethods {
467 VirtMethodsCount = 0usize,
468 }
469
470 /// [`Obj`] virtual methods table.
471 ///
472 /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
473 pub struct ObjVtable(pub [*const (); ObjVirtMethods::VirtMethodsCount as usize]);
474
475 impl ObjVtable {
476 /// Creates [`Obj`] virtual methods table.
477 ///
478 /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
479 #[allow(clippy::new_without_default)]
480 pub const fn new() -> Self {
481 ObjVtable([])
482 }
483 }
484
485 const OBJ_VTABLE: [*const (); ObjVirtMethods::VirtMethodsCount as usize] = ObjVtable::new().0;
486}
487
488pub mod obj_sync {
489 use alloc::sync::Arc;
490 use downcast_rs::{DowncastSync, impl_downcast};
491 use dynamic_cast::{SupportsInterfaces, impl_supports_interfaces};
492 use macro_magic::export_tokens_no_emit;
493 use crate::Vtable;
494
495 pub mod obj_sync_types {
496 //! Some reexported types and other things.
497 //!
498 //! Used by the [`import`] macro, not intended for direct use in code.
499 }
500
501 #[export_tokens_no_emit]
502 #[sync]
503 struct inherits_ObjSync { __class__: ObjSync }
504
505 /// Base class, contains no fields or methods. For [`Arc`]-based classes.
506 ///
507 /// Use [`import`] and [`class_unsafe`](crate::class_unsafe) macros
508 /// to define a class inherited from `ObjSync`:
509 ///
510 /// ```ignore
511 /// #[class_unsafe(inherits_ObjSync)]
512 /// struct Class { }
513 /// ```
514 #[derive(Debug, Clone)]
515 pub struct ObjSync {
516 vtable: Vtable,
517 }
518
519 unsafe impl Send for ObjSync { }
520
521 unsafe impl Sync for ObjSync { }
522
523 impl ObjSync {
524 /// Creates new `ObjSync` class instance, wrapped in [`Arc`] smart pointer.
525 ///
526 /// A rarely used function, since it creates `ObjSync` itself, not one of its inheritors.
527 #[allow(clippy::new_ret_no_self)]
528 pub fn new() -> Arc<dyn IsObjSync> {
529 Arc::new(unsafe { Self::new_raw(OBJ_SYNC_VTABLE.as_ptr()) })
530 }
531
532 /// Creates new `ObjSync`.
533 ///
534 /// Intended to be called from inheritors constructors to initialize a base type field.
535 ///
536 /// # Safety
537 ///
538 /// Calling this function is safe iff vtable is empty or
539 /// generated using the [`class_unsafe`](crate::class_unsafe) macro on a
540 /// direct or indirect `ObjSync` inheritor.
541 pub unsafe fn new_raw(vtable: Vtable) -> Self {
542 ObjSync { vtable }
543 }
544
545 /// Returns vtable, passed to the constructor.
546 pub fn vtable(&self) -> Vtable { self.vtable }
547 }
548
549 /// Represents [`ObjSync`] or any of its inheritors.
550 ///
551 /// Usually obtained by using
552 /// [`dyn_cast_arc`](dynamic_cast::dyn_cast_arc)
553 /// on a derived trait.
554 pub trait IsObjSync: SupportsInterfaces + DowncastSync {
555 /// Returns reference to inner data.
556 fn obj_sync(&self) -> &ObjSync;
557
558 /// Converts to inner data.
559 fn into_obj_sync(self) -> ObjSync where Self: Sized;
560 }
561
562 impl_supports_interfaces!(ObjSync: IsObjSync);
563
564 impl_downcast!(sync IsObjSync);
565
566 impl IsObjSync for ObjSync {
567 fn obj_sync(&self) -> &ObjSync { self }
568
569 fn into_obj_sync(self) -> ObjSync { self }
570 }
571
572 /// [`ObjSync`] virtual methods list.
573 ///
574 /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
575 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
576 #[repr(usize)]
577 pub enum ObjSyncVirtMethods {
578 VirtMethodsCount = 0usize,
579 }
580
581 /// [`ObjSync`] virtual methods table.
582 ///
583 /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
584 pub struct ObjSyncVtable(pub [*const (); ObjSyncVirtMethods::VirtMethodsCount as usize]);
585
586 impl ObjSyncVtable {
587 /// Creates [`ObjSync`] virtual methods table.
588 ///
589 /// Used by the [`class_unsafe`](crate::class_unsafe) macro, not intended for direct use in code.
590 #[allow(clippy::new_without_default)]
591 pub const fn new() -> Self {
592 ObjSyncVtable([])
593 }
594 }
595
596 const OBJ_SYNC_VTABLE: [*const (); ObjSyncVirtMethods::VirtMethodsCount as usize] = ObjSyncVtable::new().0;
597}