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
//! Value type and implementation for run-time memory space values.

use std::fmt;
use std::ops::Add;
use std::cmp::Ordering;

use sindra;
use sindra::value::{Coerce, Cast, Extract};

use ast::Literal;
use PType;

use psk_std::complex::Complex;

/// Value type for run-time memory values.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// Storage for string value
    String(String),
    /// Storage for floating point number value
    Float(f64),
    /// Storage for integer number value
    Int(i64),
    /// Storage for a boolean,
    Boolean(bool),
    /// Storage for a complex number,
    Complex(f64, f64),
    /// Storage for a set
    Set(Box<ValueSet>),
    /// Indication of a value returned from a function
    Return(Box<Value>),
    /// Indication of a value resulting from a break in a loop
    Break(Box<Value>),
    /// Indication of empty / null value
    Empty
}
impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
        match *self {
            Value::String(ref s)  => write!(f, "{}", s),
            Value::Float(ref fl)  => write!(f, "{}", fl),
            Value::Int(ref i)     => write!(f, "{}", i),
            Value::Boolean(ref b) => write!(f, "{}", b),
            Value::Complex(ref re, ref im)
                                  => write!(f, "{}+{}i", re, im),
            Value::Set(ref s)     => write!(f, "{}", s),
            Value::Return(ref v)  => write!(f, "{}", *v),
            Value::Break(ref v)   => write!(f, "{}", *v),
            Value::Empty          => write!(f, "<null>")
        }
    }
}
impl sindra::Value for Value {}

impl From<Literal> for Value {
    fn from(lit: Literal) -> Value {
        match lit {
            Literal::String(s) => Value::String(s),
            Literal::Float(f) => Value::Float(f),
            Literal::Int(i) => Value::Int(i),
            Literal::Boolean(b) => Value::Boolean(b),
        }
    }
}

impl<'a> From<&'a Value> for PType {
    fn from(v: &'a Value) -> PType {
        match *v {
            Value::String(_)      => PType::String,
            Value::Float(_)       => PType::Float,
            Value::Int(_)         => PType::Int,
            Value::Boolean(_)     => PType::Boolean,
            Value::Complex(_, _)  => PType::Complex,
            Value::Set(_)         => PType::Set,
            Value::Return(ref v)  => PType::from(v.as_ref()),
            Value::Break(ref v)   => PType::from(v.as_ref()),
            Value::Empty          => PType::Void,
        }
    }
}

impl Cast<PType> for Value {
    fn cast(self, dest_ty: PType) -> Value {
        match dest_ty {
            PType::Float => {
                match self {
                    Value::Int(i) => Value::Float(i as f64),
                    _ => self
                }
            },
            PType::Complex => {
                match self {
                    Value::Int(i) => Value::Complex(i as f64, 0.0),
                    Value::Float(f) => Value::Complex(f, 0.0),
                    _ => self
                }
            }
            _ => self
        }
    }
}
impl Cast<PType> for PType {
    fn cast(self, dest_ty: PType) -> PType {
        match dest_ty {
            PType::Float => {
                match self {
                    PType::Int => PType::Float,
                    _ => self
                }
            },
            PType::Complex => {
                match self {
                    PType::Int => PType::Complex,
                    PType::Float => PType::Complex,
                    _ => self
                }
            },
            _ => self
        }
    }
}

impl Coerce<PType> for Value {
    fn coerce(self, dest_ty: Option<PType>) -> Value {
        match dest_ty {
            Some(dest) => {
                self.cast(dest)
            },
            None => self
        }
    }
}
impl Coerce<PType> for PType {
    fn coerce(self, dest_ty: Option<PType>) -> PType {
        match dest_ty {
            Some(dest) => {
                self.cast(dest)
            },
            None => self
        }
    }
}

impl<'a> Add for &'a Value {
    type Output = Value;

    fn add(self, rhs: &Value) -> Value {
        match (self, rhs) {
            (&Value::Float(ref left), &Value::Float(ref right)) => {
                Value::Float(left + right)
            },
            (&Value::Int(ref left), &Value::Int(ref right)) => {
                Value::Int(left + right)
            },
            _ => panic!("unable to add value of type '{}' with a rhs of type '{}'",
                PType::from(self), PType::from(rhs))
        }
    }
}
impl PartialOrd for Value {
    fn partial_cmp(&self, other: &Value) -> Option<Ordering> {
        match (self, other) {
            (&Value::Float(ref left), &Value::Float(ref right)) => {
                left.partial_cmp(&right)
            },
            (&Value::Int(ref left), &Value::Int(ref right)) => {
                left.partial_cmp(&right)
            },
            _ => panic!("unable to add value of type '{}' with a rhs of type '{}'",
                PType::from(self), PType::from(other))
        }
    }
}

