[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [PATCH 22/26] rust: qom: add casting functionality
From: |
Paolo Bonzini |
Subject: |
Re: [PATCH 22/26] rust: qom: add casting functionality |
Date: |
Mon, 16 Dec 2024 16:17:09 +0100 |
On Mon, Dec 16, 2024 at 1:35 PM Zhao Liu <zhao1.liu@intel.com> wrote:
>
> > +/// Macro to mark superclasses of QOM classes. This enables type-safe
> > +/// up- and downcasting.
> > +///
> > +/// # Safety
> > +///
> > +/// This macro is a thin wrapper around the [`IsA`] trait and performs
> > +/// no checking whatsoever of what is declared. It is the caller's
> > +/// responsibility to have $struct begin, directly or indirectly, with
> > +/// a field of type `$parent`.
> > +#[macro_export]
> > +macro_rules! qom_isa {
> > + ($struct:ty : $($parent:ty),* ) => {
>
> This macro is quite good, but it requires specifying all the parents...
> So I am thinking if it is possible to move ParentType to ObjectType, and
> then try to traverse the ParentType in the macro, implementing IsA for
> each ParentType... However, the first difficulty has already stopped me:
> I cannot define ParentType for Object itself.
I am not sure how that could be done, but I've seen people
implementing boolean logic purely with types, like
pub struct True;
pub struct False;
pub trait Boolean {}
impl Boolean for True;
impl Boolean for False;
pub trait Or<T: Boolean>: Boolean {
type Result: Boolean;
}
impl<T: Boolean> Or<T> for True {
type Result = True;
}
impl<T: Boolean> Or<T> for False {
type Result = T;
}
and I think that can be used to implement recursive IsA, but that is a
bit too magic for this first step. QEMU class hierarchies are
relatively shallow.
> > @@ -94,8 +147,224 @@ pub unsafe trait ObjectType: Sized {
> > /// The name of the type, which can be passed to `object_new()` to
> > /// generate an instance of this type.
> > const TYPE_NAME: &'static CStr;
> > +
> > + /// Return the receiver as an Object. This is always safe, even
> > + /// if this type represents an interface.
>
> This comment is a bit confusing to me... EMM, why mention the interface?
> I understand if something implements ObjectType, then it should be an
> Object, so deref/cast here would be valid. And if it is an interface,
> it would need to implement the corresponding trait.
What I meant is that interfaces do (will) not implement IsA<Object>,
but they are ObjectTypes. So if you have let's say an "&impl
UserCreatable" argument, you could use as_object() to obtain an
&Object.
> This cast idea is nice! In the future, class might also need to implement=
> similar cast support (e.g., class_init in virtio).
Ok, good!
Paolo
- Re: [PATCH 18/26] rust: qom: add possibility of overriding unparent, (continued)
[PATCH 22/26] rust: qom: add casting functionality, Paolo Bonzini, 2024/12/09
Re: [PATCH 00/26] rust: bundle of prerequisites for HPET implementation, Philippe Mathieu-Daudé, 2024/12/09