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

use polar_core::terms::*;

use std::collections::HashMap;

use super::Host;

/// 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`.
pub trait ToPolar {
    fn to_polar_value(&self, host: &mut Host) -> Value;

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

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.clone())
    }
}

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

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

impl<T: ToPolar> ToPolar for Vec<T> {
    fn to_polar_value(&self, host: &mut Host) -> Value {
        Value::List(self.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
                .iter()
                .map(|(k, v)| (Symbol(k.to_string()), v.to_polar(host)))
                .collect(),
        })
    }
}

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

impl ToPolar for Box<dyn ToPolar> {
    fn to_polar_value(&self, host: &mut Host) -> Value {
        self.as_ref().to_polar_value(host)
    }
}

impl ToPolar for crate::Class {
    fn to_polar_value(&self, host: &mut Host) -> Value {
        let type_class = host.type_class();
        for method_name in self.class_methods.keys() {
            type_class
                .instance_methods
                .entry(method_name.clone())
                .or_insert_with(|| {
                    super::class_method::InstanceMethod::from_class_method(method_name.clone())
                });
        }
        let repr = format!("type<{}>", self.name);
        let instance = type_class.cast_to_instance(self.clone());
        let instance = host.cache_instance(instance, None);
        Value::ExternalInstance(ExternalInstance {
            constructor: None,
            repr: Some(repr),
            instance_id: instance,
        })
    }
}

impl<C: 'static + Clone + crate::PolarClass> ToPolar for C {
    fn to_polar_value(&self, host: &mut Host) -> Value {
        let class = host
            .get_class_from_type::<C>()
            .expect("Class not registered");
        let instance = class.cast_to_instance(self.clone());
        let instance = host.cache_instance(instance, None);
        Value::ExternalInstance(ExternalInstance {
            constructor: None,
            repr: None,
            instance_id: instance,
        })
    }
}

use std::iter;

pub type PolarResultIter = Box<dyn Iterator<Item = Result<Box<dyn ToPolar>, crate::OsoError>>>;

// 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) -> PolarResultIter;
}

impl<C: 'static + Sized + Clone + ToPolar> ToPolarResults for C {
    fn to_polar_results(&self) -> PolarResultIter {
        Box::new(iter::once(Ok(Box::new(self.clone()) as Box<dyn ToPolar>)))
    }
}

impl<C: ToPolarResults, E: ToString> ToPolarResults for Result<C, E> {
    fn to_polar_results(&self) -> PolarResultIter {
        match self {
            Ok(result) => result.to_polar_results(),
            Err(e) => Box::new(iter::once(Err(crate::OsoError::Custom {
                message: e.to_string(),
            }))),
        }
    }
}

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

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

impl<I: ToPolarResults, Iter: std::iter::Iterator<Item = I> + Clone + Sized + 'static>
    ToPolarResults for PolarIter<I, Iter>
{
    fn to_polar_results(&self) -> PolarResultIter {
        Box::new(self.iter.clone().flat_map(|e| e.to_polar_results()))
    }
}