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
//! query-interface - dynamically query a type-erased object for any trait implementation
//!
//! ```rust
//! #[macro_use]
//! extern crate query_interface;
//! use query_interface::{Object, ObjectClone};
//! use std::fmt::Debug;
//!
//! #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
//! struct Foo;
//!
//! interfaces!(Foo: ObjectClone, Debug, Bar);
//!
//! trait Bar {
//!     fn do_something(&self);
//! }
//! impl Bar for Foo {
//!     fn do_something(&self) {
//!         println!("I'm a Foo!");
//!     }
//! }
//!
//! fn main() {
//!     let obj = Box::new(Foo) as Box<Object>;
//!     let obj2 = obj.clone();
//!     println!("{:?}", obj2);
//!
//!     obj2.query_ref::<Bar>().unwrap().do_something();  // Prints: "I'm a Foo!"
//! }
//! ```
#[cfg(feature = "dynamic")]
#[macro_use]
extern crate lazy_static;

use std::any::{TypeId, Any};
use std::ptr;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use std::fmt::{Debug, Display};
use std::path::PathBuf;

#[cfg(feature = "dynamic")]
#[macro_use]
pub mod dynamic;

/// Represents a trait object's vtable pointer. You shouldn't need to use this as a
/// consumer of the crate but it is required for macro expansion.
#[doc(hidden)]
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct VTable(*const ());

impl VTable {
    pub fn none() -> VTable {
        VTable(ptr::null())
    }
}

unsafe impl Send for VTable {}
unsafe impl Sync for VTable {}

/// Represents a trait object's layout. You shouldn't need to use this as a
/// consumer of the crate but it is required for macro expansion.
#[doc(hidden)]
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct TraitObject {
    pub data: *const (),
    pub vtable: VTable
}

/// Obtain the vtable for a type/trait pair. You shouldn't need to use this as a
/// consumer of the crate but it is required for macro expansion.
#[doc(hidden)]
#[macro_export]
macro_rules! vtable_for {
    ($x:ty as $y:ty) => ({
        let x = ::std::ptr::null::<$x>() as *const $y;
        #[allow(unused_unsafe)]
        unsafe { ::std::mem::transmute::<_, $crate::TraitObject>(x).vtable }
    })
}

