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
use {Ident, Lifetime, LifetimeDef};
use aster::invoke::{Invoke, Identity};

// ////////////////////////////////////////////////////////////////////////////

pub trait IntoLifetime {
    fn into_lifetime(self) -> Lifetime;
}

impl IntoLifetime for Lifetime {
    fn into_lifetime(self) -> Lifetime {
        self
    }
}

impl<'a> IntoLifetime for &'a str {
    fn into_lifetime(self) -> Lifetime {
        Lifetime { ident: self.into() }
    }
}

// ////////////////////////////////////////////////////////////////////////////

pub trait IntoLifetimeDef {
    fn into_lifetime_def(self) -> LifetimeDef;
}

impl IntoLifetimeDef for LifetimeDef {
    fn into_lifetime_def(self) -> LifetimeDef {
        self
    }
}

impl IntoLifetimeDef for Lifetime {
    fn into_lifetime_def(self) -> LifetimeDef {
        LifetimeDef {
            attrs: vec![],
            lifetime: self,
            bounds: vec![],
        }
    }
}

impl<'a> IntoLifetimeDef for &'a str {
    fn into_lifetime_def(self) -> LifetimeDef {
        self.into_lifetime().into_lifetime_def()
    }
}

impl IntoLifetimeDef for String {
    fn into_lifetime_def(self) -> LifetimeDef {
        (*self).into_lifetime().into_lifetime_def()
    }
}

// ////////////////////////////////////////////////////////////////////////////

pub struct LifetimeDefBuilder<F = Identity> {
    callback: F,
    lifetime: Lifetime,
    bounds: Vec<Lifetime>,
}

impl LifetimeDefBuilder {
    pub fn new<N>(name: N) -> Self
        where N: Into<Ident>
    {
        LifetimeDefBuilder::with_callback(name, Identity)
    }
}

impl<F> LifetimeDefBuilder<F>
    where F: Invoke<LifetimeDef>
{
    pub fn with_callback<N>(name: N, callback: F) -> Self
        where N: Into<Ident>
    {
        let lifetime = Lifetime { ident: name.into() };

        LifetimeDefBuilder {
            callback: callback,
            lifetime: lifetime,
            bounds: Vec::new(),
        }
    }

    pub fn bound<N>(mut self, name: N) -> Self
        where N: Into<Ident>
    {
        let lifetime = Lifetime { ident: name.into() };

        self.bounds.push(lifetime);
        self
    }

    pub fn build(self) -> F::Result {
        self.callback.invoke(LifetimeDef {
            attrs: vec![],
            lifetime: self.lifetime,
            bounds: self.bounds,
        })
    }
}