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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
#![feature(slice_partition_dedup)]

#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate lalrpop_util;

lalrpop_mod!(
    #[allow(clippy::all)]
    pub ascesis_parser
);

lalrpop_mod!(
    #[allow(clippy::all)]
    pub bnf_parser
);

pub mod bnf;
pub mod grammar;
pub mod sentence;

use std::{
    cmp, fmt,
    collections::{BTreeSet, BTreeMap},
    convert::{TryFrom, TryInto},
    iter::FromIterator,
    str::FromStr,
    error::Error,
};
use regex::Regex;
use enquote::unquote;
use crate::ascesis_parser::{
    CesFileBlockParser, ImmediateDefParser, CesInstanceParser, CapBlockParser, MulBlockParser,
    InhBlockParser, RexParser, ThinArrowRuleParser, FatArrowRuleParser, PolynomialParser,
};

pub type ParsingError = lalrpop_util::ParseError<usize, String, String>;
pub type ParsingResult<T> = Result<T, ParsingError>;

#[derive(Clone, Debug)]
pub enum AscesisError {
    ParsingError(ParsingError),
    UnknownAxiom(String),
}

impl Error for AscesisError {
    fn description(&self) -> &str {
        use AscesisError::*;

        match self {
            ParsingError(_) => "ascesis parsing error",
            UnknownAxiom(_) => "unknown axiom",
        }
    }
}

impl fmt::Display for AscesisError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use AscesisError::*;

        match self {
            ParsingError(err) => {
                let message = format!("{}", err);
                let mut lines = message.lines();

                if let Some(line) = lines.next() {
                    writeln!(f, "{}", line)?;
                }

                for line in lines {
                    writeln!(f, "\t{}", line)?;
                }

                Ok(())
            }
            UnknownAxiom(symbol) => write!(f, "Unknown axiom '{}'", symbol),
        }
    }
}

impl From<ParsingError> for AscesisError {
    fn from(err: ParsingError) -> Self {
        AscesisError::ParsingError(err)
    }
}

#[derive(Clone, Debug)]
pub struct Axiom(String);

impl Axiom {
    pub fn from_known_symbol<S: AsRef<str>>(symbol: S) -> Option<Self> {
        let symbol = symbol.as_ref();

        match symbol {
            "CesFileBlock" | "ImmediateDef" | "CesInstance" | "CapBlock" | "MulBlock"
            | "InhBlock" | "Rex" | "ThinArrowRule" | "FatArrowRule" | "Polynomial" => {
                Some(Axiom(symbol.to_owned()))
            }
            _ => None,
        }
    }

    pub fn guess_from_spec<S: AsRef<str>>(spec: S) -> Self {
        lazy_static! {
            static ref IMM_RE: Regex = Regex::new(r"^ces\s+[[:alpha:]][[:word:]]*\s*\{").unwrap();
            static ref CAP_RE: Regex = Regex::new(r"^cap\s*\{").unwrap();
            static ref MUL_RE: Regex = Regex::new(r"^mul\s*\{").unwrap();
            static ref INH_RE: Regex = Regex::new(r"^inh\s*\{").unwrap();
            static ref TIN_RE: Regex = Regex::new(r"^[[:alpha:]][[:word:]]*\s*!\s*\(").unwrap();
            static ref IIN_RE: Regex =
                Regex::new(r"^[[:alpha:]][[:word:]]*\s*\(\s*\)\s*$").unwrap();
            static ref REX_RE: Regex = Regex::new(r"(\{|,|!|\(\s*\))").unwrap();
            static ref TAR_RE: Regex = Regex::new(r"(->|<-)").unwrap();
            static ref FAR_RE: Regex = Regex::new(r"(=>|<=)").unwrap();
        }

        let spec = spec.as_ref().trim();

        if IMM_RE.is_match(spec) {
            Axiom("ImmediateDef".to_owned())
        } else if CAP_RE.is_match(spec) {
            Axiom("CapBlock".to_owned())
        } else if MUL_RE.is_match(spec) {
            Axiom("MulBlock".to_owned())
        } else if INH_RE.is_match(spec) {
            Axiom("InhBlock".to_owned())
        } else if TIN_RE.is_match(spec) || IIN_RE.is_match(spec) {
            Axiom("CesInstance".to_owned())
        } else if REX_RE.is_match(spec) {
            Axiom("Rex".to_owned())
        } else if TAR_RE.is_match(spec) {
            Axiom("ThinArrowRule".to_owned())
        } else if FAR_RE.is_match(spec) {
            Axiom("FatArrowRule".to_owned())
        } else {
            // FIXME into tests: `a(b)` is a Polynomial, `a()`,
            // `a(b,)` are instantiations.
            Axiom("Polynomial".to_owned())
        }
    }