/// Define a custom Object-like trait. The `query`, `query_ref` and `query_mut`
/// methods will be automatically implemented on this trait object.
/// 
/// You may add additional static bounds to your custom trait via the
/// `HasInterface<I>` trait. This example will statically ensure that all
/// types convertible to `MyObject` can be cloned. Your trait must extend
/// `Object`.
/// 
/// ```rust
/// # #[macro_use]
/// # extern crate query_interface;
/// # use query_interface::*;
/// trait MyObject: Object + ObjectClone + HasInterface<ObjectClone> { }
/// mopo!(MyObject);
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! mopo {
    ($name:ty) => (
        impl $name {
            pub fn query_ref<U: ::std::any::Any + ?Sized>(&self) -> Option<&U> {
                if let Some(vtable) = self.query_vtable(::std::any::TypeId::of::<U>()) {
                    unsafe {
                        let data = self as *const Self;
                        let u = $crate::TraitObject { data: data as *const (), vtable: vtable };
                        Some(*::std::mem::transmute::<_, &&U>(&u))
                    }
                } else {
                    None
                }
            }
            pub fn query_mut<U: ::std::any::Any + ?Sized>(&mut self) -> Option<&mut U> {
                if let Some(vtable) = self.query_vtable(::std::any::TypeId::of::<U>()) {
                    unsafe {
                        let data = self as *mut Self;
                        let mut u = $crate::TraitObject { data: data as *const (), vtable: vtable };
                        Some(*::std::mem::transmute::<_, &mut &mut U>(&mut u))
                    }
                } else {
                    None
                }
            }
            pub fn query<U: ::std::any::Any + ?Sized>(self: Box<Self>) -> ::std::result::Result<Box<U>, Box<Self>> {
                if let Some(vtable) = self.query_vtable(::std::any::TypeId::of::<U>()) {
                    unsafe {
                        let data = Box::into_raw(self);
                        let mut u = $crate::TraitObject { data: data as *const (), vtable: vtable };
                        Ok(Box::from_raw(*::std::mem::transmute::<_, &mut *mut U>(&mut u)))
                    }
                } else {
                    Err(self)
                }
            }
            pub fn query_arc<U: ::std::any::Any + ?Sized>(self_: ::std::sync::Arc<Self>) -> ::std::result::Result<::std::sync::Arc<U>, ::std::sync::Arc<Self>> {
                if let Some(vtable) = self_.query_vtable(::std::any::TypeId::of::<U>()) {
                    unsafe {
                        let data = ::std::sync::Arc::into_raw(self_);
                        let mut u = $crate::TraitObject { data: data as *const (), vtable: vtable };
                        Ok(::std::sync::Arc::from_raw(*::std::mem::transmute::<_, &mut *mut U>(&mut u)))
                    }
                } else {
                    Err(self_)
                }
            }
            pub fn query_rc<U: ::std::any::Any + ?Sized>(self_: ::std::rc::Rc<Self>) -> ::std::result::Result<::std::rc::Rc<U>, ::std::rc::Rc<Self>> {
                if let Some(vtable) = self_.query_vtable(::std::any::TypeId::of::<U>()) {
                    unsafe {
                        let data = ::std::rc::Rc::into_raw(self_);
                        let mut u = $crate::TraitObject { data: data as *const (), vtable: vtable };
                        Ok(::std::rc::Rc::from_raw(*::std::mem::transmute::<_, &mut *mut U>(&mut u)))
                    }
                } else {
                    Err(self_)
                }
            }
            pub fn obj_partial_eq(&self, other: &Self) -> bool {
                if let Some(x) = self.query_ref::<$crate::ObjectPartialEq>() {
                    x.obj_eq(other.query_ref().unwrap())
                } else {
                    (self as *const Self) == (other as *const Self)
                }
            }
            pub fn obj_partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
                if let Some(x) = self.query_ref::<$crate::ObjectPartialOrd>() {
                    x.obj_partial_cmp(other.query_ref().unwrap())
                } else {
                    None
                }
            }
        }
        impl ::std::clone::Clone for Box<$name> {
            fn clone(&self) -> Self {
                (**self).to_owned()
            }
        }
        impl ::std::borrow::ToOwned for $name {
            type Owned = Box<$name>;
            fn to_owned(&self) -> Box<$name> {
                self.query_ref::<$crate::ObjectClone>().expect("Object not clonable!").obj_clone().query::<$name>().unwrap()
            }
        }
        impl ::std::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                if let Some(o) = self.query_ref::<::std::fmt::Debug>() {
                    o.fmt(f)
                } else {
                    writeln!(f, "Object {{ <no `Debug` implementation> }}")
                }
            }
        }
        impl ::std::cmp::PartialEq for $name {
            fn eq(&self, other: &Self) -> bool {
                // Require `Eq` rather than `PartialEq` as this allows `Object`s to be used as
                // key in hash maps
                if let Some(x) = self.query_ref::<$crate::ObjectEq>() {
                    x.obj_eq(other.query_ref().unwrap())
                } else {
                    // This trivially meets the requirements of `Eq`
                    (self as *const Self) == (other as *const Self)
                }
            }
        }
        impl ::std::cmp::Eq for $name {}
        impl ::std::cmp::PartialOrd for $name {
            fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }
        impl ::std::cmp::Ord for $name {
            fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
                if let Some(x) = self.query_ref::<$crate::ObjectOrd>() {
                    if let Some(o) = x.obj_cmp(other.query_ref().unwrap()) {
                        return o
                    }
                }
                Ord::cmp(&(self as *const Self), &(other as *const Self))
            }
        }
        impl ::std::hash::Hash for $name {
            fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
                if let Some(x) = self.query_ref::<$crate::ObjectHash>() {
                    x.obj_hash(state)
                } else {
                    state.write_usize(self as *const Self as *const () as usize)
                }
            }
        }
    )
}

/// This trait is the primary function of the library. `Object` trait objects
/// can be freely queried for any other trait, allowing conversion between
/// trait objects.
pub unsafe trait Object: Any {
    /// This is implemented by the `interfaces!` macro, and should never be
    /// manually implemented.
    #[doc(hidden)]
    fn query_vtable(&self, id: TypeId) -> Option<VTable>;
}

/// You can use this trait to ensure that a type implements a trait as an
/// interface. This means the type declared the trait in its `interfaces!(...)`
/// list, and guarantees that querying an `Object` of that type for the trait
/// will always succeed.
/// 
/// When using `HasInterface<SomeTrait>` in a generic bound, you should also
/// specify `SomeTrait` as a bound. While `HasInterface<SomeTrait>` is a more
/// stringent requirement than, and in practice implies `SomeTrait`, the
/// compiler cannot deduce that because it is enforced through macros rather
/// than the type system.
pub unsafe trait HasInterface<I: ?Sized> {}

