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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! This module implements an Abstract Syntax Tree for Dot graphs. The main
//! structure is `Graph`, which corresponds to the `graph` non-terminal in the
//! grammar.

use pest::iterators::Pair;
use pest::Parser;

use std::iter::FromIterator;
use std::marker::PhantomData;

mod parser {
    use pest_derive::Parser;

    #[derive(Parser)]
    #[grammar = "parser/dot.pest"]
    pub struct DotParser;
}

use self::parser::DotParser;
use self::parser::Rule;

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
/// This structure is an AST for the DOT graph language.  The generic `A`
/// denotes the type of attributes. By default (and when parsing), it is
/// `(&'a str, &'a str)`, i.e. two strings, one for the key and one for the
/// value of the attribute. The library provides functions to map from one type
/// to an other.
pub struct Graph<'a, A = (&'a str, &'a str)> {
    /// 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 statements that describe the graph.
    pub stmts: StmtList<'a, A>,
}

impl<'a> Graph<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut inner = p.into_inner();
        let mut strict = false;
        let mut name = None;
        let mut pair = inner.next().unwrap();
        if let Rule::strict = pair.as_rule() {
            strict = true;
            pair = inner.next().unwrap();
        }
        let is_digraph = match pair.as_rule() {
            Rule::digraph => true,
            Rule::graph => false,
            _ => return Err(()),
        };
        pair = inner.next().unwrap();
        if let Rule::ident = pair.as_rule() {
            name = Some(pair.as_str());
            pair = inner.next().unwrap();
        }
        let stmts = StmtList::parse(pair).unwrap();
        Ok(Graph {
            strict,
            is_digraph,
            name,
            stmts,
        })
    }

    /// Read a graph from a DOT file.
    pub fn read_dot(file: &'a str) -> Result<Self, pest::error::Error<Rule>> {
        DotParser::parse(Rule::dotgraph, file).map(|mut p| Graph::parse(p.next().unwrap()).unwrap())
    }
}

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_stmts: StmtList<'a, B> = self
            .stmts
            .into_iter()
            .map(|stmt| stmt.filter_map_attr(&f))
            .collect();
        Graph {
            strict: self.strict,
            is_digraph: self.is_digraph,
            name: self.name,
            stmts: new_stmts,
        }
    }
}

/// A list of statements. This corresponds to the `stmt_list` non-terminal of the
/// grammar.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct StmtList<'a, A = (&'a str, &'a str)> {
    /// The list of statements.
    pub stmts: Vec<Stmt<'a, A>>,
}

impl<'a> StmtList<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut stmts = Vec::new();
        let mut inner = p.into_inner();
        match inner.next() {
            None => {}
            Some(stmt) => {
                let tail = inner.next().unwrap();
                let mut tail = StmtList::parse(tail).unwrap();
                let stmt = Stmt::parse(stmt).unwrap();
                stmts.push(stmt);
                stmts.append(&mut tail.stmts);
            }
        }
        Ok(StmtList { stmts })
    }
}

impl<'a, A> IntoIterator for StmtList<'a, A> {
    type Item = Stmt<'a, A>;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.stmts.into_iter()
    }
}

impl<'a, 'b, A> IntoIterator for &'b StmtList<'a, A> {
    type Item = &'b Stmt<'a, A>;
    type IntoIter = std::slice::Iter<'b, Stmt<'a, A>>;

    fn into_iter(self) -> Self::IntoIter {
        self.stmts.iter()
    }
}

impl<'a, A> FromIterator<Stmt<'a, A>> for StmtList<'a, A> {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = Stmt<'a, A>>,
    {
        Self {
            stmts: iter.into_iter().collect(),
        }
    }
}

