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
use super::{debug_wrapper, CommonNodeTrait};
use crate::graph::value_wrappers::KBValue;
use crate::graph::{Graph, InjectionGraph};
use std::cmp::{Eq, Ordering, PartialEq};
use std::convert::TryFrom;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::rc::Rc;

/// All low-level wrappers will have these functions available.
pub trait BaseNodeTrait<T>: CommonNodeTrait {
    /// Associate this node with a value.
    fn set_value(&mut self, value: Rc<dyn KBValue>);

    /// Retrieve the value associated with this node.
    fn value(&self) -> Option<Rc<dyn KBValue>>;

    /// Link this node to another one via an outgoing edge.
    fn add_outgoing(&mut self, edge_type: usize, to: &T);

    /// Link this node to another one via an incoming edge.
    fn add_incoming(&mut self, edge_type: usize, from: &T);

    /// Whether or not this node is linked to another one via an outgoing edge of a certain type.
    fn has_outgoing(&self, edge_type: usize, to: &T) -> bool;

    /// Whether or not this node is linked to another one via an outgoing edge of a certain type.
    fn has_incoming(&self, edge_type: usize, from: &T) -> bool;

    /// All nodes that this one links to via outgoing edges of a certain type.
    fn outgoing_nodes(&self, edge_type: usize) -> Vec<T>;

    /// All nodes that this one links to via incoming edges of a certain type.
    fn incoming_nodes(&self, edge_type: usize) -> Vec<T>;
}

/// Implementation for the most basic of node wrappers. Offers no additional functionality.
#[derive(Copy, Clone)]
pub struct BaseNode {
    graph: InjectionGraph,
    id: usize,
}

#[allow(clippy::new_without_default)]
impl BaseNode {
    /// Create a new node.
    pub fn new() -> Self {
        let mut g = InjectionGraph::new();
        BaseNode {
            graph: g,
            id: g.add_node(),
        }
    }
}

impl From<usize> for BaseNode {
    fn from(id: usize) -> Self {
        BaseNode {
            graph: InjectionGraph::new(),
            id,
        }
    }
}

impl<'a> TryFrom<&'a str> for BaseNode {
    type Error = String;

    fn try_from(name: &'a str) -> Result<Self, Self::Error> {
        let g = InjectionGraph {};
        // The last ID will be the most recently added node. We want later nodes to override
        // earlier ones.
        match g.lookup(name).last() {
            Some(id) => Ok(BaseNode { graph: g, id: *id }),
            None => Err(format!("No node with name \"{}\" found.", name)),
        }
    }
}

impl Debug for BaseNode {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        debug_wrapper("BWrapper", self, f)
    }
}

impl Hash for BaseNode {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl Eq for BaseNode {}

impl PartialEq for BaseNode {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Ord for BaseNode {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id.cmp(&other.id)
    }
}

impl PartialOrd for BaseNode {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl CommonNodeTrait for BaseNode {
    fn id(&self) -> usize {
        self.id
    }

    fn set_internal_name(&mut self, name: String) {
        self.graph.set_node_name(self.id, name);
    }

    fn internal_name(&self) -> Option<Rc<String>> {
        self.graph.node_name(self.id)
    }
}

impl BaseNodeTrait<BaseNode> for BaseNode {
    fn set_value(&mut self, value: Rc<dyn KBValue>) {
        self.graph.set_node_value(self.id, value)
    }

    fn value(&self) -> Option<Rc<dyn KBValue>> {
        self.graph.node_value(self.id)
    }

    fn add_outgoing(&mut self, edge_type: usize, to: &BaseNode) {
        self.graph.add_edge(self.id(), edge_type, to.id())
    }

    fn add_incoming(&mut self, edge_type: usize, from: &BaseNode) {
        self.graph.add_edge(from.id(), edge_type, self.id())
    }

    fn has_outgoing(&self, edge_type: usize, to: &BaseNode) -> bool {
        self.graph.has_edge(self.id, edge_type, to.id)
    }

    fn has_incoming(&self, edge_type: usize, from: &BaseNode) -> bool {
        self.graph.has_edge(from.id, edge_type, self.id)
    }

    fn outgoing_nodes(&self, edge_type: usize) -> Vec<BaseNode> {
        self.graph
            .outgoing_nodes(self.id(), edge_type)
            .into_iter()
            .map(BaseNode::from)
            .collect()
    }