mopo!(Object);


/// This is an object-safe version of `Clone`, which is automatically
/// implemented for all `Clone + Object` types. This is a support trait used to
/// allow `Object` trait objects to be clonable.
pub trait ObjectClone {
    fn obj_clone(&self) -> Box<Object>;
}
impl<T: Clone + Object> ObjectClone for T {
    fn obj_clone(&self) -> Box<Object> {
        Box::new(self.clone())
    }
}

/// This is an object-safe version of `PartialEq`, which is automatically
/// implemented for all `PartialEq + Object` types. This is a support trait used to
/// allow `Object` trait objects to be comparable in this way.
pub trait ObjectPartialEq {
    fn obj_eq(&self, other: &Object) -> bool;
}
impl<T: PartialEq + Object> ObjectPartialEq for T {
    fn obj_eq(&self, other: &Object) -> bool {
        if let Some(o) = other.query_ref::<Self>() {
            self == o
        } else {
            false
        }
    }
}

/// This is an object-safe version of `Eq`, which is automatically
/// implemented for all `Eq + Object` types. This is a support trait used to
/// allow `Object` trait objects to be comparable in this way.
pub trait ObjectEq: ObjectPartialEq {}
impl<T: Eq + Object> ObjectEq for T {}

/// This is an object-safe version of `PartialOrd`, which is automatically
/// implemented for all `PartialOrd + Object` types. This is a support trait used to
/// allow `Object` trait objects to be comparable in this way.
pub trait ObjectPartialOrd {
    fn obj_partial_cmp(&self, other: &Object) -> Option<Ordering>;
}
impl<T: PartialOrd + Object> ObjectPartialOrd for T {
    fn obj_partial_cmp(&self, other: &Object) -> Option<Ordering> {
        if let Some(o) = other.query_ref::<Self>() {
            self.partial_cmp(o)
        } else {
            None
        }
    }
}

/// This is an object-safe version of `Ord`, which is automatically
/// implemented for all `Ord + Object` types. This is a support trait used to
/// allow `Object` trait objects to be comparable in this way.
pub trait ObjectOrd {
    fn obj_cmp(&self, other: &Object) -> Option<Ordering>;
}
impl<T: Ord + Object> ObjectOrd for T {
    fn obj_cmp(&self, other: &Object) -> Option<Ordering> {
        if let Some(o) = other.query_ref::<Self>() {
            Some(self.cmp(o))
        } else {
            None
        }
    }
}

/// This is an object-safe version of `Hash`, which is automatically
/// implemented for all `Hash + Object` types. This is a support trait used to
/// allow `Object` trait objects to be comparable in this way.
///
/// Note: `Object`s are not guaranteed to hash to the same value as their
/// underlying type.
pub trait ObjectHash {
    fn obj_hash(&self, state: &mut Hasher);
}
impl<T: Hash + Object> ObjectHash for T {
    fn obj_hash(&self, state: &mut Hasher) {
        let mut h = DefaultHasher::new();
        self.hash(&mut h);
        state.write_u64(h.finish());
    }
}