    pub fn symbol(&self) -> &str {
        self.0.as_str()
    }

    pub fn parse<S: AsRef<str>>(&self, spec: S) -> Result<Box<dyn FromSpec>, AscesisError> {
        macro_rules! from_spec_as {
            ($typ:ty, $spec:expr) => {{
                let object: $typ = $spec.parse()?;
                Ok(Box::new(object))
            }};
        }

        let spec = spec.as_ref();

        match self.0.as_str() {
            "CesFileBlock" => from_spec_as!(CesFileBlock, spec),
            "ImmediateDef" => from_spec_as!(ImmediateDef, spec),
            "CesInstance" => from_spec_as!(CesInstance, spec),
            "CapBlock" => from_spec_as!(CapacityBlock, spec),
            "MulBlock" => from_spec_as!(MultiplierBlock, spec),
            "InhBlock" => from_spec_as!(InhibitorBlock, spec),
            "Rex" => from_spec_as!(Rex, spec),
            "ThinArrowRule" => from_spec_as!(ThinArrowRule, spec),
            "FatArrowRule" => from_spec_as!(FatArrowRule, spec),
            "Polynomial" => from_spec_as!(Polynomial, spec),
            _ => Err(AscesisError::UnknownAxiom(self.0.clone())),
        }
    }
}

pub trait FromSpec: fmt::Debug {
    fn from_spec<S>(spec: S) -> ParsingResult<Self>
    where
        S: AsRef<str>,
        Self: Sized;
}

macro_rules! impl_from_str_for {
    ($nt:ty) => {
        impl FromStr for $nt {
            type Err = ParsingError;

            fn from_str(s: &str) -> ParsingResult<Self> {
                Self::from_spec(s)
            }
        }
    };
}

impl_from_str_for!(CesFileBlock);
impl_from_str_for!(ImmediateDef);
impl_from_str_for!(CesInstance);
impl_from_str_for!(CapacityBlock);
impl_from_str_for!(MultiplierBlock);
impl_from_str_for!(InhibitorBlock);
impl_from_str_for!(Rex);
impl_from_str_for!(ThinArrowRule);
impl_from_str_for!(FatArrowRule);
impl_from_str_for!(Polynomial);

#[derive(Debug)]
pub enum CesFileBlock {
    Imm(ImmediateDef),
    Cap(CapacityBlock),
    Mul(MultiplierBlock),
    Inh(InhibitorBlock),
}

impl From<ImmediateDef> for CesFileBlock {
    fn from(imm: ImmediateDef) -> Self {
        CesFileBlock::Imm(imm)
    }
}

impl From<CapacityBlock> for CesFileBlock {
    fn from(cap: CapacityBlock) -> Self {
        CesFileBlock::Cap(cap)
    }
}

impl From<MultiplierBlock> for CesFileBlock {
    fn from(mul: MultiplierBlock) -> Self {
        CesFileBlock::Mul(mul)
    }
}

impl From<InhibitorBlock> for CesFileBlock {
    fn from(inh: InhibitorBlock) -> Self {
        CesFileBlock::Inh(inh)
    }
}

