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
//! Support package for phreak_engine.
//!
//! The phreak_facts module is used to separate the fact generation logic from the phreak_engine.
//!
#[macro_use]
extern crate serde;

use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::rc::Rc;

use generational_arena::{Arena, Index as Handle};
use serde::export::fmt::Error;
use serde::export::Formatter;

pub use data::Value;

mod data;

/// A FactAttribute consists of three values
///
/// The normal usage would be:
///  attribute.0 identifies the object
///  attribute.1 identifies the type of the attribute
///  attribute.2 identifies the value
#[derive(Serialize, Deserialize, PartialEq, Eq)]
pub struct FactAttribute(pub Value, pub Value, pub Value);

// impl PartialEq for FactAttribute {
//     fn eq(&self, other: &Self) -> bool {
//         self.0 == other.0 && self.1 == other.1 && self.2 == other.2
//     }
// }

//impl Eq for FactAttribute {}

impl Hash for FactAttribute {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
        self.1.hash(state);
        self.2.hash(state);
    }
}

impl PartialOrd for FactAttribute {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let mut r = self.0.partial_cmp(&other.0);
        if r == Some(Ordering::Equal) {
            r = self.1.partial_cmp(&other.1);
        }
        if r == Some(Ordering::Equal) {
            r = self.2.partial_cmp(&other.2);
        }
        r
    }
}

impl Ord for FactAttribute {
    fn cmp(&self, other: &Self) -> Ordering {
        let mut r = self.0.cmp(&other.0);
        if Ordering::Equal == r {
            r = self.1.cmp(&other.1);
        }
        if Ordering::Equal == r {
            r = self.2.cmp(&other.2);
        }
        r
    }
}

impl Debug for FactAttribute {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        write!(f, "<{}, {}, {}>", &self.0, &self.1, &self.2)
    }
}

/// FactObject contains grouped information around a single object.
///
/// Example: A Car can have multiple pieces of information associated:
///  The color is red.
///  It has 4 wheels, and 3 doors.
///  The brand is Ferrari
///
/// This information is stored in a standardized way for the phreak algorithm, in order to
/// efficiently match conditions against the known facts.
#[derive(Serialize, Deserialize)]
pub struct FactObject {
    // note: for now we store this using multiple allocations, but ideally this would be
    // a single allocation of continues memory
    class: String,
    attrs: Vec<Rc<FactAttribute>>,
}

impl FactObject {
    pub fn get_name(&self) -> &String {
        &self.class
    }

    pub fn iter_attrs(&self) -> std::slice::Iter<'_, Rc<FactAttribute>> {
        self.attrs.iter()
    }
}

impl Debug for FactObject {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        let v: Vec<(&Value, &Value, &Value)> = self.attrs.iter().map(|rc| {
            let b: &FactAttribute = rc.borrow();
            (&b.0, &b.1, &b.2)
        }).collect();
        write!(f, "Facts{{ class='{}', attrs={:?} }}", self.class, v)
    }
}

impl Clone for FactObject {
    fn clone(&self) -> Self {
        FactObject { class: self.class.to_owned(), attrs: self.attrs.clone() }
    }
}

impl Hash for FactObject {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.class.hash(state);
        for attr in self.attrs.iter() {
            let b: &FactAttribute = attr.borrow();
            b.0.hash(state);
            b.1.hash(state);
            b.2.hash(state);
        }
    }
}

impl PartialEq for FactObject {
    fn eq(&self, other: &Self) -> bool {
        let mut b = self.class == other.class && self.attrs.len() == other.attrs.len();
        let mut i = 0;
        while b && i < self.attrs.len() {
            let left: &FactAttribute = self.attrs[i].borrow();
            let right: &FactAttribute = other.attrs[i].borrow();
            b = left.0 == right.0 && left.1 == right.1 && left.2 == right.2;
            i = i + 1;
        }
        b
    }
}

/// To facilitate the creation of facts, we offer a builder pattern.
///
/// To simplify the conversion from an object into a facts structure, we offer this
/// builder pattern.
///
/// ```
/// # use phreak_facts::FactsBuilder;
/// let facts = FactsBuilder::new("Car".to_owned())
///     .add_attributes("123".to_string(), "color".to_string(), "red".to_string())
///     .add_attributes("123".to_string(), "type".to_string(), "hatchback".to_string())
///     .add_attributes("123".to_string(), "brand".to_string(), "Toyota".to_string())
///     .build()
/// ;
///
/// ```
pub struct FactsBuilder {
    f: Option<FactObject>,
}