/// A statement of the graph. This corresponds to the `stmt` non-terminal of the
/// grammar.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Stmt<'a, A = (&'a str, &'a str)> {
    /// A node statement.
    NodeStmt(NodeStmt<'a, A>),
    /// An edge statement.
    EdgeStmt(EdgeStmt<'a, A>),
    /// An attribute statement.
    AttrStmt(AttrStmt<'a, A>),
    /// An alias statement.
    IDEq(&'a str, &'a str),
}

impl<'a> Stmt<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let inner = p.into_inner().next().unwrap();
        match inner.as_rule() {
            Rule::node_stmt => NodeStmt::parse(inner).map(|p| Stmt::NodeStmt(p)),
            Rule::edge_stmt => EdgeStmt::parse(inner).map(|p| Stmt::EdgeStmt(p)),
            Rule::attr_stmt => AttrStmt::parse(inner).map(|p| Stmt::AttrStmt(p)),
            Rule::id_eq => {
                let mut inners = inner.into_inner();
                let id1 = inners.next().unwrap().as_str();
                let id2 = inners.next().unwrap().as_str();
                Ok(Stmt::IDEq(id1, id2))
            }
            other => {
                println!("{:#?}", other);
                Err(())
            }
        }
    }
}

impl<'a, A> Stmt<'a, A> {
    /// Convert a statement with attributes of type `A` into a statement with
    /// attributes of type `B`.
    fn filter_map_attr<B>(self, f: &dyn Fn(A) -> Option<B>) -> Stmt<'a, B> {
        match self {
            Stmt::NodeStmt(node) => Stmt::NodeStmt(node.filter_map_attr(f)),
            Stmt::EdgeStmt(edge) => Stmt::EdgeStmt(edge.filter_map_attr(f)),
            Stmt::AttrStmt(attr) => Stmt::AttrStmt(attr.filter_map_attr(f)),
            Stmt::IDEq(a, b) => Stmt::IDEq(a, b),
        }
    }

    /// Returns true if `self` is a `NodeStmt` variant.
    pub fn is_node_stmt(&self) -> bool {
        if let Stmt::NodeStmt(_) = self {
            true
        } else {
            false
        }
    }

    /// Returns `Some(&node)` if `&self` if a `&NodeStmt(node)`, and `None`
    /// otherwise.
    pub fn get_node_ref(&self) -> Option<&NodeStmt<A>> {
        if let Stmt::NodeStmt(node) = self {
            Some(node)
        } else {
            None
        }
    }

    /// Returns `Some(node)` if `self` if a `NodeStmt(node)`, and `None`
    /// otherwise.
    pub fn get_node(self) -> Option<NodeStmt<'a, A>> {
        if let Stmt::NodeStmt(node) = self {
            Some(node)
        } else {
            None
        }
    }

    /// Returns true if `self` is a `EdgeStmt` variant.
    pub fn is_edge_stmt(&self) -> bool {
        if let Stmt::EdgeStmt(_) = self {
            true
        } else {
            false
        }
    }

    /// Returns `Some(&edge)` if `&self` if a `&EdgeStmt(edge)`, and `None`
    /// otherwise.
    pub fn get_edge_ref(&self) -> Option<&EdgeStmt<A>> {
        if let Stmt::EdgeStmt(edge) = self {
            Some(edge)
        } else {
            None
        }
    }

    /// Returns `Some(edge)` if `self` if a `EdgeStmt(edge)`, and `None`
    /// otherwise.
    pub fn get_edge(self) -> Option<EdgeStmt<'a, A>> {
        if let Stmt::EdgeStmt(edge) = self {
            Some(edge)
        } else {
            None
        }
    }

    /// Returns true if `self` is a `AttrStmt` variant.
    pub fn is_attr_stmt(&self) -> bool {
        if let Stmt::AttrStmt(_) = self {
            true
        } else {
            false
        }
    }

    /// Returns `Some(&attr)` if `&self` if a `&AttrStmt(attr)`, and `None`
    /// otherwise.
    pub fn get_attr_ref(&self) -> Option<&AttrStmt<A>> {
        if let Stmt::AttrStmt(attr) = self {
            Some(attr)
        } else {
            None
        }
    }

    /// Returns `Some(attr)` if `self` if a `AttrStmt(attr)`, and `None`
    /// otherwise.
    pub fn get_attr(self) -> Option<AttrStmt<'a, A>> {
        if let Stmt::AttrStmt(attr) = self {
            Some(attr)
        } else {
            None
        }
    }

    /// Returns true if `self` is a `IDEq` variant.
    pub fn is_ideq_stmt(&self) -> bool {
        if let Stmt::IDEq(..) = self {
            true
        } else {
            false
        }
    }

    /// Returns `Some((&id1, &id2))` if `&self` if a `&IDEq(id1, id2)` and `None`
    /// otherwise.
    pub fn get_ideq_ref(&self) -> Option<(&str, &str)> {
        if let Stmt::IDEq(id1, id2) = self {
            Some((id1, id2))
        } else {
            None
        }
    }
}