impl FromSpec for CesFileBlock {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = CesFileBlockParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

#[derive(Debug)]
pub struct ImmediateDef {
    name: String,
    rex:  Rex,
}

impl ImmediateDef {
    pub fn new(name: String, rex: Rex) -> Self {
        ImmediateDef { name, rex }
    }
}

impl FromSpec for ImmediateDef {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = ImmediateDefParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

#[derive(Debug)]
pub struct CesInstance {
    name: String,
    args: Vec<String>,
}

impl CesInstance {
    pub(crate) fn new(name: String) -> Self {
        CesInstance { name, args: Vec::new() }
    }

    pub(crate) fn with_args(mut self, mut args: Vec<String>) -> Self {
        self.args.append(&mut args);
        self
    }
}

impl FromSpec for CesInstance {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = CesInstanceParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

/// A map from nodes to their capacities.
#[derive(Clone, PartialEq, Eq, Default, Debug)]
pub struct CapacityBlock {
    capacities: BTreeMap<String, u64>,
}

impl CapacityBlock {
    pub fn new(size: Literal, nodes: Polynomial) -> Result<Self, Box<dyn Error>> {
        let size = size.try_into()?;
        let nodes: NodeList = nodes.try_into()?;
        let mut capacities = BTreeMap::new();

        for node in nodes.nodes.into_iter() {
            capacities.insert(node, size);
        }

        Ok(CapacityBlock { capacities })
    }

    pub(crate) fn with_more(mut self, more: Vec<Self>) -> Self {
        for mut block in more {
            self.capacities.append(&mut block.capacities);
        }
        self
    }
}

impl FromSpec for CapacityBlock {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = CapBlockParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

/// An alphabetically ordered and deduplicated list of `Multiplier`s.
#[derive(Clone, PartialEq, Eq, Default, Debug)]
pub struct MultiplierBlock {
    multipliers: Vec<Multiplier>,
}

impl MultiplierBlock {
    pub fn new_causes(
        size: Literal,
        post_nodes: Polynomial,
        pre_set: Polynomial,
    ) -> Result<Self, Box<dyn Error>> {
        let size = size.try_into()?;
        let post_nodes: NodeList = post_nodes.try_into()?;
        let pre_set: NodeList = pre_set.try_into()?;

        let multipliers = post_nodes
            .nodes
            .into_iter()
            .map(|post_node| {
                Multiplier::Rx(RxMultiplier { size, post_node, pre_set: pre_set.clone() })
            })
            .collect();
        // No need to sort: `post_nodes` are already ordered and deduplicated.

        Ok(MultiplierBlock { multipliers })
    }

    pub fn new_effects(
        size: Literal,
        pre_nodes: Polynomial,
        post_set: Polynomial,
    ) -> Result<Self, Box<dyn Error>> {
        let size = size.try_into()?;
        let pre_nodes: NodeList = pre_nodes.try_into()?;
        let post_set: NodeList = post_set.try_into()?;

        let multipliers = pre_nodes
            .nodes
            .into_iter()
            .map(|pre_node| {
                Multiplier::Tx(TxMultiplier { size, pre_node, post_set: post_set.clone() })
            })
            .collect();
        // No need to sort: `pre_nodes` are already ordered and deduplicated.

        Ok(MultiplierBlock { multipliers })
    }

    pub(crate) fn with_more(mut self, more: Vec<Self>) -> Self {
        for mut block in more {
            self.multipliers.append(&mut block.multipliers);
        }

        self.multipliers.sort();
        let len = self.multipliers.partition_dedup().0.len();
        self.multipliers.truncate(len);

        self
    }
}

impl FromSpec for MultiplierBlock {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = MulBlockParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Multiplier {
    Rx(RxMultiplier),
    Tx(TxMultiplier),
}

impl cmp::Ord for Multiplier {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        use Multiplier::*;