impl FactsBuilder {
    /// Start building a new Facts object with the given class name
    pub fn new(name: String) -> Self {
        FactsBuilder { f: Some(FactObject { class: name, attrs: vec!() }) }
    }

    /// Add one triple of information
    ///
    /// Triples can be of the format ( instance-id, attribute, value )
    pub fn add_attributes(mut self, field1: String, field2: String, field3: String) -> Self {
        match &mut self.f {
            None => panic!("Set classname first"),
            Some(facts) => {
                facts.attrs.push(Rc::new(FactAttribute(
                    Value::from(field1),
                    Value::from(field2),
                    Value::from(field3))
                ));
            }
        }
        self
    }

    /// Add one triple of information
    ///
    /// Triples can be of the format ( instance-id, attribute, value )
    pub fn add_attributes_from_slice(mut self, field1: &str, field2: &str, field3: &str) -> Self {
        match &mut self.f {
            None => panic!("Set classname first"),
            Some(facts) => {
                let f = FactAttribute(
                    Value::from(field1),
                    Value::from(field2),
                    Value::from(field3),
                );
                facts.attrs.push(Rc::new(f));
            }
        }
        self
    }

    pub fn add_values(mut self, field1: Value, field2: Value, field3: Value) -> Self {
        match &mut self.f {
            None => panic!("Set classname first"),
            Some(facts) => {
                facts.attrs.push(Rc::new(FactAttribute(field1, field2, field3)));
            }
        }
        self
    }

    /// Finalize the facts object and return it
    pub fn build(self) -> FactObject {
        self.f.unwrap()
    }
}

/// Long-time storage of facts
pub struct Store {
    arena: Arena<FactObject>,
    handles: BTreeMap<u64, Vec<Handle>>,
}

impl Store {
    /// Create a new Store
    pub fn new() -> Self {
        Store { arena: Arena::new(), handles: BTreeMap::new() }
    }

    /// Add a single Facts object to the store, and return a Handle to it
    pub fn add_facts(&mut self, facts: FactObject) -> Handle {
        let mut s = DefaultHasher::new();
        facts.hash(&mut s);
        let hash = s.finish();

        let handle = self.arena.insert(facts);

        match &mut self.handles.get_mut(&hash) {
            None => {
                let mut v = Vec::with_capacity(1);
                v.push(handle);
                self.handles.insert(hash, v);
            }
            Some(v) => {
                v.push(handle);
            }
        }
        handle
    }

    /// Remove a Facts object by its handle
    pub fn remove_facts(&mut self, handle: Handle) -> Option<FactObject> {
        let facts = self.arena.remove(handle);
        match &facts {
            None => {}
            Some(f) => {
                let mut s = DefaultHasher::new();
                f.hash(&mut s);
                let hash = s.finish();
                match self.handles.get_mut(&hash) {
                    None => { panic!("Handle not found in Arena: {:?}", handle) }
                    Some(v) => {
                        let i = v.iter().enumerate().find(|h| h.1 == &handle).expect("Handle not found in bucket").0;
                        if v.len() == 1 {
                            v.pop();
                        } else {
                            if i == v.len() - 1 {
                                v.remove(i);
                            } else {
                                v.swap_remove(i);
                            }
                        }
                    }
                }
                self.handles.remove(&hash);
            }
        }
        facts
    }

    /// get the handle to a facts object
    pub fn find_facts(&self, facts: &FactObject) -> Option<Handle> {
        let mut s = DefaultHasher::new();
        facts.hash(&mut s);
        let hash = s.finish();

        // get the handle for the given facts object from the bucket
        self.handles.get(&hash).and_then(|bucket| { // get the bucket
            bucket.iter().find(|index| { // find the entry
                self.arena[**index] == *facts
            }).and_then(|handle| { // return the handle
                Some(handle.clone())
            })
        })
    }
}


#[cfg(test)]
mod tests {
    use test_case::test_case;

    use super::*;

    #[test_case("1", "2", "3")]
    fn test_facts_store(f1: &str, f2: &str, f3: &str) {
        let fact = FactsBuilder::new("class1".to_owned())
            .add_attributes_from_slice(f1, f2, f3)
            .build();

        let mut s = Store::new();
        let index = s.add_facts(fact);

        let fact = FactsBuilder::new("class1".to_owned())
            .add_attributes_from_slice(f1, f2, f3)
            .build();
        assert_eq!(s.find_facts(&fact), Some(index));

        s.remove_facts(index);
        assert_eq!(s.find_facts(&fact), None);
    }
}