    fn incoming_nodes(&self, edge_type: usize) -> Vec<BaseNode> {
        self.graph
            .incoming_nodes(self.id(), edge_type)
            .into_iter()
            .map(BaseNode::from)
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::concepts::initialize_kb;
    use crate::graph::value_wrappers::{unwrap_weak, WeakValue};

    #[test]
    fn create_and_retrieve_node_id() {
        initialize_kb();
        let node1 = BaseNode::new();
        let node2 = BaseNode::new();
        assert_eq!(node1.id() + 1, node2.id());
    }

    #[test]
    fn from_node_id() {
        initialize_kb();
        let node = BaseNode::new();
        let node_copy = BaseNode::from(node.id());
        assert_eq!(node.id(), node_copy.id());
    }

    #[test]
    fn from_name() {
        initialize_kb();
        let mut node = BaseNode::new();
        node.set_internal_name("A".to_string());
        assert_eq!(BaseNode::try_from("A"), Ok(node));
        assert!(BaseNode::try_from("B").is_err());
    }

    #[test]
    fn create_and_retrieve_node_name() {
        initialize_kb();
        let mut node = BaseNode::new();
        node.set_internal_name("A".to_string());
        assert_eq!(node.internal_name(), Some(Rc::new("A".to_string())));
    }

    #[test]
    fn retrieve_node_value() {
        initialize_kb();
        let mut node = BaseNode::new();
        let v = Rc::new(5);
        node.set_value(Rc::new(WeakValue::new(&v)));
        assert_eq!(unwrap_weak::<i32>(node.value()), Some(v));
    }

    #[test]
    fn no_outgoing_nodes() {
        initialize_kb();
        let a = BaseNode::new();
        assert_eq!(a.outgoing_nodes(a.id()), Vec::new());
    }

    #[allow(clippy::many_single_char_names)]
    #[test]
    fn outgoing_nodes() {
        initialize_kb();
        let mut a = BaseNode::new();
        let b = BaseNode::new();
        let c = BaseNode::new();
        let d = BaseNode::new();
        let mut e = BaseNode::new();
        let edge_type1 = BaseNode::new();
        let edge_type2 = BaseNode::new();
        a.add_outgoing(edge_type1.id(), &b);
        a.add_outgoing(edge_type2.id(), &c);
        a.add_outgoing(edge_type1.id(), &d);
        e.add_outgoing(edge_type1.id(), &a);
        assert_eq!(a.outgoing_nodes(edge_type1.id()), vec![b, d]);
    }

    #[test]
    fn no_incoming_nodes() {
        initialize_kb();
        let a = BaseNode::new();
        assert_eq!(a.incoming_nodes(a.id()), Vec::new());
    }

    #[allow(clippy::many_single_char_names)]
    #[test]
    fn incoming_nodes() {
        initialize_kb();
        let mut a = BaseNode::new();
        let b = BaseNode::new();
        let c = BaseNode::new();
        let d = BaseNode::new();
        let mut e = BaseNode::new();
        let edge_type1 = BaseNode::new();
        let edge_type2 = BaseNode::new();
        a.add_incoming(edge_type1.id(), &b);
        a.add_incoming(edge_type2.id(), &c);
        a.add_incoming(edge_type1.id(), &d);
        e.add_incoming(edge_type1.id(), &a);
        assert_eq!(a.incoming_nodes(edge_type1.id()), vec![b, d]);
    }

    #[test]
    fn test_has_outgoing() {
        initialize_kb();
        let mut a = BaseNode::new();
        let b = BaseNode::new();
        let edge_type1 = BaseNode::new();
        let edge_type2 = BaseNode::new();
        a.add_outgoing(edge_type1.id(), &b);
        assert!(a.has_outgoing(edge_type1.id(), &b));
        assert!(!a.has_outgoing(edge_type2.id(), &b));
        assert!(!b.has_outgoing(edge_type1.id(), &a));
    }

    #[test]
    fn test_has_incoming() {
        initialize_kb();
        let mut a = BaseNode::new();
        let b = BaseNode::new();
        let edge_type1 = BaseNode::new();
        let edge_type2 = BaseNode::new();
        a.add_incoming(edge_type1.id(), &b);
        assert!(a.has_incoming(edge_type1.id(), &b));
        assert!(!a.has_incoming(edge_type2.id(), &b));
        assert!(!b.has_incoming(edge_type1.id(), &a));
    }
}