        match self {
            Rx(s) => match other {
                Rx(o) => s.cmp(o),
                Tx(_) => cmp::Ordering::Less,
            },
            Tx(s) => match other {
                Rx(_) => cmp::Ordering::Greater,
                Tx(o) => s.cmp(o),
            },
        }
    }
}

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

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct RxMultiplier {
    size:      u64,
    post_node: String,
    pre_set:   NodeList,
}

impl cmp::Ord for RxMultiplier {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        match self.post_node.cmp(&other.post_node) {
            cmp::Ordering::Equal => match self.pre_set.cmp(&other.pre_set) {
                cmp::Ordering::Equal => self.size.cmp(&other.size),
                result => result,
            },
            result => result,
        }
    }
}

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

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TxMultiplier {
    size:     u64,
    pre_node: String,
    post_set: NodeList,
}

impl cmp::Ord for TxMultiplier {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        match self.pre_node.cmp(&other.pre_node) {
            cmp::Ordering::Equal => match self.post_set.cmp(&other.post_set) {
                cmp::Ordering::Equal => self.size.cmp(&other.size),
                result => result,
            },
            result => result,
        }
    }
}

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

/// An alphabetically ordered and deduplicated list of `Inhibitor`s.
#[derive(Clone, PartialEq, Eq, Default, Debug)]
pub struct InhibitorBlock {
    inhibitors: Vec<Inhibitor>,
}

impl InhibitorBlock {
    pub fn new_causes(post_nodes: Polynomial, pre_set: Polynomial) -> Result<Self, Box<dyn Error>> {
        let post_nodes: NodeList = post_nodes.try_into()?;
        let pre_set: NodeList = pre_set.try_into()?;

        let inhibitors = post_nodes
            .nodes
            .into_iter()
            .map(|post_node| Inhibitor::Rx(RxInhibitor { post_node, pre_set: pre_set.clone() }))
            .collect();
        // No need to sort: `post_nodes` are already ordered and deduplicated.

        Ok(InhibitorBlock { inhibitors })
    }

    pub fn new_effects(
        pre_nodes: Polynomial,
        post_set: Polynomial,
    ) -> Result<Self, Box<dyn Error>> {
        let pre_nodes: NodeList = pre_nodes.try_into()?;
        let post_set: NodeList = post_set.try_into()?;

        let inhibitors = pre_nodes
            .nodes
            .into_iter()
            .map(|pre_node| Inhibitor::Tx(TxInhibitor { pre_node, post_set: post_set.clone() }))
            .collect();
        // No need to sort: `pre_nodes` are already ordered and deduplicated.

        Ok(InhibitorBlock { inhibitors })
    }

    pub(crate) fn with_more(mut self, more: Vec<Self>) -> Self {
        for mut block in more {
            self.inhibitors.append(&mut block.inhibitors);
        }

        self.inhibitors.sort();
        let len = self.inhibitors.partition_dedup().0.len();
        self.inhibitors.truncate(len);

        self
    }
}

impl FromSpec for InhibitorBlock {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = InhBlockParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Inhibitor {
    Rx(RxInhibitor),
    Tx(TxInhibitor),
}

impl cmp::Ord for Inhibitor {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        use Inhibitor::*;

        match self {
            Rx(s) => match other {
                Rx(o) => s.cmp(o),
                Tx(_) => cmp::Ordering::Less,
            },
            Tx(s) => match other {
                Rx(_) => cmp::Ordering::Greater,
                Tx(o) => s.cmp(o),
            },
        }
    }
}

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

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct RxInhibitor {
    post_node: String,
    pre_set:   NodeList,
}

impl cmp::Ord for RxInhibitor {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        match self.post_node.cmp(&other.post_node) {
            cmp::Ordering::Equal => self.pre_set.cmp(&other.pre_set),
            result => result,
        }
    }
}

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

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TxInhibitor {
    pre_node: String,
    post_set: NodeList,
}

impl cmp::Ord for TxInhibitor {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        match self.pre_node.cmp(&other.pre_node) {
            cmp::Ordering::Equal => self.post_set.cmp(&other.post_set),
            result => result,
        }
    }
}

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

pub type RexID = usize;

#[derive(Debug)]
pub struct Rex {
    root:  RexID,
    kinds: Vec<RexKind>,
}

impl Rex {
    pub(crate) fn with_more(self, rexlist: Vec<(Option<BinOp>, Rex)>) -> Self {
        let mut sum_pos = Vec::new();
        for (ndx, (op, _)) in rexlist.iter().enumerate() {
            if let Some(op) = op {
                if *op == BinOp::Add {
                    sum_pos.push(ndx);
                }
            }
        }

        self
    }
}