/// An attribute statement. This corresponds to the rule `attr_stmt`
/// non-terminal of the grammar.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum AttrStmt<'a, A = (&'a str, &'a str)> {
    /// An `AttrStmt` on the whole graph.
    Graph(AttrList<'a, A>),
    /// An `AttrStmt` on each nodes of the graph.
    Node(AttrList<'a, A>),
    /// An `AttrStmt` on each edges of the graph.
    Edge(AttrList<'a, A>),
}

impl<'a> AttrStmt<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut inners = p.into_inner();
        let kind = inners.next().unwrap().as_rule();
        let attr = AttrList::parse(inners.next().unwrap()).unwrap();
        match kind {
            Rule::graph => Ok(AttrStmt::Graph(attr)),
            Rule::node => Ok(AttrStmt::Node(attr)),
            Rule::edge => Ok(AttrStmt::Edge(attr)),
            _ => Err(()),
        }
    }
}

impl<'a, A> AttrStmt<'a, A> {
    fn filter_map_attr<B>(self, f: &dyn Fn(A) -> Option<B>) -> AttrStmt<'a, B> {
        match self {
            AttrStmt::Graph(attr) => AttrStmt::Graph(attr.filter_map_attr(f)),
            AttrStmt::Node(attr) => AttrStmt::Node(attr.filter_map_attr(f)),
            AttrStmt::Edge(attr) => AttrStmt::Edge(attr.filter_map_attr(f)),
        }
    }
}

/// A list of `AList`s, i.e. a list of list of attributes. This (strange)
/// indirection is induced by the grammar. This structure corresponds to the
/// `attr_list` non-terminal of the grammar.
///
/// Notice methods `flatten` and `flatten_ref` to remove the indirection.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AttrList<'a, A = (&'a str, &'a str)> {
    /// The list of `AList`s.
    pub elems: Vec<AList<'a, A>>,
}

impl<'a> AttrList<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut v: Vec<AList<'a>> = Vec::new();
        let mut inners = p.into_inner();
        let alist = AList::parse(inners.next().unwrap()).unwrap();
        let mut tail = inners
            .next()
            .map(|p| {
                AttrList::parse(p)
                    .map(|alist| alist.elems)
                    .unwrap_or(Vec::new())
            })
            .unwrap_or(Vec::new());
        v.push(alist);
        v.append(&mut tail);

        Ok(AttrList { elems: v })
    }
}

impl<'a, A> AttrList<'a, A> {
    fn filter_map_attr<B>(self, f: &dyn Fn(A) -> Option<B>) -> AttrList<'a, B> {
        AttrList {
            elems: self
                .into_iter()
                .map(|alist| alist.filter_map_attr(f))
                .collect(),
        }
    }

    /// Flatten the nested `AList`s: returns a single `AList` that contains all
    /// attributes contained in the `AttrList`.
    pub fn flatten(self) -> AList<'a, A> {
        self.into()
    }

    /// Flatten the nested `AList`s: returns a single `AList` that contains all
    /// attributes contained in the `AttrList`.
    pub fn flatten_ref<'b>(&'b self) -> AList<'a, &'b A> {
        self.into()
    }
}

impl<'a, A> FromIterator<AList<'a, A>> for AttrList<'a, A> {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = AList<'a, A>>,
    {
        Self {
            elems: iter.into_iter().map(|u| u.into_iter().collect()).collect(),
        }
    }
}

impl<'a, A> IntoIterator for AttrList<'a, A> {
    type Item = AList<'a, A>;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.elems.into_iter()
    }
}

