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
//! `Obj` module.
//! A hashmap of keys to values, where values can be any type, including other objects.

#![allow(unused_imports)] // will complain about num_traits::Zero otherwise

use OverResult;
use arr::Arr;
use error::OverError;
use fraction::BigFraction;
use num::bigint::BigInt;
use num_traits::Zero;
use parse;
use std::cell::RefCell;
use std::collections::HashMap;
use std::convert;
use std::io;
use std::rc::Rc;
use std::str::FromStr;
use tup::Tup;
use types::Type;
use value::Value;

#[derive(Clone, Debug)]
struct ObjInner {
    fields: HashMap<String, Value>,
    parent: Option<Obj>,
}

/// `Obj` struct.
#[derive(Clone, Debug)]
pub struct Obj {
    inner: Rc<RefCell<ObjInner>>,
}

macro_rules! get_fn {
    ( $name:tt, $type:ty ) => {
        /// Try to get the `$type` associated with `field`.
        pub fn $name(&self, field: &str) -> OverResult<$type> {
            match self.get(field) {
                Some(value) => {
                    match value.$name() {
                        Ok(result) => Ok(result),
                        e @ Err(_) => e,
                    }
                }
                None => Err(OverError::FieldNotFound(field.into())),
            }
        }
    }
}

impl Obj {
    /// Returns a new empty `Obj`.
    pub fn new() -> Obj {
        Obj {
            inner: Rc::new(RefCell::new(ObjInner {
                fields: HashMap::new(),
                parent: None,
            })),
        }
    }

    /// Returns a new `Obj` loaded from a file.
    pub fn from_file(path: &str) -> OverResult<Obj> {
        parse::load_from_file(path).map_err(OverError::from)
    }

    /// Writes this `Obj` to given file in `.over` representation.
    pub fn write_to_file(&self, path: &str) -> OverResult<()> {
        parse::write_to_file(self, path).map_err(OverError::from)
    }

    /// Returns the number of fields for this `Obj` (children/parents not included).
    // TODO: test this
    pub fn len(&self) -> usize {
        self.inner.borrow().fields.len()
    }

    /// Returns whether this `Obj` is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.borrow().fields.is_empty()
    }

    /// Returns whether this `Arr` and `other` point to the same data.
    pub fn ptr_eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.inner, &other.inner)
    }

    /// Returns true iff the `Obj` contains `field`.
    pub fn contains(&self, field: &str) -> bool {
        self.inner.borrow().fields.contains_key(field)
    }

    /// Removes a field and its associated value from the `Obj`.
    pub fn remove(&mut self, field: &str) -> Option<Value> {
        match self.inner.borrow_mut().fields.remove(field) {
            Some(value) => Some(value),
            None => None,
        }
    }

    /// Clears all fields from the `Obj`.
    pub fn clear(&mut self) {
        self.inner.borrow_mut().fields.clear();
    }

    /// Gets the `Value` associated with `field`.
    pub fn get(&self, field: &str) -> Option<Value> {
        let inner = self.inner.borrow();

        match inner.fields.get(field) {
            Some(value) => Some(value.clone()),
            None => {
                match inner.parent {
                    Some(ref parent) => parent.get(field),
                    None => None,
                }
            }
        }
    }

    get_fn!(get_bool, bool);
    get_fn!(get_int, BigInt);
    get_fn!(get_frac, BigFraction);
    get_fn!(get_char, char);
    get_fn!(get_str, String);
    get_fn!(get_arr, Arr);
    get_fn!(get_tup, Tup);
    get_fn!(get_obj, Obj);

    /// Sets the `Value` for `field`.
    pub fn set(&mut self, field: &str, value: Value) {
        let _ = self.inner.borrow_mut().fields.insert(
            String::from(field),
            value,
        );
    }

    /// Returns whether this `Obj` has a parent.
    pub fn has_parent(&self) -> bool {
        self.inner.borrow().parent.is_some()
    }

    /// Returns the parent for this `Obj`.
    pub fn get_parent(&self) -> OverResult<Obj> {
        match self.inner.borrow().parent {
            Some(ref parent) => Ok(parent.clone()),
            None => Err(OverError::NoParentFound),
        }
    }

    /// Sets the parent for this `Obj`.
    /// Circular references in parents are not allowed.
    pub fn set_parent(&mut self, parent: &Obj) -> OverResult<()> {
        // Test for a circular reference.
        let mut cur_parent = parent.clone();
        if self.ptr_eq(&cur_parent) {
            return Err(OverError::CircularParentReferences);
        }
        while cur_parent.has_parent() {
            cur_parent = cur_parent.get_parent()?;
            if self.ptr_eq(&cur_parent) {
                return Err(OverError::CircularParentReferences);
            }
        }

        self.inner.borrow_mut().parent = Some(parent.clone());
        Ok(())
    }

    // TODO:
    // /// An iterator visiting all field/value pairs in arbitrary order.
    // pub fn iter(&self) -> OverResult<Iter<String, Value>> {
    //     match self.fields {
    //         None => Err(OverError::NullObj),
    //         Some(ref fields) => {
    //             let hashmap = fields.read().map_err(OverError::from)?;
    //             let cloned: HashMap<String, Value> = hashmap.iter().
    //                 map(|(field, value)| (field.clone(), value.clone()))
    //                 .collect();
    //             Ok(cloned.iter())
    //         }
    //     }
    // }
}

impl Default for Obj {
    fn default() -> Self {
        Self::new()
    }
}

impl FromStr for Obj {
    type Err = OverError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse::load_from_str(s).map_err(OverError::from)
    }
}

impl PartialEq for Obj {
    fn eq(&self, other: &Self) -> bool {
        let inner = self.inner.borrow();
        let other_inner = other.inner.borrow();

        if inner.parent.is_some() && other_inner.parent.is_some() {
            let parent = self.get_parent().unwrap();
            let other_parent = other.get_parent().unwrap();
            if !parent.ptr_eq(&other_parent) {
                return false;
            }
        } else if !(inner.parent.is_none() && other_inner.parent.is_none()) {
            return false;
        }

        inner.fields == other_inner.fields
    }
}

// TODO:
// pub struct Iter {

// }

// impl Iterator for Iter {
//     type Item = (String, Value);

//     fn next(&mut self) -> Option<Self::Item> {
//         match self.fields {
//             None => None,
//             Some(ref fields) => {
//                 fields.read().unwrap().next()
//             }
//         }
//     }
// }