impl From<ThinArrowRule> for Rex {
    fn from(rule: ThinArrowRule) -> Self {
        Rex { root: 0, kinds: vec![RexKind::Thin(rule)] }
    }
}

impl From<FatArrowRule> for Rex {
    fn from(rule: FatArrowRule) -> Self {
        Rex { root: 0, kinds: vec![RexKind::Fat(rule)] }
    }
}

impl From<CesInstance> for Rex {
    fn from(instance: CesInstance) -> Self {
        Rex { root: 0, kinds: vec![RexKind::Instance(instance)] }
    }
}

impl FromSpec for Rex {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = RexParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

#[derive(Debug)]
pub enum RexKind {
    Thin(ThinArrowRule),
    Fat(FatArrowRule),
    Instance(CesInstance),
    Product(RexProduct),
    Sum(RexSum),
}

#[derive(Debug)]
pub struct RexProduct {
    ids: Vec<RexID>,
}

#[derive(Debug)]
pub struct RexSum {
    ids: Vec<RexID>,
}

#[derive(Default, Debug)]
pub struct ThinArrowRule {
    nodes:  NodeList,
    cause:  Polynomial,
    effect: Polynomial,
}

impl ThinArrowRule {
    pub(crate) fn new() -> Self {
        Default::default()
    }

    pub(crate) fn with_nodes(mut self, nodes: Polynomial) -> Result<Self, Box<dyn Error>> {
        self.nodes = nodes.try_into()?;
        Ok(self)
    }

    pub(crate) fn with_cause(mut self, cause: Polynomial) -> Self {
        self.cause = cause;
        self
    }

    pub(crate) fn with_effect(mut self, effect: Polynomial) -> Self {
        self.effect = effect;
        self
    }
}

impl FromSpec for ThinArrowRule {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = ThinArrowRuleParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

#[derive(Default, Debug)]
pub struct FatArrowRule {
    causes:  Vec<Polynomial>,
    effects: Vec<Polynomial>,
}

impl FatArrowRule {
    pub(crate) fn from_parts(head: Polynomial, tail: Vec<(BinOp, Polynomial)>) -> Self {
        assert!(!tail.is_empty(), "Single-polynomial fat rule");

        let mut rule = Self::default();
        let mut prev = head;

        for (op, poly) in tail.into_iter() {
            match op {
                BinOp::FatTx => {
                    rule.causes.push(prev);
                    rule.effects.push(poly.clone());
                }
                BinOp::FatRx => {
                    rule.effects.push(prev);
                    rule.causes.push(poly.clone());
                }
                _ => panic!("Operator not allowed in a fat rule: '{}'.", op),
            }
            prev = poly;
        }
        rule
    }
}

impl FromSpec for FatArrowRule {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = FatArrowRuleParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

/// An alphabetically ordered and deduplicated list of `Node`s.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default, Debug)]
pub struct NodeList {
    nodes: Vec<String>,
}

impl NodeList {
    pub fn with_more(mut self, nodes: Vec<String>) -> Self {
        self.nodes.extend(nodes.into_iter());
        self.nodes.sort();
        let len = self.nodes.partition_dedup().0.len();
        self.nodes.truncate(len);
        self
    }
}

impl From<String> for NodeList {
    fn from(node: String) -> Self {
        NodeList { nodes: vec![node] }
    }
}

impl From<Vec<String>> for NodeList {
    fn from(mut nodes: Vec<String>) -> Self {
        nodes.sort();
        let len = nodes.partition_dedup().0.len();
        nodes.truncate(len);
        NodeList { nodes }
    }
}

impl TryFrom<Polynomial> for NodeList {
    type Error = &'static str;