impl Value {
    /// Returns true if the associated type for this value is the same type as the associated
    /// type of the other value. Returns false otherwise.
    pub fn has_same_type(&self, other: &Value) -> bool {
        PType::from(self) == PType::from(other)
    }
}

impl Extract<u64> for Value {
    fn extract(&self) -> Result<u64, String> {
        match *self {
            Value::Int(i) => {
                Ok(i as u64)
            },
            _ => Err(format!("unable to extract unsigned int from type {}", PType::from(self)))
        }
    }
}
impl Extract<usize> for Value {
    fn extract(&self) -> Result<usize, String> {
        match *self {
            Value::Int(i) => {
                Ok(i as usize)
            },
            _ => Err(format!("unable to extract unsigned int from type {}", PType::from(self)))
        }
    }
}
impl Extract<i64> for Value {
    fn extract(&self) -> Result<i64, String> {
        match *self {
            Value::Int(i) => {
                Ok(i)
            },
            _ => Err(format!("unable to extract int from type {}", PType::from(self)))
        }
    }
}
impl Extract<String> for Value {
    fn extract(&self) -> Result<String, String> {
        match *self {
            Value::String(ref s) => {
                Ok(s.clone())
            },
            _ => Err(format!("unable to extract string from type {}", PType::from(self)))
        }
    }
}
impl Extract<f64> for Value {
    fn extract(&self) -> Result<f64, String> {
        match *self {
            Value::Float(f) => {
                Ok(f)
            },
            _ => Err(format!("unable to extract float from type {}", PType::from(self)))
        }
    }
}
impl Extract<Complex> for Value {
    fn extract(&self) -> Result<Complex, String> {
        match *self {
            Value::Complex(re, im) => {
                Ok(Complex::new(re, im))
            },
            _ => Err(format!("unable to extract complex from type {}", PType::from(self)))
        }
    }
}


/// Value type for sets
#[derive(Debug, Clone, PartialEq)]
pub enum ValueSet {
    /// A set represented by an interval specification
    Interval(SetInterval)
}

impl ValueSet {
    /// Return an iterator over the elements of the set.
    ///
    /// #Failures
    /// Returns an `Err` if the set definition is inconsistent (e.g. has inconsistent types in
    /// the type definition)
    pub fn iter<'a>(&'a self) -> Result<SetIter<'a>, String> {
        let iter = match *self {
            ValueSet::Interval(ref interval) => {
                // verify interval types
                if !interval.start.has_same_type(&interval.end) ||
                        !interval.start.has_same_type(&interval.step) {
                    return Err("interval must have same value type for start, end, and step \
                        to be iterated".to_string())
                }
                SetIter::Interval {
                    set: interval,
                    prev: None
                }
            }
        };
        Ok(iter)
    }
}

impl fmt::Display for ValueSet {
    fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
        match *self {
            ValueSet::Interval(ref set) => write!(f, "{}", set),
        }
    }
}

/// Set specification using an interval specification.
#[derive(Debug, Clone, PartialEq)]
pub struct SetInterval {
    /// Starting value for the interval (inclusive).
    pub start: Value,
    /// Ending value for the interval (exclusive).
    pub end: Value,
    /// Whether the ending value for the interval is inclusive or exclusive.
    pub end_inclusive: bool,
    /// Step level for the interval.
    pub step: Value,
}

impl fmt::Display for SetInterval {
    fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
        write!(f, "{}..{}..{}", self.start, self.step, self.end)
    }
}

/// Iterator over a set.
pub enum SetIter<'a> {
    /// Iterator over a set represented by an interval.
    Interval {
        /// Reference to the underlying set interval specification.
        set: &'a SetInterval,
        /// Previous value returned by iterator
        prev: Option<Value>,
    }
}
impl<'a> Iterator for SetIter<'a> {
    type Item = Value;

    fn next(&mut self) -> Option<Value> {
        match *self {
            SetIter::Interval { ref set, ref mut prev } => {
                let next = match *prev {
                    Some(ref prev) => {
                        prev + &set.step
                    },
                    None => {
                        set.start.clone()
                    }
                };
                // terminate only when completely past the end of the set when the set is inclusive,
                // terminate when at the end or beyond when the set is exclusive
                let terminate = if set.end_inclusive {
                    next > set.end
                } else {
                    next >= set.end
                };
                if terminate {
                    None
                } else {
                    *prev = Some(next.clone());
                    Some(next)
                }

            }
        }
    }
}