someguynamedjosh / ouroboros

Easy self-referential struct generation for Rust.
Apache License 2.0
523 stars 35 forks source link

Macro call generates syntaxically invalid Rust code #116

Open Ten0 opened 2 months ago

Ten0 commented 2 months ago

e.g.

    use std::sync::Arc;

    pub struct Iter<T: 'static> {
        inner: IterInner<T>,
    }

    #[ouroboros::self_referencing]
    struct IterInner<T: 'static> {
        arc: Arc<Vec<T>>,
        #[borrows(mut arc)]
        iter: std::slice::Iter<'this, T>,
    }

    impl<T: 'static> Iter<T> {
        pub fn new(arc: Arc<Vec<T>>) -> Self {
            Iter {
                inner: IterInner::new(arc, |a| a.iter()),
            }
        }
    }

    impl<T: Clone> Iterator for Iter<T> {
        type Item = T;

        fn next(&mut self) -> Option<Self::Item> {
            self.inner.with_iter_mut(|a| a.next().cloned())
        }
    }

generates (notably):

 #[doc = "A struct for holding mutable references to all [tail fields](https://docs.rs/ouroboros/latest/ouroboros/attr.self_referencing.html#definitions) in an instance of [`IterInner`](IterInner)."]
    pub(super)struct BorrowedMutFields<'outer_borrow,'this0,T:'static>where 'static:'this0{
        pub(super)iter: &'outer_borrow mut std::slice::Iter<'this0,T> ,_consume_template_type_t: ::core::marker::PhantomData<T>
    }
    {
        ;
    }#[doc = "A struct which contains only the [head fields](https://docs.rs/ouroboros/latest/ouroboros/attr.self_referencing.html#definitions) of [`IterInner`](IterInner)."]
    pub(super)struct Heads<T:'static>{
        pub(super)arc:Arc<Vec<T> > ,_consume_template_type_t: ::core::marker::PhantomData<T>
    }

(note the "block" open which is incorrect in item position, and the random ;)

Workaround: this does not happen if specifying #[covariant].

Version: 0.18.4

QuantumEF commented 1 month ago

I believe I have an issue related to this as well where the following code

use std::collections::HashMap;

use ouroboros::self_referencing;

#[self_referencing]
struct MyStruct {
    items: Vec<String>,
    #[borrows(items)]
    map: HashMap<(&'this String, &'this String), (&'this String, &'this String)>,
}

Expands out to something containing:

{
        ::core::compile_error!{
            "Ouroboros cannot automatically determine if this type is covariant.\n\nAs an example, a Box<&'this ()> is covariant because it can be used as a\nBox<&'smaller ()> for any lifetime smaller than 'this. In contrast,\na Fn(&'this ()) is not covariant because it cannot be used as a\nFn(&'smaller ()). In general, values that are safe to use with smaller\nlifetimes than they were defined with are covariant, breaking this \nguarantee means the value is not covariant.\n\nTo resolve this error, add #[covariant] or #[not_covariant] to the field.\n"
        };
    }
The issue with my code being a missing `#[covariant]` but the error generated instead is a syntax error.
"error: expected item, found `{`"

ouroboros = "0.18.4"