    fn try_from(poly: Polynomial) -> Result<Self, Self::Error> {
        if poly.is_flat {
            let mut monomials = poly.monomials.into_iter();

            if let Some(monomial) = monomials.next() {
                let nodes = Vec::from_iter(monomial.into_iter());
                // no need for sorting, unless `monomial` breaks the
                // invariants: 'is-ordered' and 'no-duplicates'...

                if monomials.next().is_none() {
                    Ok(NodeList { nodes })
                } else {
                    Err("Not a node list")
                }
            } else {
                Ok(Default::default())
            }
        } else {
            Err("Not a node list")
        }
    }
}

/// An alphabetically ordered and deduplicated list of monomials,
/// where each monomial is alphabetically ordered and deduplicated
/// list of `Node`s.
#[derive(Clone, Debug)]
pub struct Polynomial {
    monomials: BTreeSet<BTreeSet<String>>,

    // FIXME falsify on leading "+" or parens, even if still a mono
    is_flat: bool,
}

impl Polynomial {
    /// Returns `self` multiplied by the product of `factors`.
    pub(crate) fn with_product_multiplied(mut self, mut factors: Vec<Self>) -> Self {
        self.multiply_assign(&mut factors);
        self
    }

    /// Returns `self` added to the product of `factors`.
    pub(crate) fn with_product_added(mut self, mut factors: Vec<Self>) -> Self {
        if let Some((head, tail)) = factors.split_first_mut() {
            head.multiply_assign(tail);
            self.add_assign(head);
        }
        self
    }

    fn multiply_assign(&mut self, factors: &mut [Self]) {
        for factor in factors {
            if !factor.is_flat {
                self.is_flat = false;
            }

            let lhs: Vec<_> = self.monomials.iter().cloned().collect();
            self.monomials.clear();

            for this_mono in lhs.iter() {
                for other_mono in factor.monomials.iter() {
                    let mut mono = this_mono.clone();
                    mono.extend(other_mono.iter().cloned());
                    self.monomials.insert(mono);
                }
            }
        }
    }

    fn add_assign(&mut self, other: &mut Self) {
        self.is_flat = false;
        self.monomials.append(&mut other.monomials);
    }
}

impl FromSpec for Polynomial {
    fn from_spec<S: AsRef<str>>(spec: S) -> ParsingResult<Self> {
        let spec = spec.as_ref();
        let mut errors = Vec::new();

        let result = PolynomialParser::new()
            .parse(&mut errors, spec)
            .map_err(|err| err.map_token(|t| format!("{}", t)).map_error(|e| e.to_owned()))?;

        Ok(result)
    }
}

impl Default for Polynomial {
    fn default() -> Self {
        Polynomial { monomials: BTreeSet::default(), is_flat: true }
    }
}

impl From<String> for Polynomial {
    fn from(node: String) -> Self {
        Polynomial {
            monomials: BTreeSet::from_iter(Some(BTreeSet::from_iter(Some(node)))),
            is_flat:   true,
        }
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Literal {
    Size(u64),
    Name(String),
}

impl Literal {
    pub(crate) fn from_digits(digits: &str) -> Result<Self, Box<dyn Error>> {
        Ok(Literal::Size(u64::from_str(digits)?))
    }

    pub(crate) fn from_quoted_str(quoted: &str) -> Result<Self, Box<dyn Error>> {
        Ok(Literal::Name(unquote(quoted)?))
    }
}

impl TryFrom<Literal> for u64 {
    type Error = &'static str;

    fn try_from(lit: Literal) -> Result<Self, Self::Error> {
        if let Literal::Size(size) = lit {
            Ok(size)
        } else {
            Err("Bad literal, not a size")
        }
    }
}

impl TryFrom<Literal> for String {
    type Error = &'static str;

    fn try_from(lit: Literal) -> Result<Self, Self::Error> {
        if let Literal::Name(name) = lit {
            Ok(name)
        } else {
            Err("Bad literal, not a string")
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BinOp {
    Add,
    ThinTx,
    ThinRx,
    FatTx,
    FatRx,
}

impl fmt::Display for BinOp {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            BinOp::Add => '+'.fmt(f),
            BinOp::ThinTx => "->".fmt(f),
            BinOp::ThinRx => "<-".fmt(f),
            BinOp::FatTx => "=>".fmt(f),
            BinOp::FatRx => "<=".fmt(f),
        }
    }
}