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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
//! This modules implement "Canonical graphs". This is motivated by the fact
//! that graphs parsed naively may be difficult to work with, from a programming
//! viewpoint: typically, `attr_list` in the grammar are defined as
//! "[ID = ID, ...][ID = ID, ...]". Therefore, we may want to flatten such
//! structures. This is done in the `canonical` module.
//!
//! The main structure of the module is `Graph`, which implements such a flatten
//! graph.

use std::collections::HashMap;
use std::ops::AddAssign;

use crate::ast::{
    AList, AttrStmt as AstAttrStmt, EdgeStmt, Graph as AstGraph, NodeID, NodeStmt, Port, Stmt,
};

/// A `Graph` is a structure that can be created from a regular
/// `Graph`, but that is more friendly to work with. For instance, in a `Graph`,
/// attributes are most often given as a list of list of `Attr`, while in a
/// `Graph`, the lists are flatten.
#[derive(Debug)]
pub struct Graph<'a, A> {
    /// Specifies if the `Graph` is strict or not. A "strict" graph must not
    /// contain the same edge multiple times. Notice that, for undirected edge,
    /// an edge from `A` to `B` and an edge from `B` to `A` are equals.
    pub strict: bool,
    /// Specifies if the `Graph` is directed.
    pub is_digraph: bool,
    /// The name of the `Graph`, if any.
    pub name: Option<&'a str>,
    /// The global attributes of the graph.
    pub attr: Vec<AttrStmt<A>>,
    /// The nodes of the graph.
    pub nodes: NodeSet<'a, A>,
    /// The edges of the graph.
    pub edges: EdgeSet<'a, A>,
}

impl<'a, A> Graph<'a, A> {
    /// Filter and map attributes. The main intended usage of this function is
    /// to convert attributes as `&'a str` into an enum, e.g.
    /// to convert `["label"="whatever", "color"="foo"]` into
    /// `[Attr::Label(whatever), Attr::Color(foo)]`.
    ///
    /// To take into account non-standard attributes, the `Attr` enum has to be
    /// provided by the user.
    pub fn filter_map<F, B>(self, f: F) -> Graph<'a, B>
    where
        F: Fn(A) -> Option<B>,
    {
        let new_attr = self
            .attr
            .into_iter()
            .filter_map(|attr_stmt| attr_stmt.filter_map(&f))
            .collect();
        let new_nodes = self.nodes.map(&f);
        let new_edges = self.edges.map(&f);

        Graph {
            strict: self.strict,
            is_digraph: self.is_digraph,
            name: self.name,
            attr: new_attr,
            nodes: new_nodes,
            edges: new_edges,
        }
    }
}

impl<'a, A> From<AstGraph<'a, A>> for Graph<'a, A>
where
    A: Clone,
{
    fn from(graph: AstGraph<'a, A>) -> Self {
        let mut attrs: Vec<AstAttrStmt<_>> = Vec::new();
        let mut nodes = Vec::new();
        let mut edges = Vec::new();

        for stmt in graph.stmts {
            match stmt {
                Stmt::NodeStmt(node) => nodes.push(node),
                Stmt::EdgeStmt(edge) => edges.push(edge),
                Stmt::AttrStmt(attr) => attrs.push(attr),
                _ => unimplemented!(),
            }
        }

        let mut nodes: NodeSet<A> = nodes.into();
        let edges: EdgeSet<A> = (edges, &mut nodes).into();
        let attr: Vec<AttrStmt<A>> = attrs
            .into_iter()
            .map(|stmt: AstAttrStmt<_>| {
                let attr_l: Vec<AttrStmt<A>> = stmt.into();
                attr_l
            })
            .flatten()
            .collect();

        Graph {
            strict: graph.strict,
            is_digraph: graph.is_digraph,
            name: graph.name,
            attr,
            nodes,
            edges,
        }
    }
}

/// A single node of the graph.
#[derive(Debug)]
pub struct Node<'a, A> {
    /// The identifier of the node.
    pub id: &'a str,
    /// The port of the node.
    pub port: Option<Port<'a>>,
    /// The attributes that apply to this node.
    pub attr: AList<'a, A>,
}

impl<'a, A> From<NodeStmt<'a, A>> for Node<'a, A> {
    fn from(stmt: NodeStmt<'a, A>) -> Self {
        Node {
            id: stmt.node.id,
            port: stmt.node.port,
            attr: stmt.attr.map(|list| list.into()).unwrap_or(AList::empty()),
        }
    }
}

impl<'a, A> From<&NodeID<'a>> for Node<'a, A> {
    fn from(node: &NodeID<'a>) -> Self {
        Node {
            id: node.id,
            port: node.port,
            attr: AList::empty(),
        }
    }
}

impl<'a, A> Node<'a, A> {
    fn map<F, B>(self, f: F) -> Node<'a, B>
    where
        F: Fn(A) -> Option<B>,
    {
        Node {
            id: self.id,
            port: self.port,
            attr: self.attr.filter_map_attr(&f),
        }
    }
}

/// A set of `Node`s.
#[derive(Debug)]
pub struct NodeSet<'a, A> {
    /// The set of nodes in the NodeSet. They are indexed by their identifier.
    /// Note that this field being public is experimental.
    pub set: HashMap<&'a str, Node<'a, A>>,
}

impl<'a, A> NodeSet<'a, A> {
    fn insert_if_absent<'b>(&'b mut self, id: &'a str, or: Node<'a, A>) {
        // TODO: clarify what happens if id != or.id
        if let None = self.set.get(id) {
            self.set.insert(id, or);
        }
    }

    fn map<F, B>(self, f: F) -> NodeSet<'a, B>
    where
        F: Fn(A) -> Option<B>,
    {
        let new_set = self
            .set
            .into_iter()
            .map(|(name, node)| (name, node.map(&f)))
            .collect();
        NodeSet { set: new_set }
    }
}