impl<'a, 'b, A> IntoIterator for &'b AttrList<'a, A> {
    type Item = &'b AList<'a, A>;
    type IntoIter = std::slice::Iter<'b, AList<'a, A>>;

    fn into_iter(self) -> Self::IntoIter {
        (&self.elems).into_iter()
    }
}

/// A list of attributes. This corresponds to the `a_list` non-terminal of the
/// grammar.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct AList<'a, A = (&'a str, &'a str)> {
    /// The attributes in the list.
    pub elems: Vec<A>,
    _p: PhantomData<&'a ()>,
}

impl<'a> AList<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut v = Vec::new();
        let mut inners = p.into_inner();
        let id1 = inners.next().unwrap().as_str();
        let id2 = inners.next().unwrap().as_str();
        let mut tail = inners
            .next()
            .map(|p| {
                AList::parse(p)
                    .map(|alist| alist.elems)
                    .unwrap_or(Vec::new())
            })
            .unwrap_or(Vec::new());
        v.push((id1, id2));
        v.append(&mut tail);

        Ok(AList {
            elems: v,
            _p: PhantomData,
        })
    }
}

impl<'a, A> AList<'a, A> {
    pub(in crate) fn filter_map_attr<B>(self, f: &dyn Fn(A) -> Option<B>) -> AList<'a, B> {
        AList {
            elems: self.into_iter().filter_map(f).collect(),
            _p: PhantomData,
        }
    }

    pub(in crate) fn empty() -> Self {
        AList {
            elems: Vec::new(),
            _p: PhantomData,
        }
    }
}

impl<'a, A> FromIterator<A> for AList<'a, A> {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = A>,
    {
        Self {
            elems: iter.into_iter().collect(),
            _p: PhantomData,
        }
    }
}

impl<'a, A> IntoIterator for AList<'a, A> {
    type Item = A;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.elems.into_iter()
    }
}

impl<'a, 'b, A> IntoIterator for &'b AList<'a, A> {
    type Item = &'b A;
    type IntoIter = std::slice::Iter<'b, A>;

    fn into_iter(self) -> Self::IntoIter {
        (&self.elems).into_iter()
    }
}

impl<'a, A> From<AttrList<'a, A>> for AList<'a, A> {
    fn from(attr: AttrList<'a, A>) -> Self {
        attr.into_iter().flatten().collect()
    }
}

impl<'a, 'b, A> From<&'b AttrList<'a, A>> for AList<'a, &'b A> {
    fn from(attr: &'b AttrList<'a, A>) -> Self {
        attr.into_iter().flatten().collect()
    }
}

/// The description of an edge. This corresponds to the `edge_stmt` non-terminal
/// of the grammar.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct EdgeStmt<'a, A = (&'a str, &'a str)> {
    /// The origin of the edge.
    pub node: NodeID<'a>,
    /// The destination of the edge.
    pub next: EdgeRHS<'a>,
    /// The attributes of the edge.
    pub attr: Option<AttrList<'a, A>>,
}

impl<'a> EdgeStmt<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut inners = p.into_inner();
        let node = inners.next().map(|p| NodeID::parse(p).unwrap()).unwrap();
        let next = inners.next().map(|p| EdgeRHS::parse(p).unwrap()).unwrap();
        let attr = inners.next().map(|p| AttrList::parse(p).unwrap());
        Ok(EdgeStmt { node, next, attr })
    }
}

impl<'a, A> EdgeStmt<'a, A> {
    fn filter_map_attr<B>(self, f: &dyn Fn(A) -> Option<B>) -> EdgeStmt<'a, B> {
        EdgeStmt {
            node: self.node,
            next: self.next,
            attr: self.attr.map(|a| a.filter_map_attr(f)),
        }
    }
}

/// The Right hand side of an edge description. This corresponds to the
/// `EdgeRHS` non-terminal of the grammar.
/// Notice that the grammar allows multiple EdgeRHS in sequence, to chain edges:
/// `A -> B -> C`.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct EdgeRHS<'a> {
    /// The identifier of the destination of the edge.
    pub node: NodeID<'a>,
    /// A possible chained RHS.
    pub next: Option<Box<EdgeRHS<'a>>>,
}

