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
//! Trait and implementations of `ToPolar` for converting from
//! Rust types back to Polar types.

use impl_trait_for_tuples::*;
use polar_core::terms::*;

use std::collections::HashMap;
use std::iter;

use super::Host;
use crate::host::Instance;
use crate::PolarValue;

/// Convert Rust types to Polar types.
///
/// This trait is automatically implemented for any
/// type that implements the `PolarClass` marker trait,
/// which should be preferred.
///
/// This is also implemented automatically using the
/// `#[derive(PolarClass)]` macro.
///
/// For non-primitive types, the instance will be stored
/// on the provided `Host`.
/// ## Trait bounds
///
/// `ToPolar` requires types to be `Send + Sync`, since it
/// is possible to store a `ToPolar` value on an `Oso` instance
/// which can be shared between threads.
///
/// `ToPolar` implementors must also be concrete, sized types without
/// any borrows.
pub trait ToPolar: Send + Sync + Sized + 'static {
    fn to_polar_value(self, host: &mut Host) -> Value {
        let instance = Instance::new(self);
        let instance = host.cache_instance(instance, None);
        Value::ExternalInstance(ExternalInstance {
            constructor: None,
            repr: Some(std::any::type_name::<Self>().to_owned()),
            instance_id: instance,
        })
    }

    fn to_polar(self, host: &mut Host) -> Term {
        Term::new_from_ffi(self.to_polar_value(host))
    }
}

impl<C: crate::PolarClass + Send + Sync> ToPolar for C {
    fn to_polar_value(self, host: &mut Host) -> Value {
        let instance = Instance::new(self);
        let instance = host.cache_instance(instance, None);
        if host.get_class_from_type::<Self>().is_err() {
            let class = Self::get_polar_class();
            let name = Symbol(class.name.clone());
            tracing::info!("class {} not previously registered, doing so now", name.0);
            // If we hit this error its because somehow we didn't find the class, and yet
            // we also weren't able to register the class because the name already exists.
            // TODO: can we handle this without panicking?
            host.cache_class(class, name)
                .expect("failed to register a class that we thought was previously unregistered");
        }
        Value::ExternalInstance(ExternalInstance {
            constructor: None,
            repr: Some(std::any::type_name::<Self>().to_owned()),
            instance_id: instance,
        })
    }
}

mod private {
    /// Prevents implementations of `ToPolarList` outside of this crate
    pub trait Sealed {}
}

pub trait ToPolarList: private::Sealed {
    fn to_polar_list(self, host: &mut Host) -> Vec<Term>
    where
        Self: Sized;
}

#[impl_for_tuples(16)]
#[tuple_types_custom_trait_bound(ToPolar + 'static)]
impl private::Sealed for Tuple {}

impl ToPolarList for () {
    fn to_polar_list(self, _host: &mut Host) -> Vec<Term> {
        Vec::new()
    }
}

#[impl_for_tuples(1, 16)]
#[tuple_types_custom_trait_bound(ToPolar + 'static)]
impl ToPolarList for Tuple {
    fn to_polar_list(self, host: &mut Host) -> Vec<Term> {
        let mut result = Vec::new();
        for_tuples!(
            #( result.push(self.Tuple.to_polar(host)); )*
        );
        result
    }
}

impl ToPolar for bool {
    fn to_polar_value(self, _host: &mut Host) -> Value {
        Value::Boolean(self)
    }
}

macro_rules! int_to_polar {
    ($i:ty) => {
        impl ToPolar for $i {
            fn to_polar_value(self, _host: &mut Host) -> Value {
                Value::Number(Numeric::Integer(self.into()))
            }
        }
    };
}

int_to_polar!(u8);
int_to_polar!(i8);
int_to_polar!(u16);
int_to_polar!(i16);
int_to_polar!(u32);
int_to_polar!(i32);
int_to_polar!(i64);

macro_rules! float_to_polar {
    ($i:ty) => {
        impl ToPolar for $i {
            fn to_polar_value(self, _host: &mut Host) -> Value {
                Value::Number(Numeric::Float(self.into()))
            }
        }
    };
}

float_to_polar!(f32);
float_to_polar!(f64);

impl ToPolar for String {
    fn to_polar_value(self, _host: &mut Host) -> Value {
        Value::String(self)
    }
}

impl ToPolar for &'static str {
    fn to_polar_value(self, _host: &mut Host) -> Value {
        Value::String(self.to_string())
    }
}

impl<T: ToPolar> ToPolar for Vec<T> {
    fn to_polar_value(self, host: &mut Host) -> Value {
        Value::List(self.into_iter().map(|v| v.to_polar(host)).collect())
    }
}

impl<T: ToPolar> ToPolar for HashMap<String, T> {
    fn to_polar_value(self, host: &mut Host) -> Value {
        Value::Dictionary(Dictionary {
            fields: self
                .into_iter()
                .map(|(k, v)| (Symbol(k), v.to_polar(host)))
                .collect(),
        })
    }
}

impl ToPolar for PolarValue {
    fn to_polar_value(self, host: &mut Host) -> Value {
        self.to_term(host).value().clone()
    }
}

impl ToPolar for Value {
    fn to_polar_value(self, _host: &mut Host) -> Value {
        self
    }
}

pub type PolarResultIter = Box<dyn Iterator<Item = Result<Term, crate::OsoError>> + 'static>;

// Trait for the return value of class methods.
// This allows us to return polar values, as well as options and results of polar values.
pub trait ToPolarResults {
    fn to_polar_results(self, host: &mut Host) -> PolarResultIter;
}

impl<C: 'static + Sized + ToPolar> ToPolarResults for C {
    fn to_polar_results(self, host: &mut Host) -> PolarResultIter {
        Box::new(iter::once(Ok(self.to_polar(host))))
    }
}

impl<C, E> ToPolarResults for Result<C, E>
where
    C: ToPolarResults,
    E: std::error::Error + 'static + Send + Sync,
{
    fn to_polar_results(self, host: &mut Host) -> PolarResultIter {
        match self {
            Ok(result) => result.to_polar_results(host),
            Err(e) => Box::new(iter::once(Err(crate::OsoError::ApplicationError {
                source: Box::new(e),
                type_name: None,
                attr: None,
            }))),
        }
    }
}

// NOTE: MISSING specialization... Want to have a variant for Result that
// is not over an error, but alas impossible???

impl<C: ToPolarResults> ToPolarResults for Option<C> {
    fn to_polar_results(self, host: &mut Host) -> PolarResultIter {
        self.map_or_else(
            || Box::new(std::iter::empty()) as PolarResultIter,
            |c| c.to_polar_results(host),
        )
    }
}

pub struct PolarIter<I, Iter>
where
    I: ToPolarResults + 'static,
    Iter: std::iter::Iterator<Item = I> + Sized + 'static,
{
    pub iter: Iter,
}

impl<I: ToPolarResults + 'static, Iter: std::iter::Iterator<Item = I> + Sized + 'static>
    ToPolarResults for PolarIter<I, Iter>
{
    fn to_polar_results(self, host: &mut Host) -> PolarResultIter {
        Box::new(
            self.iter
                .flat_map(|i| i.to_polar_results(host))
                .collect::<Vec<crate::Result<Term>>>()
                .into_iter(),
        ) as PolarResultIter
    }
}