impl<'a, A, I> From<I> for NodeSet<'a, A>
where
    I: IntoIterator<Item = NodeStmt<'a, A>>,
{
    fn from(nodes: I) -> Self {
        let set: HashMap<_, _> = nodes
            .into_iter()
            .map(|node| (node.node.id, node.into()))
            .collect();
        NodeSet { set }
    }
}

/// A set of `Edge`s.
#[derive(Debug)]
pub struct EdgeSet<'a, A> {
    /// `Edge`s of the set.
    pub set: Vec<Edge<'a, A>>,
}

impl<'a, A> EdgeSet<'a, A> {
    fn empty() -> Self {
        Self { set: Vec::new() }
    }

    fn map<F, B>(self, f: F) -> EdgeSet<'a, B>
    where
        F: Fn(A) -> Option<B>,
    {
        let new_set = self.set.into_iter().map(|edge| edge.map(&f)).collect();
        EdgeSet { set: new_set }
    }
}

impl<'a, A> AddAssign for EdgeSet<'a, A> {
    fn add_assign(&mut self, mut rhs: Self) {
        self.set.append(&mut rhs.set)
    }
}

/// A single edge of the graph.
#[derive(Debug)]
pub struct Edge<'a, A> {
    /// The name of the origin of the edge.
    pub from: &'a str,
    /// The name of the destination of the edge.
    pub to: &'a str,
    /// A list of attributes that apply to this specific edge.
    pub attr: AList<'a, A>,
}

impl<'a, A> Edge<'a, A> {
    fn map<F, B>(self, f: F) -> Edge<'a, B>
    where
        F: Fn(A) -> Option<B>,
    {
        Edge {
            from: self.from,
            to: self.to,
            attr: self.attr.filter_map_attr(&f),
        }
    }
}

impl<'a, A> From<(EdgeStmt<'a, A>, &mut NodeSet<'a, A>)> for EdgeSet<'a, A>
where
    A: Clone,
{
    fn from(tuple: (EdgeStmt<'a, A>, &mut NodeSet<'a, A>)) -> Self {
        let (stmt, nodes) = tuple;
        let mut from = stmt.node;
        let mut rhs = stmt.next;
        let mut set = Vec::new();
        let attr = stmt.attr.map(|list| list.into()).unwrap_or(AList::empty());

        loop {
            let to = rhs.node;
            let from_id = from.id;
            let to_id = to.id;

            nodes.insert_if_absent(from.id, (&from).into());
            nodes.insert_if_absent(to.id, (&to).into());

            let edge = Edge {
                from: from_id,
                to: to_id,
                attr: attr.clone(),
            };

            set.push(edge);

            if let None = rhs.next {
                return EdgeSet { set };
            }
            from = to;
            rhs = *(rhs.next.unwrap());
        }
    }
}

impl<'a, A, I> From<(I, &mut NodeSet<'a, A>)> for EdgeSet<'a, A>
where
    I: IntoIterator<Item = EdgeStmt<'a, A>>,
    A: Clone,
{
    fn from(tuple: (I, &mut NodeSet<'a, A>)) -> Self {
        let (stmts, nodes) = tuple;
        let mut set = EdgeSet::empty();
        for stmt in stmts {
            set += (stmt, &mut *nodes).into();
        }
        set
    }
}

#[derive(Debug)]
/// An `AttrStmt`, i.e. a statement that applies to either the whole graph, all
/// edges, or all nodes. Note that, in a canonical graph, `AttrStmt`s contain a
/// single statement.
pub enum AttrStmt<A> {
    /// An `AttrStmt` that applies to the whole graph.
    Graph(A),
    /// An `AttrStmt` that applies to all nodes of the graph.
    Node(A),
    /// An `AttrStmt` that applies to all edges of the graph.
    Edge(A),
}

impl<A> AttrStmt<A> {
    fn filter_map<F, B>(self, f: F) -> Option<AttrStmt<B>>
    where
        F: Fn(A) -> Option<B>,
    {
        match self {
            AttrStmt::Graph(a) => {
                if let Some(b) = f(a) {
                    Some(AttrStmt::Graph(b))
                } else {
                    None
                }
            }
            AttrStmt::Node(a) => {
                if let Some(b) = f(a) {
                    Some(AttrStmt::Node(b))
                } else {
                    None
                }
            }
            AttrStmt::Edge(a) => {
                if let Some(b) = f(a) {
                    Some(AttrStmt::Edge(b))
                } else {
                    None
                }
            }
        }
    }
}

impl<'a, A> Into<Vec<AttrStmt<A>>> for AstAttrStmt<'a, A> {
    fn into(self) -> Vec<AttrStmt<A>> {
        match self {
            AstAttrStmt::Graph(list) => {
                let alist: AList<'a, A> = list.into();
                alist
                    .into_iter()
                    .map(|attr| AttrStmt::Graph(attr.into()))
                    .collect()
            }
            AstAttrStmt::Node(list) => {
                let alist: AList<'a, A> = list.into();
                alist
                    .into_iter()
                    .map(|attr| AttrStmt::Node(attr.into()))
                    .collect()
            }
            AstAttrStmt::Edge(list) => {
                let alist: AList<'a, A> = list.into();
                alist
                    .into_iter()
                    .map(|attr| AttrStmt::Edge(attr.into()))
                    .collect()
            }
        }
    }
}