impl<'a> EdgeRHS<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut inners = p.into_inner();
        let node = inners.next().map(|p| NodeID::parse(p).unwrap()).unwrap();
        let next = inners.next().map(|p| Box::new(EdgeRHS::parse(p).unwrap()));
        Ok(EdgeRHS { node, next })
    }
}

/// This structure corresponds to the `node_stmt` non-terminal of the grammar.
/// It is basically a node identifier attached to some attributes.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct NodeStmt<'a, A = (&'a str, &'a str)> {
    /// The identifier of the node.
    pub node: NodeID<'a>,
    /// The possible list of attributes.
    pub attr: Option<AttrList<'a, A>>,
}

impl<'a> NodeStmt<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut inners = p.into_inner();
        let node = inners.next().map(|p| NodeID::parse(p).unwrap()).unwrap();
        let attr = inners.next().map(|p| AttrList::parse(p).unwrap());
        Ok(NodeStmt { node, attr })
    }
}

impl<'a, A> NodeStmt<'a, A> {
    fn filter_map_attr<B>(self, f: &dyn Fn(A) -> Option<B>) -> NodeStmt<'a, B> {
        NodeStmt {
            node: self.node,
            attr: self.attr.map(|a| a.filter_map_attr(f)),
        }
    }

    /// Get the name of the `NodeStmt`, i.e. the identifier of the
    /// `NodeID` contained in the `NodeStmt`.
    pub fn name(&self) -> &str {
        self.node.id
    }
}

/// This structure corresponds to the `node_id` non-terminal of the grammar.
/// If contains the identifier of the node, and possibly a port.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct NodeID<'a> {
    /// The identifier of the node.
    pub id: &'a str,
    /// The port of the node, if any.
    pub port: Option<Port<'a>>,
}

impl<'a> NodeID<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut inners = p.into_inner();
        let id = inners.next().unwrap().as_str();
        let port = inners.next().map(|p| Port::parse(p).unwrap());
        Ok(NodeID { id, port })
    }
}

/// This enum corresponds to the `port` non-terminal of the grammar.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
pub enum Port<'a> {
    /// The variant in which an ID is given, and possibly a compass point.
    ID(&'a str, Option<CompassPt>),
    /// The variant in which only a compass point is given.
    Compass(CompassPt),
}

impl<'a> Port<'a> {
    fn parse(p: Pair<'a, Rule>) -> Result<Self, ()> {
        let mut inners = p.into_inner();
        let inner = inners.next().unwrap();
        match inner.as_rule() {
            Rule::compass_pt => Ok(Port::Compass(CompassPt::parse(inner).unwrap())),
            Rule::ident => {
                let comp_pair = inners.next();
                let opt_comp = comp_pair.map(|p| CompassPt::parse(p).unwrap());
                Ok(Port::ID(inner.as_str(), opt_comp))
            }
            _ => Err(()),
        }
    }
}

/// An enum that corresponds to the `compass_pt` non-terminal of the grammar.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
pub enum CompassPt {
    /// A North orientation
    N,
    /// A North-East orientation
    NE,
    /// An East orientation
    E,
    /// A South-East orientation
    SE,
    /// A South orientation
    S,
    /// A South-West orientation
    SW,
    /// A West orientation
    W,
    /// A North-West orientation
    NW,
    /// A Central orientation
    C,
    /// An unspecified orientation
    Underscore,
}

impl CompassPt {
    fn parse(p: Pair<Rule>) -> Result<Self, ()> {
        match p.into_inner().next().unwrap().as_rule() {
            Rule::n => Ok(CompassPt::N),
            Rule::ne => Ok(CompassPt::NE),
            Rule::e => Ok(CompassPt::E),
            Rule::se => Ok(CompassPt::SE),
            Rule::s => Ok(CompassPt::S),
            Rule::sw => Ok(CompassPt::SW),
            Rule::w => Ok(CompassPt::W),
            Rule::nw => Ok(CompassPt::NW),
            Rule::c => Ok(CompassPt::C),
            Rule::underscore => Ok(CompassPt::Underscore),
            _ => Err(()),
        }
    }
}