/// Allow a set of traits to be dynamically queried from a type when it is
/// stored as an `Object` trait object.
/// 
/// Example use:
/// 
/// ```rust
/// # #[macro_use]
/// # extern crate query_interface;
/// # use query_interface::*;
/// #[derive(Clone)]
/// struct Foo;
/// interfaces!(Foo: ObjectClone);
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! interfaces {
    (@unbracket $(($($v:tt)*))*) => ($($($v)*)*);
    (@inner $imp:tt $cond:tt $name:ty: $($iface:ty),+ {}) => (
        interfaces!(@unbracket $imp ($crate::HasInterface<$name> for $name) $cond ({}));
        interfaces!(@unbracket $imp ($crate::HasInterface<$crate::Object> for $name) $cond ({}));
        $(interfaces!(@unbracket $imp ($crate::HasInterface<$iface> for $name) $cond ({}));)*
        interfaces!(@unbracket $imp ($crate::Object for $name) $cond ({
            fn query_vtable(&self, id: ::std::any::TypeId) -> Option<$crate::VTable> {
                if id == ::std::any::TypeId::of::<$name>() {
                    Some($crate::VTable::none())
                } else if id == ::std::any::TypeId::of::<$crate::Object>() {
                    Some(vtable_for!($name as $crate::Object))
                } else $(if id == ::std::any::TypeId::of::<$iface>() {
                    Some(vtable_for!($name as $iface))
                } else)* {
                    // If "dynamic" feature is enabled, fall back to
                    // looking in the registry
                    #[cfg(feature = "dynamic")]
                    { $crate::dynamic::find_in_registry::<$name>(id) }
                    // No dynamic lookup
                    #[cfg(not(feature = "dynamic"))]
                    { None }
                }
            }
        }));
    );
    (@imp ($($result:tt)*) $name:ty: $($iface:ty),+ $(where $($cond:tt)*)*) => (
        interfaces!(@inner (unsafe impl<$($result)*>) ($(where $($cond)*)*) $name: $($iface),+ {});
    );
    (@parse < $($rest:tt)*) => (
        interfaces!(@parseArg () $($rest)*);
    );
    (@parse $($rest:tt)*) => (
        interfaces!(@imp () $($rest)*);
    );
    (@parseArg ($($result:tt)*) $name:ident , $($rest:tt)*) => (
        interfaces!(@parseArg ($($result)* $name ,) $($rest)*);
    );
    (@parseArg ($($result:tt)*) $name:ident : $($rest:tt)*) => (
        interfaces!(@parseBound ($($result)* $name : ) $($rest)*);
    );
    (@parseArg ($($result:tt)*) $name:ident > $($rest:tt)*) => (
        interfaces!(@imp ($($result)* $name) $($rest)*);
    );
    (@parseBound ($($result:tt)*) $bound:tt + $($rest:tt)*) => (
        interfaces!(@parseBound ($($result)* $bound +) $($rest)*);
    );
    (@parseBound ($($result:tt)*) $bound:tt , $($rest:tt)*) => (
        interfaces!(@parseArg ($($result)* $bound ,) $($rest)*);
    );
    (@parseBound ($($result:tt)*) $bound:tt > $($rest:tt)*) => (
        interfaces!(@imp ($($result)* $bound) $($rest)*);
    );
    (< $($rest:tt)*) => (
        interfaces!(@parse < $($rest)*);
    );
    ($x:ty: $($rest:tt)*) => (
        interfaces!(@parse $x: $($rest)*);
    );
    (@expand2 ($name:ty) ($($rest:tt)*)) => (
        interfaces!($name $($rest)*);
    );
    (@expand {$($name:ty),*} $rest:tt) => (
        $( interfaces!(@expand2 ($name) $rest); )*
    );
    ({$($name:ty),*} $($rest:tt)*) => (
        interfaces!(@expand {$($name),*} ($($rest)*));
    );
}

// Integral types
interfaces!({
    bool, i8, u8, i16, u16, i32, u32, i64, u64, char
}: ObjectClone, Debug, Display, ObjectPartialEq, ObjectPartialOrd, ObjectEq, ObjectOrd, ObjectHash, ToString);

// Floating point types
interfaces!({
    f32, f64
}: ObjectClone, Debug, Display, ObjectPartialEq, ObjectPartialOrd, ToString);

// Strings
interfaces!(String: ObjectClone, Debug, Display, ObjectPartialEq, ObjectPartialOrd, ObjectEq, ObjectOrd, ObjectHash, ToString);

// Paths
interfaces!(PathBuf: ObjectClone, Debug, ObjectPartialEq, ObjectPartialOrd, ObjectEq, ObjectOrd, ObjectHash);

// Vecs
interfaces!({
    Vec<bool>, Vec<i8>, Vec<u8>, Vec<i16>, Vec<u16>, Vec<i32>, Vec<u32>, Vec<i64>, Vec<u64>, Vec<char>
}: ObjectClone, Debug, ObjectPartialEq, ObjectPartialOrd, ObjectEq, ObjectOrd, ObjectHash);
interfaces!({
    Vec<f32>, Vec<f64>
}: ObjectClone, Debug, ObjectPartialEq, ObjectPartialOrd);
interfaces!({
    Vec<String>, Vec<PathBuf>
}: ObjectClone, Debug, ObjectPartialEq, ObjectPartialOrd, ObjectEq, ObjectOrd, ObjectHash);


#[cfg(test)]
mod tests {
    use std::fmt::Debug;
    use std::sync::Arc;
    use std::rc::Rc;

