1
#![allow(clippy::result_large_err)]
2

            
3
use std::iter;
4

            
5
use itertools::Itertools;
6
use pest::error::ErrorVariant;
7

            
8
use merc_pest_consume::Error;
9
use merc_pest_consume::match_nodes;
10

            
11
use crate::ActDecl;
12
use crate::ActFrm;
13
use crate::Action;
14
use crate::ActionRenameDecl;
15
use crate::Assignment;
16
use crate::BagElement;
17
use crate::Comm;
18
use crate::ComplexSort;
19
use crate::ConstructorDecl;
20
use crate::DataExpr;
21
use crate::DataExprUnaryOp;
22
use crate::DataExprUpdate;
23
use crate::EqnDecl;
24
use crate::EqnSpec;
25
use crate::FixedPointOperator;
26
use crate::IdDecl;
27
use crate::Mcrl2Parser;
28
use crate::MultiAction;
29
use crate::MultiActionLabel;
30
use crate::PbesEquation;
31
use crate::PbesExpr;
32
use crate::ProcDecl;
33
use crate::ProcessExpr;
34
use crate::PropVarDecl;
35
use crate::PropVarInst;
36
use crate::RegFrm;
37
use crate::Rename;
38
use crate::Rule;
39
use crate::SortDecl;
40
use crate::SortExpression;
41
use crate::StateFrm;
42
use crate::StateVarAssignment;
43
use crate::StateVarDecl;
44
use crate::UntypedActionRenameSpec;
45
use crate::UntypedDataSpecification;
46
use crate::UntypedPbes;
47
use crate::UntypedProcessSpecification;
48
use crate::UntypedStateFrmSpec;
49
use crate::VarDecl;
50
use crate::parse_actfrm;
51
use crate::parse_dataexpr;
52
use crate::parse_pbesexpr;
53
use crate::parse_process_expr;
54
use crate::parse_regfrm;
55
use crate::parse_sortexpr;
56
use crate::parse_sortexpr_primary;
57
use crate::parse_statefrm;
58

            
59
/// Type alias for Errors resulting parsing.
60
pub(crate) type ParseResult<T> = std::result::Result<T, Error<Rule>>;
61
pub(crate) type ParseNode<'i> = merc_pest_consume::Node<'i, Rule, ()>;
62

            
63
/// These functions are used to consume the parse tree generated by the `pest` parser into a syntax tree.
64
///
65
/// Functions that are private are only used by other functions within the module, especially within the `matches_nodes!` macro.
66
/// See `pest_consume` documentation for more details on how to use this macro. The main idea is to apply the consume functions to the children of a parse node whenver they matce the arm.
67
///
68
/// Functions that are `pub(crate)` are used by the pratt parser to consume the parse tree and build the syntax tree with priorities
69
/// and associativity. They are defined in `precedence.rs`.
70
#[merc_pest_consume::parser]
71
impl Mcrl2Parser {
72
    // Although these are not public, they are the main entry points for consuming the parse tree.
73
    pub(crate) fn MCRL2Spec(spec: ParseNode) -> ParseResult<UntypedProcessSpecification> {
74
        let mut action_declarations = Vec::new();
75
        let mut map_declarations = Vec::new();
76
        let mut constructor_declarations = Vec::new();
77
        let mut equation_declarations = Vec::new();
78
        let mut global_variables = Vec::new();
79
        let mut process_declarations = Vec::new();
80
        let mut sort_declarations = Vec::new();
81

            
82
        let mut init = None;
83

            
84
        for child in spec.into_children() {
85
            match child.as_rule() {
86
                Rule::ActSpec => {
87
                    action_declarations.extend(Mcrl2Parser::ActSpec(child)?);
88
                }
89
                Rule::ConsSpec => {
90
                    constructor_declarations.append(&mut Mcrl2Parser::ConsSpec(child)?);
91
                }
92
                Rule::MapSpec => {
93
                    map_declarations.append(&mut Mcrl2Parser::MapSpec(child)?);
94
                }
95
                Rule::GlobVarSpec => {
96
                    global_variables.append(&mut Mcrl2Parser::GlobVarSpec(child)?);
97
                }
98
                Rule::EqnSpec => {
99
                    equation_declarations.append(&mut Mcrl2Parser::EqnSpec(child)?);
100
                }
101
                Rule::ProcSpec => {
102
                    process_declarations.append(&mut Mcrl2Parser::ProcSpec(child)?);
103
                }
104
                Rule::SortSpec => {
105
                    sort_declarations.append(&mut Mcrl2Parser::SortSpec(child)?);
106
                }
107
                Rule::Init => {
108
                    if init.is_some() {
109
                        return Err(Error::new_from_span(
110
                            ErrorVariant::CustomError {
111
                                message: "Multiple init expressions are not allowed".to_string(),
112
                            },
113
                            child.as_span(),
114
                        ));
115
                    }
116

            
117
                    init = Some(Mcrl2Parser::Init(child)?);
118
                }
119
                Rule::EOI => {
120
                    // End of input
121
                    break;
122
                }
123
                _ => {
124
                    unimplemented!("Unexpected rule: {:?}", child.as_rule());
125
                }
126
            }
127
        }
128

            
129
        let data_specification = UntypedDataSpecification {
130
            map_declarations,
131
            constructor_declarations,
132
            equation_declarations,
133
            sort_declarations,
134
        };
135

            
136
        Ok(UntypedProcessSpecification {
137
            data_specification,
138
            global_variables,
139
            action_declarations,
140
            process_declarations,
141
            init,
142
        })
143
    }
144

            
145
    pub fn PbesSpec(spec: ParseNode) -> ParseResult<UntypedPbes> {
146
        let mut data_specification = None;
147
        let mut global_variables = None;
148
        let mut equations = None;
149
        let mut init = None;
150

            
151
        for child in spec.into_children() {
152
            match child.as_rule() {
153
                Rule::DataSpec => {
154
                    data_specification = Some(Mcrl2Parser::DataSpec(child)?);
155
                }
156
                Rule::GlobVarSpec => {
157
                    global_variables = Some(Mcrl2Parser::GlobVarSpec(child)?);
158
                }
159
                Rule::PbesEqnSpec => {
160
                    equations = Some(Mcrl2Parser::PbesEqnSpec(child)?);
161
                }
162
                Rule::PbesInit => {
163
                    init = Some(Mcrl2Parser::PbesInit(child)?);
164
                }
165
                Rule::EOI => {
166
                    // End of input
167
                    break;
168
                }
169
                _ => {
170
                    unimplemented!("Unexpected rule: {:?}", child.as_rule());
171
                }
172
            }
173
        }
174

            
175
        Ok(UntypedPbes {
176
            data_specification: data_specification.unwrap_or_default(),
177
            global_variables: global_variables.unwrap_or_default(),
178
            equations: equations.unwrap(),
179
            init: init.unwrap(),
180
        })
181
    }
182

            
183
    fn PbesInit(init: ParseNode) -> ParseResult<PropVarInst> {
184
        match_nodes!(init.into_children();
185
            [PropVarInst(inst)] => {
186
                Ok(inst)
187
            }
188
        )
189
    }
190

            
191
    fn PbesEqnSpec(spec: ParseNode) -> ParseResult<Vec<PbesEquation>> {
192
        match_nodes!(spec.into_children();
193
            [PbesEqnDecl(equations)..] => {
194
                Ok(equations.collect())
195
            },
196
        )
197
    }
198

            
199
    fn PbesEqnDecl(decl: ParseNode) -> ParseResult<PbesEquation> {
200
        let span = decl.as_span();
201
        match_nodes!(decl.into_children();
202
            [FixedPointOperator(operator), PropVarDecl(variable), PbesExpr(formula)] => {
203
                Ok(PbesEquation {
204
                    operator,
205
                    variable,
206
                    formula,
207
                    span: span.into(),
208
                })
209
            },
210
        )
211
    }
212

            
213
    fn FixedPointOperator(op: ParseNode) -> ParseResult<FixedPointOperator> {
214
        match op.into_children().next().unwrap().as_rule() {
215
            Rule::FixedPointMu => Ok(FixedPointOperator::Least),
216
            Rule::FixedPointNu => Ok(FixedPointOperator::Greatest),
217
            x => unimplemented!("This is not a fixed point operator: {:?}", x),
218
        }
219
    }
220

            
221
    fn PropVarDecl(decl: ParseNode) -> ParseResult<PropVarDecl> {
222
        let span = decl.as_span();
223
        match_nodes!(decl.into_children();
224
            [Id(identifier), VarsDeclList(params)] => {
225
                Ok(PropVarDecl {
226
                    identifier,
227
                    parameters: params,
228
                    span: span.into(),
229
                })
230
            },
231
            [Id(identifier)] => {
232
                Ok(PropVarDecl {
233
                    identifier,
234
                    parameters: Vec::new(),
235
                    span: span.into(),
236
                })
237
            }
238
        )
239
    }
240

            
241
    pub(crate) fn PropVarInst(inst: ParseNode) -> ParseResult<PropVarInst> {
242
        match_nodes!(inst.into_children();
243
            [Id(identifier)] => {
244
                Ok(PropVarInst {
245
                    identifier,
246
                    arguments: Vec::new(),
247
                })
248
            },
249
            [Id(identifier), DataExprList(arguments)] => {
250
                Ok(PropVarInst {
251
                    identifier,
252
                    arguments,
253
                })
254
            }
255
        )
256
    }
257

            
258
    fn PbesExpr(expr: ParseNode) -> ParseResult<PbesExpr> {
259
        parse_pbesexpr(expr.children().as_pairs().clone())
260
    }
261

            
262
    fn ActSpec(spec: ParseNode) -> ParseResult<Vec<ActDecl>> {
263
        match_nodes!(spec.into_children();
264
            [ActDecl(decls)..] => {
265
                Ok(decls.flatten().collect())
266
            },
267
        )
268
    }
269

            
270
    fn ActDecl(decl: ParseNode) -> ParseResult<Vec<ActDecl>> {
271
        let span = decl.as_span();
272
        match_nodes!(decl.into_children();
273
            [IdList(identifiers)] => {
274
759
                Ok(identifiers.iter().map(|name| ActDecl { identifier: name.clone(), args: Vec::new(), span: span.into() }).collect())
275
            },
276
            [IdList(identifiers), SortProduct(args)] => {
277
5220
                Ok(identifiers.iter().map(|name| ActDecl { identifier: name.clone(), args: args.clone(), span: span.into() }).collect())
278
            },
279
        )
280
    }
281

            
282
    fn SortProduct(sort: ParseNode) -> ParseResult<Vec<SortExpression>> {
283
        let mut iter = sort.into_children();
284

            
285
        // An expression of the shape SortExprPrimary ~ (SortExprProduct ~ SortExprPrimary)*
286
        let mut result = vec![parse_sortexpr_primary(iter.next().unwrap().as_pair().clone())?];
287

            
288
        for mut chunk in &iter.chunks(2) {
289
            if chunk.next().unwrap().as_rule() == Rule::SortExprProduct {
290
                let sort = parse_sortexpr_primary(chunk.next().unwrap().as_pair().clone())?;
291
                result.push(sort);
292
            }
293
        }
294

            
295
        Ok(result)
296
    }
297

            
298
    fn GlobVarSpec(spec: ParseNode) -> ParseResult<Vec<VarDecl>> {
299
        match_nodes!(spec.into_children();
300
            [VarsDeclList(vars)] => {
301
                Ok(vars)
302
            }
303
        )
304
    }
305

            
306
    fn SortExprPrimary(sort: ParseNode) -> ParseResult<SortExpression> {
307
        parse_sortexpr(sort.children().as_pairs().clone())
308
    }
309

            
310
    pub(crate) fn DataSpec(spec: ParseNode) -> ParseResult<UntypedDataSpecification> {
311
        let mut map_declarations = Vec::new();
312
        let mut equation_declarations = Vec::new();
313
        let mut constructor_declarations = Vec::new();
314
        let mut sort_declarations = Vec::new();
315

            
316
        for child in spec.into_children() {
317
            match child.as_rule() {
318
                Rule::ConsSpec => {
319
                    constructor_declarations.append(&mut Mcrl2Parser::ConsSpec(child)?);
320
                }
321
                Rule::MapSpec => {
322
                    map_declarations.append(&mut Mcrl2Parser::MapSpec(child)?);
323
                }
324
                Rule::EqnSpec => {
325
                    equation_declarations.append(&mut Mcrl2Parser::EqnSpec(child)?);
326
                }
327
                Rule::SortSpec => {
328
                    sort_declarations.append(&mut Mcrl2Parser::SortSpec(child)?);
329
                }
330
                Rule::EOI => {
331
                    // End of input
332
                    break;
333
                }
334
                _ => {
335
                    unimplemented!("Unexpected rule: {:?}", child.as_rule());
336
                }
337
            }
338
        }
339

            
340
        Ok(UntypedDataSpecification {
341
            map_declarations,
342
            equation_declarations,
343
            constructor_declarations,
344
            sort_declarations,
345
        })
346
    }
347

            
348
    pub fn ActionRenameSpec(spec: ParseNode) -> ParseResult<UntypedActionRenameSpec> {
349
        let mut map_declarations = Vec::new();
350
        let mut equation_declarations = Vec::new();
351
        let mut constructor_declarations = Vec::new();
352
        let mut sort_declarations = Vec::new();
353
        let mut action_declarations = Vec::new();
354
        let mut rename_declarations = Vec::new();
355

            
356
        for child in spec.into_children() {
357
            match child.as_rule() {
358
                Rule::ConsSpec => {
359
                    constructor_declarations.append(&mut Mcrl2Parser::ConsSpec(child)?);
360
                }
361
                Rule::MapSpec => {
362
                    map_declarations.append(&mut Mcrl2Parser::MapSpec(child)?);
363
                }
364
                Rule::EqnSpec => {
365
                    equation_declarations.append(&mut Mcrl2Parser::EqnSpec(child)?);
366
                }
367
                Rule::SortSpec => {
368
                    sort_declarations.append(&mut Mcrl2Parser::SortSpec(child)?);
369
                }
370
                Rule::ActSpec => {
371
                    action_declarations.append(&mut Mcrl2Parser::ActSpec(child)?);
372
                }
373
                Rule::ActionRenameRuleSpec => rename_declarations.push(Mcrl2Parser::ActionRenameRuleSpec(child)?),
374
                Rule::EOI => {
375
                    // End of input
376
                    break;
377
                }
378
                _ => {
379
                    unimplemented!("Unexpected rule: {:?}", child.as_rule());
380
                }
381
            }
382
        }
383

            
384
        let data_specification = UntypedDataSpecification {
385
            map_declarations,
386
            equation_declarations,
387
            constructor_declarations,
388
            sort_declarations,
389
        };
390

            
391
        Ok(UntypedActionRenameSpec {
392
            data_specification,
393
            action_declarations,
394
            rename_declarations,
395
        })
396
    }
397

            
398
    pub(crate) fn StateFrmId(id: ParseNode) -> ParseResult<StateFrm> {
399
        match_nodes!(id.into_children();
400
            [Id(identifier)] => {
401
                Ok(StateFrm::Id(identifier, Vec::new()))
402
            },
403
            [Id(identifier), DataExprList(expressions)] => {
404
                Ok(StateFrm::Id(identifier, expressions))
405
            },
406
        )
407
    }
408

            
409
    fn MapSpec(spec: ParseNode) -> ParseResult<Vec<IdDecl>> {
410
        match_nodes!(spec.into_children();
411
            [IdsDecl(decls)..] => {
412
                Ok(decls.flatten().collect())
413
            }
414
        )
415
    }
416

            
417
    fn SortSpec(spec: ParseNode) -> ParseResult<Vec<SortDecl>> {
418
        match_nodes!(spec.into_children();
419
            [SortDecl(decls)..] => {
420
                Ok(decls.flatten().collect())
421
            }
422
        )
423
    }
424

            
425
    fn SortDecl(decl: ParseNode) -> ParseResult<Vec<SortDecl>> {
426
        let span = decl.as_span();
427

            
428
        match_nodes!(decl.into_children();
429
            [Id(identifier), SortExpr(expr)] => {
430
                Ok(vec![SortDecl { identifier, expr: Some(expr), span: span.into() }])
431
            },
432
            [IdList(ids)] => {
433
9
                Ok(ids.iter().map(|identifier| SortDecl { identifier: identifier.clone(), expr: None, span: span.into() }).collect())
434
            },
435
            [IdsDecl(decl)] => {
436
                Ok(decl.iter().map(|element| SortDecl { identifier: element.identifier.clone(), expr: Some(element.sort.clone()), span: span.into() }).collect())
437
            }
438
        )
439
    }
440

            
441
    fn ConsSpec(spec: ParseNode) -> ParseResult<Vec<IdDecl>> {
442
        match_nodes!(spec.into_children();
443
            [IdsDecl(decls)..] => {
444
                Ok(decls.flatten().collect())
445
            }
446
        )
447
    }
448

            
449
    fn Init(init: ParseNode) -> ParseResult<ProcessExpr> {
450
        match_nodes!(init.into_children();
451
            [ProcExpr(expr)] => {
452
                Ok(expr)
453
            }
454
        )
455
    }
456

            
457
    fn ProcSpec(spec: ParseNode) -> ParseResult<Vec<ProcDecl>> {
458
        match_nodes!(spec.into_children();
459
            [ProcDecl(decls)..] => {
460
                Ok(decls.collect())
461
            },
462
        )
463
    }
464

            
465
    fn ProcDecl(decl: ParseNode) -> ParseResult<ProcDecl> {
466
        let span = decl.as_span();
467
        match_nodes!(decl.into_children();
468
            [Id(identifier), VarsDeclList(params), ProcExpr(body)] => {
469
                Ok(ProcDecl {
470
                    identifier,
471
                    params,
472
                    body,
473
                    span: span.into(),
474
                })
475
            },
476
            [Id(identifier), ProcExpr(body)] => {
477
                Ok(ProcDecl {
478
                    identifier,
479
                    params: Vec::new(),
480
                    body,
481
                    span: span.into(),
482
                })
483
            }
484
        )
485
    }
486

            
487
    pub(crate) fn ProcExprAt(input: ParseNode) -> ParseResult<DataExpr> {
488
        match_nodes!(input.into_children();
489
            [DataExprUnit(expr)] => {
490
                Ok(expr)
491
            },
492
        )
493
    }
494

            
495
    pub(crate) fn StateFrmExists(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
496
        match_nodes!(input.into_children();
497
            [VarsDeclList(variables)] => {
498
                Ok(variables)
499
            },
500
        )
501
    }
502

            
503
    pub(crate) fn StateFrmForall(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
504
        match_nodes!(input.into_children();
505
            [VarsDeclList(variables)] => {
506
                Ok(variables)
507
            },
508
        )
509
    }
510

            
511
    pub(crate) fn StateFrmMu(input: ParseNode) -> ParseResult<StateVarDecl> {
512
        match_nodes!(input.into_children();
513
            [StateVarDecl(variable)] => {
514
                Ok(variable)
515
            },
516
        )
517
    }
518

            
519
    pub(crate) fn StateFrmNu(input: ParseNode) -> ParseResult<StateVarDecl> {
520
        match_nodes!(input.into_children();
521
            [StateVarDecl(variable)] => {
522
                Ok(variable)
523
            },
524
        )
525
    }
526

            
527
    pub(crate) fn ActFrmExists(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
528
        match_nodes!(input.into_children();
529
            [VarsDeclList(variables)] => {
530
                Ok(variables)
531
            },
532
        )
533
    }
534

            
535
    pub(crate) fn ActFrmForall(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
536
        match_nodes!(input.into_children();
537
            [VarsDeclList(variables)] => {
538
                Ok(variables)
539
            },
540
        )
541
    }
542

            
543
    pub(crate) fn DataExpr(expr: ParseNode) -> ParseResult<DataExpr> {
544
        parse_dataexpr(expr.children().as_pairs().clone())
545
    }
546

            
547
    pub(crate) fn DataExprUnit(expr: ParseNode) -> ParseResult<DataExpr> {
548
        parse_dataexpr(expr.children().as_pairs().clone())
549
    }
550

            
551
    pub(crate) fn DataValExpr(expr: ParseNode) -> ParseResult<DataExpr> {
552
        match_nodes!(expr.into_children();
553
            [DataExpr(expr)] => {
554
                Ok(expr)
555
            },
556
        )
557
    }
558

            
559
    pub(crate) fn DataExprUpdate(expr: ParseNode) -> ParseResult<DataExprUpdate> {
560
        match_nodes!(expr.into_children();
561
            [DataExpr(expr), DataExpr(update)] => {
562
                Ok(DataExprUpdate { expr, update })
563
            },
564
        )
565
    }
566

            
567
    pub(crate) fn DataExprApplication(expr: ParseNode) -> ParseResult<Vec<DataExpr>> {
568
        match_nodes!(expr.into_children();
569
            [DataExprList(expressions)] => {
570
                Ok(expressions)
571
            },
572
        )
573
    }
574

            
575
    pub(crate) fn DataExprWhr(expr: ParseNode) -> ParseResult<Vec<Assignment>> {
576
        match_nodes!(expr.into_children();
577
            [AssignmentList(assignments)] => {
578
                Ok(assignments)
579
            },
580
        )
581
    }
582

            
583
    pub(crate) fn AssignmentList(assignments: ParseNode) -> ParseResult<Vec<Assignment>> {
584
        match_nodes!(assignments.into_children();
585
            [Assignment(assignment)] => {
586
                Ok(vec![assignment])
587
            },
588
            [Assignment(assignment)..] => {
589
                Ok(assignment.collect())
590
            },
591
        )
592
    }
593

            
594
    pub(crate) fn Assignment(assignment: ParseNode) -> ParseResult<Assignment> {
595
        match_nodes!(assignment.into_children();
596
            [Id(identifier), DataExpr(expr)] => {
597
                Ok(Assignment { identifier, expr })
598
            },
599
        )
600
    }
601

            
602
    pub(crate) fn DataExprSize(expr: ParseNode) -> ParseResult<DataExpr> {
603
        match_nodes!(expr.into_children();
604
            [DataExpr(expr)] => {
605
                Ok(DataExpr::Unary { op: DataExprUnaryOp::Size, expr: Box::new(expr) })
606
            },
607
        )
608
    }
609

            
610
    fn DataExprList(expr: ParseNode) -> ParseResult<Vec<DataExpr>> {
611
        match_nodes!(expr.into_children();
612
            [DataExpr(expr)] => {
613
                Ok(vec![expr])
614
            },
615
            [DataExpr(expr)..] => {
616
                Ok(expr.collect())
617
            },
618
        )
619
    }
620

            
621
    fn VarSpec(vars: ParseNode) -> ParseResult<Vec<VarDecl>> {
622
        match_nodes!(vars.into_children();
623
            [VarsDeclList(ids)..] => {
624
                Ok(ids.flatten().collect())
625
            },
626
        )
627
    }
628

            
629
    pub(crate) fn VarsDeclList(vars: ParseNode) -> ParseResult<Vec<VarDecl>> {
630
        match_nodes!(vars.into_children();
631
            [VarsDecl(decl)..] => {
632
                Ok(decl.flatten().collect())
633
            },
634
        )
635
    }
636

            
637
    fn VarsDecl(decl: ParseNode) -> ParseResult<Vec<VarDecl>> {
638
        let mut vars = Vec::new();
639

            
640
        let span = decl.as_span();
641
        match_nodes!(decl.into_children();
642
            [IdList(identifier), SortExpr(sort)] => {
643
                for id in identifier {
644
                    vars.push(VarDecl { identifier: id, sort: sort.clone(), span: span.into() });
645
                }
646
            },
647
        );
648

            
649
        Ok(vars)
650
    }
651

            
652
    pub(crate) fn SortExpr(expr: ParseNode) -> ParseResult<SortExpression> {
653
        parse_sortexpr(expr.children().as_pairs().clone())
654
    }
655

            
656
    pub(crate) fn Id(identifier: ParseNode) -> ParseResult<String> {
657
        Ok(identifier.as_str().to_string())
658
    }
659

            
660
    pub(crate) fn IdList(identifiers: ParseNode) -> ParseResult<Vec<String>> {
661
        match_nodes!(identifiers.into_children();
662
            [Id(ids)..] => {
663
                Ok(ids.collect())
664
            },
665
        )
666
    }
667

            
668
    // Complex sorts
669
    pub(crate) fn SortExprList(inner: ParseNode) -> ParseResult<SortExpression> {
670
        Ok(SortExpression::Complex(
671
            ComplexSort::List,
672
            Box::new(parse_sortexpr(inner.children().as_pairs().clone())?),
673
        ))
674
    }
675

            
676
    pub(crate) fn SortExprSet(inner: ParseNode) -> ParseResult<SortExpression> {
677
        Ok(SortExpression::Complex(
678
            ComplexSort::Set,
679
            Box::new(parse_sortexpr(inner.children().as_pairs().clone())?),
680
        ))
681
    }
682

            
683
    pub(crate) fn SortExprBag(inner: ParseNode) -> ParseResult<SortExpression> {
684
        Ok(SortExpression::Complex(
685
            ComplexSort::Bag,
686
            Box::new(parse_sortexpr(inner.children().as_pairs().clone())?),
687
        ))
688
    }
689

            
690
    pub(crate) fn SortExprFSet(inner: ParseNode) -> ParseResult<SortExpression> {
691
        Ok(SortExpression::Complex(
692
            ComplexSort::FSet,
693
            Box::new(parse_sortexpr(inner.children().as_pairs().clone())?),
694
        ))
695
    }
696

            
697
    pub(crate) fn SortExprFBag(inner: ParseNode) -> ParseResult<SortExpression> {
698
        Ok(SortExpression::Complex(
699
            ComplexSort::FBag,
700
            Box::new(parse_sortexpr(inner.children().as_pairs().clone())?),
701
        ))
702
    }
703

            
704
    pub(crate) fn SortExprStruct(inner: ParseNode) -> ParseResult<SortExpression> {
705
        match_nodes!(inner.into_children();
706
            [ConstrDeclList(inner)] => {
707
                Ok(SortExpression::Struct { inner })
708
            },
709
        )
710
    }
711

            
712
    pub(crate) fn ConstrDeclList(input: ParseNode) -> ParseResult<Vec<ConstructorDecl>> {
713
        match_nodes!(input.into_children();
714
            [ConstrDecl(decl)..] => {
715
                Ok(decl.collect())
716
            },
717
        )
718
    }
719

            
720
    pub(crate) fn ProjDeclList(input: ParseNode) -> ParseResult<Vec<(Option<String>, SortExpression)>> {
721
        match_nodes!(input.into_children();
722
            [ProjDecl(decl)..] => {
723
                Ok(decl.collect())
724
            },
725
        )
726
    }
727

            
728
    pub(crate) fn ConstrDecl(input: ParseNode) -> ParseResult<ConstructorDecl> {
729
        match_nodes!(input.into_children();
730
            [Id(name)] => {
731
                Ok(ConstructorDecl { name, args: Vec::new(), projection: None })
732
            },
733
            [Id(name), Id(projection)] => {
734
                Ok(ConstructorDecl { name, args: Vec::new(), projection: Some(projection)  })
735
            },
736
            [Id(name), ProjDeclList(args)] => {
737
                Ok(ConstructorDecl { name, args, projection: None })
738
            },
739
            [Id(name), ProjDeclList(args), Id(projection)] => {
740
                Ok(ConstructorDecl { name, args, projection: Some(projection) })
741
            },
742
        )
743
    }
744

            
745
    pub(crate) fn ProjDecl(input: ParseNode) -> ParseResult<(Option<String>, SortExpression)> {
746
        match_nodes!(input.into_children();
747
            [SortExpr(sort)] => {
748
                Ok((None, sort))
749
            },
750
            [Id(name), SortExpr(sort)] => {
751
                Ok((Some(name), sort))
752
            },
753
        )
754
    }
755

            
756
    pub(crate) fn DataExprListEnum(input: ParseNode) -> ParseResult<DataExpr> {
757
        match_nodes!(input.into_children();
758
            [DataExprList(expressions)] => {
759
                Ok(DataExpr::List(expressions))
760
            },
761
        )
762
    }
763

            
764
    pub(crate) fn DataExprBagEnum(input: ParseNode) -> ParseResult<DataExpr> {
765
        match_nodes!(input.into_children();
766
            [BagEnumEltList(elements)] => {
767
                Ok(DataExpr::Bag(elements))
768
            },
769
        )
770
    }
771

            
772
    fn BagEnumEltList(input: ParseNode) -> ParseResult<Vec<BagElement>> {
773
        match_nodes!(input.into_children();
774
            [BagEnumElt(elements)..] => {
775
                Ok(elements.collect())
776
            },
777
        )
778
    }
779

            
780
    fn BagEnumElt(input: ParseNode) -> ParseResult<BagElement> {
781
        match_nodes!(input.into_children();
782
            [DataExpr(expr), DataExpr(multiplicity)] => {
783
                Ok(BagElement { expr, multiplicity })
784
            },
785
        )
786
    }
787

            
788
    pub(crate) fn DataExprSetEnum(input: ParseNode) -> ParseResult<DataExpr> {
789
        match_nodes!(input.into_children();
790
            [DataExprList(expressions)] => {
791
                Ok(DataExpr::Set(expressions))
792
            },
793
        )
794
    }
795

            
796
    pub(crate) fn DataExprSetBagComp(input: ParseNode) -> ParseResult<DataExpr> {
797
        match_nodes!(input.into_children();
798
            [VarDecl(variable), DataExpr(predicate)] => {
799
                Ok(DataExpr::SetBagComp { variable, predicate: Box::new(predicate) })
800
            },
801
        )
802
    }
803

            
804
    pub(crate) fn Number(input: ParseNode) -> ParseResult<DataExpr> {
805
        Ok(DataExpr::Number(input.as_str().into()))
806
    }
807

            
808
    fn VarDecl(decl: ParseNode) -> ParseResult<VarDecl> {
809
        let span = decl.as_span();
810
        match_nodes!(decl.into_children();
811
            [Id(identifier), SortExpr(sort)] => {
812
                Ok(VarDecl { identifier, sort, span: span.into() })
813
            },
814
        )
815
    }
816

            
817
    pub(crate) fn DataExprLambda(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
818
        match_nodes!(input.into_children();
819
            [VarsDeclList(vars)] => {
820
                Ok(vars)
821
            },
822
        )
823
    }
824

            
825
    pub(crate) fn DataExprForall(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
826
        match_nodes!(input.into_children();
827
            [VarsDeclList(vars)] => {
828
                Ok(vars)
829
            },
830
        )
831
    }
832

            
833
    pub(crate) fn DataExprExists(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
834
        match_nodes!(input.into_children();
835
            [VarsDeclList(vars)] => {
836
                Ok(vars)
837
            },
838
        )
839
    }
840

            
841
    pub(crate) fn ActFrm(input: ParseNode) -> ParseResult<ActFrm> {
842
        parse_actfrm(input.children().as_pairs().clone())
843
    }
844

            
845
    fn ActIdSet(actions: ParseNode) -> ParseResult<Vec<String>> {
846
        match_nodes!(actions.into_children();
847
            [IdList(list)] => {
848
                Ok(list)
849
            },
850
        )
851
    }
852

            
853
    fn MultActId(actions: ParseNode) -> ParseResult<MultiActionLabel> {
854
        match_nodes!(actions.into_children();
855
            [Id(action), Id(actions)..] => {
856
                Ok(MultiActionLabel { actions: iter::once(action).chain(actions).collect() })
857
            },
858
        )
859
    }
860

            
861
    fn MultActIdList(actions: ParseNode) -> ParseResult<Vec<MultiActionLabel>> {
862
        match_nodes!(actions.into_children();
863
            [MultActId(action), MultActId(actions)..] => {
864
                Ok(iter::once(action).chain(actions).collect())
865
            },
866
        )
867
    }
868

            
869
    fn MultActIdSet(actions: ParseNode) -> ParseResult<Vec<MultiActionLabel>> {
870
        match_nodes!(actions.into_children();
871
            [MultActIdList(list)] => {
872
                Ok(list)
873
            },
874
        )
875
    }
876

            
877
    fn ProcExpr(input: ParseNode) -> ParseResult<ProcessExpr> {
878
        parse_process_expr(input.children().as_pairs().clone())
879
    }
880

            
881
    fn ProcExprNoIf(input: ParseNode) -> ParseResult<ProcessExpr> {
882
        parse_process_expr(input.children().as_pairs().clone())
883
    }
884

            
885
    pub(crate) fn ProcExprId(input: ParseNode) -> ParseResult<ProcessExpr> {
886
        match_nodes!(input.into_children();
887
            [Id(identifier)] => {
888
                Ok(ProcessExpr::Id(identifier, Vec::new()))
889
            },
890
            [Id(identifier), AssignmentList(assignments)] => {
891
                Ok(ProcessExpr::Id(identifier, assignments))
892
            },
893
        )
894
    }
895

            
896
    pub(crate) fn ProcExprBlock(input: ParseNode) -> ParseResult<ProcessExpr> {
897
        match_nodes!(input.into_children();
898
            [ActIdSet(actions), ProcExpr(expr)] => {
899
                Ok(ProcessExpr::Block {
900
                    actions,
901
                    operand: Box::new(expr),
902
                })
903
            },
904
        )
905
    }
906

            
907
    pub(crate) fn ProcExprIf(input: ParseNode) -> ParseResult<DataExpr> {
908
        match_nodes!(input.into_children();
909
            [DataExpr(condition)] => {
910
                Ok(condition)
911
            },
912
        )
913
    }
914

            
915
    pub(crate) fn ProcExprIfThen(input: ParseNode) -> ParseResult<(DataExpr, ProcessExpr)> {
916
        match_nodes!(input.into_children();
917
            [DataExpr(condition), ProcExprNoIf(expr)] => {
918
                Ok((condition, expr))
919
            },
920
        )
921
    }
922

            
923
    pub(crate) fn ProcExprAllow(input: ParseNode) -> ParseResult<ProcessExpr> {
924
        match_nodes!(input.into_children();
925
            [MultActIdSet(actions), ProcExpr(expr)] => {
926
                Ok(ProcessExpr::Allow {
927
                    actions,
928
                    operand: Box::new(expr),
929
                })
930
            },
931
        )
932
    }
933

            
934
    pub(crate) fn ProcExprHide(input: ParseNode) -> ParseResult<ProcessExpr> {
935
        match_nodes!(input.into_children();
936
            [ActIdSet(actions), ProcExpr(expr)] => {
937
                Ok(ProcessExpr::Hide {
938
                    actions,
939
                    operand: Box::new(expr),
940
                })
941
            },
942
        )
943
    }
944

            
945
    fn ActionList(actions: ParseNode) -> ParseResult<Vec<Action>> {
946
        match_nodes!(actions.into_children();
947
            [Action(action), Action(actions)..] => {
948
                Ok(iter::once(action).chain(actions).collect())
949
            },
950
        )
951
    }
952

            
953
    fn MultiActTau(_input: ParseNode) -> ParseResult<()> {
954
        Ok(())
955
    }
956

            
957
    pub(crate) fn MultAct(input: ParseNode) -> ParseResult<MultiAction> {
958
        match_nodes!(input.into_children();
959
            [MultiActTau(_)] => {
960
                Ok(MultiAction { actions: Vec::new() })
961
            },
962
            [ActionList(actions)] => {
963
                Ok(MultiAction { actions })
964
            },
965
        )
966
    }
967

            
968
    fn CommExpr(action: ParseNode) -> ParseResult<Comm> {
969
        match_nodes!(action.into_children();
970
            [Id(id), MultActId(multiact), Id(to)] => {
971
                let mut actions = vec![id];
972
                actions.extend(multiact.actions);
973

            
974
                Ok(Comm {
975
                    from: MultiActionLabel { actions },
976
                    to
977
                })
978
            },
979
        )
980
    }
981

            
982
    fn CommExprList(actions: ParseNode) -> ParseResult<Vec<Comm>> {
983
        match_nodes!(actions.into_children();
984
            [CommExpr(action), CommExpr(actions)..] => {
985
                Ok(iter::once(action).chain(actions).collect())
986
            },
987
        )
988
    }
989

            
990
    fn CommExprSet(actions: ParseNode) -> ParseResult<Vec<Comm>> {
991
        match_nodes!(actions.into_children();
992
            [CommExprList(list)] => {
993
                Ok(list)
994
            },
995
        )
996
    }
997

            
998
    pub(crate) fn ProcExprRename(input: ParseNode) -> ParseResult<ProcessExpr> {
999
        match_nodes!(input.into_children();
            [RenExprSet(renames), ProcExpr(expr)] => {
                Ok(ProcessExpr::Rename {
                    renames,
                    operand: Box::new(expr),
                })
            },
        )
    }
    pub(crate) fn ProcExprComm(input: ParseNode) -> ParseResult<ProcessExpr> {
        match_nodes!(input.into_children();
            [CommExprSet(comm), ProcExpr(expr)] => {
                Ok(ProcessExpr::Comm {
                    comm,
                    operand: Box::new(expr),
                })
            },
        )
    }
    pub(crate) fn Action(input: ParseNode) -> ParseResult<Action> {
        match_nodes!(input.into_children();
            [Id(id), DataExprList(args)] => {
                Ok(Action { id, args })
            },
            [Id(id)] => {
                Ok(Action { id, args: Vec::new() })
            },
        )
    }
    fn RenExprSet(renames: ParseNode) -> ParseResult<Vec<Rename>> {
        match_nodes!(renames.into_children();
            [RenExprList(renames)] => {
                Ok(renames)
            },
        )
    }
    fn RenExprList(renames: ParseNode) -> ParseResult<Vec<Rename>> {
        match_nodes!(renames.into_children();
            [RenExpr(renames)..] => {
                Ok(renames.collect())
            },
        )
    }
    fn RenExpr(renames: ParseNode) -> ParseResult<Rename> {
        match_nodes!(renames.into_children();
            [Id(from), Id(to)] => {
                Ok(Rename { from, to })
            },
        )
    }
    pub(crate) fn ProcExprSum(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
        match_nodes!(input.into_children();
            [VarsDeclList(variables)] => {
                Ok(variables)
            },
        )
    }
    pub(crate) fn ProcExprDist(input: ParseNode) -> ParseResult<(Vec<VarDecl>, DataExpr)> {
        match_nodes!(input.into_children();
            [VarsDeclList(variables), DataExpr(expr)] => {
                Ok((variables, expr))
            },
        )
    }
    pub(crate) fn StateFrmDelay(input: ParseNode) -> ParseResult<StateFrm> {
        match_nodes!(input.into_children();
            [DataExpr(delay)] => {
                Ok(StateFrm::Delay(delay))
            },
        )
    }
    pub(crate) fn StateFrmYaled(input: ParseNode) -> ParseResult<StateFrm> {
        match_nodes!(input.into_children();
            [DataExpr(delay)] => {
                Ok(StateFrm::Yaled(delay))
            },
        )
    }
    pub(crate) fn StateFrmNegation(input: ParseNode) -> ParseResult<StateFrm> {
        match_nodes!(input.into_children();
            [StateFrm(state)] => {
                Ok(StateFrm::Unary { op: crate::StateFrmUnaryOp::Negation, expr: Box::new(state) })
            },
        )
    }
    pub(crate) fn StateFrmLeftConstantMultiply(input: ParseNode) -> ParseResult<DataExpr> {
        match_nodes!(input.into_children();
            [DataValExpr(expr)] => {
                Ok(expr)
            },
        )
    }
    pub(crate) fn StateFrmRightConstantMultiply(input: ParseNode) -> ParseResult<DataExpr> {
        match_nodes!(input.into_children();
            [DataValExpr(expr)] => {
                Ok(expr)
            },
        )
    }
    pub(crate) fn StateFrmDiamond(input: ParseNode) -> ParseResult<RegFrm> {
        match_nodes!(input.into_children();
            [RegFrm(formula)] => {
                Ok(formula)
            },
        )
    }
    pub(crate) fn StateFrmBox(input: ParseNode) -> ParseResult<RegFrm> {
        match_nodes!(input.into_children();
            [RegFrm(formula)] => {
                Ok(formula)
            },
        )
    }
    pub(crate) fn StateFrmSpec(spec: ParseNode) -> ParseResult<UntypedStateFrmSpec> {
        let mut map_declarations = Vec::new();
        let mut equation_declarations = Vec::new();
        let mut constructor_declarations = Vec::new();
        let mut sort_declarations = Vec::new();
        let mut action_declarations = Vec::new();
        let mut form_spec = None;
        let span = spec.as_span();
        for child in spec.into_children() {
            match child.as_rule() {
                Rule::StateFrmSpecElt => {
                    let element = child
                        .into_children()
                        .next()
                        .expect("StateFrmSpecElt has exactly one child");
                    match element.as_rule() {
                        Rule::ConsSpec => {
                            constructor_declarations.append(&mut Mcrl2Parser::ConsSpec(element)?);
                        }
                        Rule::MapSpec => {
                            map_declarations.append(&mut Mcrl2Parser::MapSpec(element)?);
                        }
                        Rule::EqnSpec => {
                            equation_declarations.append(&mut Mcrl2Parser::EqnSpec(element)?);
                        }
                        Rule::SortSpec => {
                            sort_declarations.append(&mut Mcrl2Parser::SortSpec(element)?);
                        }
                        Rule::ActSpec => {
                            action_declarations.append(&mut Mcrl2Parser::ActSpec(element)?);
                        }
                        _ => {
                            unimplemented!("Unexpected rule in StateFrmSpecElt: {:?}", element.as_rule());
                        }
                    }
                }
                Rule::StateFrm => {
                    if form_spec.is_some() {
                        return Err(Error::new_from_span(
                            ErrorVariant::CustomError {
                                message: "Multiple state formula specifications are not allowed".to_string(),
                            },
                            child.as_span(),
                        ));
                    }
                    form_spec = Some(Mcrl2Parser::StateFrm(child)?);
                }
                Rule::FormSpec => {
                    if form_spec.is_some() {
                        return Err(Error::new_from_span(
                            ErrorVariant::CustomError {
                                message: "Multiple state formula specifications are not allowed".to_string(),
                            },
                            child.as_span(),
                        ));
                    }
                    form_spec = Some(Mcrl2Parser::FormSpec(child)?);
                }
                Rule::EOI => {
                    // End of input
                    break;
                }
                _ => {
                    unimplemented!("Unexpected rule: {:?}", child.as_rule());
                }
            }
        }
        let data_specification = UntypedDataSpecification {
            map_declarations,
            equation_declarations,
            constructor_declarations,
            sort_declarations,
        };
        Ok(UntypedStateFrmSpec {
            data_specification,
            action_declarations,
            formula: form_spec.ok_or(Error::new_from_span(
                ErrorVariant::CustomError {
                    message: "No state formula found in the state formula specification".to_string(),
                },
                span,
            ))?,
        })
    }
    pub(crate) fn PbesExprForall(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
        match_nodes!(input.into_children();
            [VarsDeclList(vars)] => {
                Ok(vars)
            },
        )
    }
    pub(crate) fn PbesExprExists(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
        match_nodes!(input.into_children();
            [VarsDeclList(vars)] => {
                Ok(vars)
            },
        )
    }
    fn IdsDecl(decl: ParseNode) -> ParseResult<Vec<IdDecl>> {
        let span = decl.as_span();
        match_nodes!(decl.into_children();
            [IdList(identifiers), SortExpr(sort)] => {
20634
                let id_decls = identifiers.into_iter().map(|identifier| {
20634
                    IdDecl { identifier, sort: sort.clone(), span: span.into() }
20634
                }).collect();
                Ok(id_decls)
            },
        )
    }
    fn EqnSpec(spec: ParseNode) -> ParseResult<Vec<EqnSpec>> {
        let mut ids = Vec::new();
        match_nodes!(spec.into_children();
            [VarSpec(variables), EqnDecl(decls)..] => {
                ids.push(EqnSpec { variables, equations: decls.collect() });
            },
            [EqnDecl(decls)..] => {
                ids.push(EqnSpec { variables: Vec::new(), equations: decls.collect() });
            },
        );
        Ok(ids)
    }
    fn EqnDecl(decl: ParseNode) -> ParseResult<EqnDecl> {
        let span = decl.as_span();
        match_nodes!(decl.into_children();
            [DataExpr(condition), DataExpr(lhs), DataExpr(rhs)] => {
                Ok(EqnDecl { condition: Some(condition), lhs, rhs, span: span.into() })
            },
            [DataExpr(lhs), DataExpr(rhs)] => {
                Ok(EqnDecl { condition: None, lhs, rhs, span: span.into() })
            },
        )
    }
    fn StateFrm(input: ParseNode) -> ParseResult<StateFrm> {
        parse_statefrm(input.children().as_pairs().clone())
    }
    fn RegFrm(input: ParseNode) -> ParseResult<RegFrm> {
        parse_regfrm(input.children().as_pairs().clone())
    }
    fn StateVarDecl(input: ParseNode) -> ParseResult<StateVarDecl> {
        let span = input.as_span();
        match_nodes!(input.into_children();
            [Id(identifier), StateVarAssignmentList(arguments)] => {
                Ok(StateVarDecl {
                    identifier,
                    arguments,
                    span: span.into(),
                })
            },
            [Id(identifier)] => {
                Ok(StateVarDecl {
                    identifier,
                    arguments: Vec::new(),
                    span: span.into(),
                })
            }
        )
    }
    fn StateVarAssignmentList(input: ParseNode) -> ParseResult<Vec<StateVarAssignment>> {
        match_nodes!(input.into_children();
            [StateVarAssignment(assignments)..] => {
                Ok(assignments.collect())
            }
        )
    }
    fn StateVarAssignment(input: ParseNode) -> ParseResult<StateVarAssignment> {
        match_nodes!(input.into_children();
            [Id(identifier), SortExpr(sort), DataExpr(expr)] => {
                Ok(StateVarAssignment {
                    identifier,
                    sort,
                    expr,
                })
            }
        )
    }
    fn ActionRenameRuleSpec(spec: ParseNode) -> ParseResult<ActionRenameDecl> {
        unimplemented!();
    }
    fn FormSpec(input: ParseNode) -> ParseResult<StateFrm> {
        match_nodes!(input.into_children();
            [StateFrm(formula)] => {
                Ok(formula)
            },
        )
    }
    pub(crate) fn StateFrmSup(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
        match_nodes!(input.into_children();
            [VarsDeclList(variables)] => {
                Ok(variables)
            },
        )
    }
    pub(crate) fn StateFrmInf(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
        match_nodes!(input.into_children();
            [VarsDeclList(variables)] => {
                Ok(variables)
            },
        )
    }
    pub(crate) fn StateFrmSum(input: ParseNode) -> ParseResult<Vec<VarDecl>> {
        match_nodes!(input.into_children();
            [VarsDeclList(variables)] => {
                Ok(variables)
            },
        )
    }
    fn EOI(_input: ParseNode) -> ParseResult<()> {
        Ok(())
    }
}