    #[derive(Debug, Clone)]
    struct Bar;
    interfaces!(Bar: Foo, super::ObjectClone, Debug, Custom);

    trait Foo: Debug {
        fn test(&self) -> bool { false }
    }
    trait Foo2: Debug {}
    impl Foo for Bar {
        fn test(&self) -> bool { true }
    }
    impl Foo2 for Bar {}

    #[derive(Debug, Clone)]
    struct GenericBar<T>(T);
    interfaces!(<T: Debug + 'static> GenericBar<T>: super::ObjectClone, Debug where T: Clone);

    #[test]
    fn test_ref() {
        let x = Box::new(Bar) as Box<super::Object>;
        let foo: Option<&Foo> = x.query_ref();
        assert!(foo.is_some());
        assert!(foo.unwrap().test());
        let foo2: Option<&Foo2> = x.query_ref();
        assert!(foo2.is_none());
        let bar: Option<&Bar> = x.query_ref();
        assert!(bar.is_some());
    }

    #[test]
    fn test_mut() {
        let mut x = Box::new(Bar) as Box<super::Object>;
        {
            let foo = x.query_mut::<Foo>();
            assert!(foo.is_some());
            assert!(foo.unwrap().test());
        }
        {
            let foo2 = x.query_mut::<Foo2>();
            assert!(foo2.is_none());
        }
        {
            let bar = x.query_mut::<Bar>();
            assert!(bar.is_some());
        }
    }

    #[test]
    fn test_owned() {
        let x = Box::new(Bar) as Box<super::Object>;
        let foo: Result<Box<Foo>, _> = x.clone().query();
        assert!(foo.is_ok());
        assert!(foo.unwrap().test());
        let foo2: Result<Box<Foo2>, _> = x.clone().query();
        assert!(foo2.is_err());
        let bar: Result<Box<Bar>, _> = x.clone().query();
        assert!(bar.is_ok());
    }

    #[test]
    fn test_rc() {
        let x = Rc::new(Bar) as Rc<super::Object>;
        let foo: Result<Rc<Foo>, _> = super::Object::query_rc(x.clone());
        assert!(foo.is_ok());
        assert!(foo.unwrap().test());
        let foo2: Result<Rc<Foo2>, _> = super::Object::query_rc(x.clone());
        assert!(foo2.is_err());
        let bar: Result<Rc<Bar>, _> = super::Object::query_rc(x.clone());
        assert!(bar.is_ok());
    }

    #[test]
    fn test_arc() {
        let x = Arc::new(Bar) as Arc<super::Object>;
        let foo: Result<Arc<Foo>, _> = super::Object::query_arc(x.clone());
        assert!(foo.is_ok());
        assert!(foo.unwrap().test());
        let foo2: Result<Arc<Foo2>, _> = super::Object::query_arc(x.clone());
        assert!(foo2.is_err());
        let bar: Result<Arc<Bar>, _> = super::Object::query_arc(x.clone());
        assert!(bar.is_ok());
    }

    trait Custom : super::Object {}
    impl Custom for Bar {}
    mopo!(Custom);

    #[test]
    fn test_derived() {
        let x = Box::new(Bar) as Box<Custom>;
        let foo: Result<Box<Foo>, _> = x.clone().query();
        assert!(foo.is_ok());
        assert!(foo.unwrap().test());
        let foo2: Result<Box<Foo2>, _> = x.clone().query();
        assert!(foo2.is_err());
        let bar: Result<Box<Bar>, _> = x.clone().query();
        assert!(bar.is_ok());
    }

    trait Dynamic {
        fn test(&self) -> u32;
    }
    impl Dynamic for Bar {
        fn test(&self) -> u32 { 42 }
    }

    #[test]
    fn test_dynamic() {
        let x = Box::new(Bar) as Box<super::Object>;
        let dyn1: Option<&Dynamic> = x.query_ref();
        assert!(dyn1.is_none());

        dynamic_interfaces! {
            Bar: Dynamic;
        }

        let dyn2: Option<&Dynamic> = x.query_ref();
        assert!(dyn2.unwrap().test() == 42);
    }

    #[test]
    fn test_primitives() {
        Box::new(1) as Box<super::Object>;
        Box::new(1f32) as Box<super::Object>;
        Box::new("test".to_string()) as Box<super::Object>;
        Box::new(vec![1,2,3]) as Box<super::Object>;
    }
}