ccarp 0.1.2

(trans)Compile C And Rust Partially
Documentation
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
988
989
990
991
992
993
994
995
996
997
//! C Declarations
//! 
//! This module defines types associated with C declarations.
//! Important definitions include:
//! - `Declaration`, which signifies a C99 declaration
//! - `ParameterTypeList`, which signifies a list of parameters
//! - `InitialiserList`, which signifies an initialiser for arrays, structs and unions
use std::fmt::Display;

use pest::iterators::Pair;

use crate::{ccarp::error::{rule_err, rule_mismatch, safe_remove, safe_unwrap, CCErr, Result}, ccarp_rust::defs::sum};

use super::{defs::{list_ast, Rule, AST}, expr::{AssignmentExpr, ConstExpr}, tt::Identifier};

pub type NonEmptyVec<T>=Vec<T>;

/// C Declaration
/// 
/// These signify variable declarations and function prototypes in C99.
/// 
/// These consist of:
/// - Declaration Specifiers followed by an optional Init Declaration list - `declaration-specifiers init-declarator-list? ;`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Declaration(pub DeclarationSpecifiers, pub Option<InitDeclaratorList>); // declaration-specifiers init-declarator-list? ;
impl AST for Declaration {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::decl => {
                let mut inner=pair.into_inner();
                let specs=DeclarationSpecifiers::take(safe_unwrap!(inner.next(),"Declaration"))?;
                if let Some(pair)=inner.next() { Ok(Self(specs, Some(InitDeclaratorList::take(pair)?))) }
                else { Ok(Self(specs, None)) }
            },
            _ => Err(rule_mismatch!(pair))
        }
    }
}

/// C Declaration Specifier
/// 
/// These consist of:
/// - Specifiers - `spec spec ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct DeclarationSpecifiers(pub NonEmptyVec<Specifier>);   // spec spec ...
impl AST for DeclarationSpecifiers {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        let mut v=vec![];
        match pair.as_rule() {
            Rule::specs => {
                for pair in pair.into_inner() { v.push(Specifier::take(pair)?); }   // spec
                Ok(Self(v))
            },
            _ => Err(rule_mismatch!(pair,specs))
        }
    }
}

/// C Specifier
/// 
/// These can consist of:
/// - Storage Specifiers - `storage_spec`
/// - Type Specifiers - `type_spec`
/// - Type Definitions - `typedef`
/// - Type Qualifiers - `type_qual`
/// - Function Specifiers - `func_spec`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Specifier {
    Storage(StorageSpecifier),  // storage_spec
    Type(TypeSpecifier),        // type_spec
    Typedef(TypedefName),       // typedef
    TypeQ(TypeQualifier),       // type_qual
    Func(FuncSpecifier)         // func_spec
}
impl AST for Specifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::storage_spec => Ok(Self::Storage(StorageSpecifier::take(pair)?)), // storage_spec
            Rule::type_qual => Ok(Self::TypeQ(TypeQualifier::take(pair)?)),         // type_qual
            Rule::func_spec => Ok(Self::Func(FuncSpecifier::take(pair)?)),          // func_spec
            Rule::type_spec => Ok(Self::Type(TypeSpecifier::take(pair)?)),          // type_spec
            Rule::typedef_name => Ok(Self::Typedef(TypedefName::take(pair)?)),      // typedef
            _ => Err(rule_mismatch!(pair))
        }
    }
}

/// C Storage Specifier
/// 
/// These can signify:
/// - Typedef - `typedef`
/// - Extern - `extern`
/// - Static - `static`
/// - Auto - `auto`
/// - or Register - `register`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum StorageSpecifier {
    Typedef,
    Extern,
    Static,
    Auto,
    Register
}
impl AST for StorageSpecifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_str() {
            "typedef" => Ok(Self::Typedef),
            "extern" => Ok(Self::Extern),
            "static" => Ok(Self::Static),
            "auto" => Ok(Self::Auto),
            "register" => Ok(Self::Register),
            _ => Err(rule_mismatch!(pair))
        }
    }
}

/// C Type Specifier
/// 
/// These can signify one of the following:
/// - Void - `void`
/// - Char - `char`
/// - Short - `short`
/// - Int - `int`
/// - Long - `long`
/// - Float - `float`
/// - Double - `double`
/// - Signed - `signed`
/// - Unsigned - `usnigned`
/// - Bool - `_Bool`
/// - Complex - `_Complex`
/// - Imaginary - `_imaginary`
/// - Struct - `struct_specifier`
/// - Enum - `enum_specfier`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum TypeSpecifier {
    Void,
    Char,
    Short,
    Int,
    Long,
    Float,
    Double,
    Signed,
    Unsigned,
    Bool,
    Complex,
    Imaginary,
    Struct(Box<StructSpecifier>),
    Enum(Box<EnumSpecifier>),
}
impl AST for TypeSpecifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::type_spec => {
                match pair.as_str() {
                    "void" => Ok(Self::Void),
                    "char" => Ok(Self::Char),
                    "short" => Ok(Self::Short),
                    "int" => Ok(Self::Int),
                    "long" => Ok(Self::Long),
                    "float" => Ok(Self::Float),
                    "double" => Ok(Self::Double),
                    "signed" => Ok(Self::Signed),
                    "unsigned" => Ok(Self::Unsigned),
                    "_Bool" => Ok(Self::Bool),
                    "_Complex" => Ok(Self::Complex),
                    "_Imaginary" => Ok(Self::Imaginary),
                    _ => {
                        let pair=safe_unwrap!(pair.into_inner().next(),"Type Specifier");
                        match pair.as_rule() {
                            Rule::struct_spec => Ok(Self::Struct(Box::new(StructSpecifier::take(pair)?))),
                            Rule::enum_spec => Ok(Self::Enum(Box::new(EnumSpecifier::take(pair)?))),
                            _ => Err(rule_mismatch!(pair))
                        }
                    }
                }
            }
            _ => Err(rule_mismatch!(pair,type_spec))
        }
        
    }
}

/// C Type Definition
/// 
/// This signifies a C type definition which consists of a single identifier (`ident`).
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TypedefName(pub Identifier);
impl AST for TypedefName {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::typedef_name => {
                let pair=safe_unwrap!(pair.into_inner().next(),"Typedef Name");
                match pair.as_rule() {
                    Rule::tok_ident => Ok(Self(Identifier::take(pair)?)),   // ident
                    _ => Err(rule_mismatch!(pair,tok_ident))
                }
            },
            _ => Err(rule_mismatch!(pair,typedef_name))
        }
    }
}

/// C Type Qualifier
/// 
/// These can be:
/// - Const - `const`
/// - Restrict - `restrict`
/// - or Volatile - `volatile`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum TypeQualifier {
    Const,
    Restrict,
    Volatile
}
impl AST for TypeQualifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_str() {
            "const" => Ok(Self::Const),
            "restrict" => Ok(Self::Restrict),
            "volatile" => Ok(Self::Volatile),
            _ => Err(rule_mismatch!(pair))
        }
    }
}

/// C Function Specifier
/// 
/// These can only be:
/// - Inline - `inline`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum FuncSpecifier {
    Inline
}
impl AST for FuncSpecifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_str() {
            "inline" => Ok(Self::Inline),
            _ => Err(rule_mismatch!(pair))
        }
    }
}



/* # Declarators # */


/// C Init Declarator List
/// 
/// These consist of:
/// - Init Declarators - `init-declarator, init-declarator, ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct InitDeclaratorList(pub NonEmptyVec<InitDeclarator>); // init-declarator, init-declarator, ...
list_ast!(InitDeclaratorList : InitDeclarator where init_decl_list => init_decl);

/// C Init Declarator
/// 
/// These consist of:
/// - Declarators - `declarator.`
/// - or Declarators followed by Initialisers - `declarator = initializer`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum InitDeclarator {
    Decl(Box<Declarator>),               // declarator
    Assign(Box<Declarator>,Initialiser)  // declarator = initializer
}
impl AST for InitDeclarator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::init_decl => {
                let mut inner=pair.into_inner();
                let decl=Declarator::take(safe_unwrap!(inner.next(),"Init Declarator"))?;       // declarator
                if let Some(pair)=inner.next() { Ok(Self::Assign(Box::new(decl),Initialiser::take(pair)?)) }    // declarator = initializer
                else { Ok(Self::Decl(Box::new(decl))) }     // declarator
            },
            _ => Err(rule_mismatch!(pair,init_decl))
        }
    }
}

/// C Declarator
/// 
/// These consist of:
/// - Optional Pointers followed by a Direct Declarator - `pointer? direct-declarator`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Declarator(pub Option<Pointer>,pub Box<DirectDeclarator>);    // pointer? direct-declarator
impl AST for Declarator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::declarator => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Declarator");
                match pair.as_rule() {
                    Rule::direct_declarator => Ok(Self(None,Box::new(DirectDeclarator::take(pair)?))),      // direct-declarator
                    Rule::pointer => Ok(Self(Some(Pointer::take(pair)?),Box::new(DirectDeclarator::take(safe_unwrap!(inner.next(),"Declarator"))?))),   // pointer? direct-declarator
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,declarator))
        }
    }
}

/// C Direct Declarator
/// 
/// These consist of:
/// - Identifiers followed by Declarator Postfixes - `ident decl-postfix decl-postfix ...`
/// - or Declarators followed by Declarator Postfixes - `declarator decl-postfix decl-postfix ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DirectDeclarator {
    Ident(Identifier,Vec<DeclPostfix>),     // ident decl-postfix decl-postfix ...
    Decl(Box<Declarator>,Vec<DeclPostfix>), // declarator decl-postfix decl-postfix ...
}
impl AST for DirectDeclarator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        sum!(IdentOrDecl;Identifier;Declarator);
        match pair.as_rule() {
            Rule::direct_declarator => {
                let mut v=vec![];
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Direct Declarator");
                let ident_or_decl=
                match pair.as_rule() {
                    Rule::tok_ident => IdentOrDecl::A(Identifier::take(pair)?),     // ident
                    Rule::decl => IdentOrDecl::B(Declarator::take(pair)?),          // declarator
                    _ => return Err(rule_mismatch!(pair))
                };
                for pair in inner { v.push(DeclPostfix::take(pair)?) }  // decl-postfix decl-postfix ...
                match ident_or_decl {
                    IdentOrDecl::A(identifier) => Ok(Self::Ident(identifier, v)),           // ident decl-postfix decl-postfix ...
                    IdentOrDecl::B(declarator) => Ok(Self::Decl(Box::new(declarator), v)),  // declarator decl-postfix decl-postfix ...
                }
            },
            _ => Err(rule_mismatch!(pair,direct_declarator))
        }
    }
}

/// C Declarator Postfix
/// 
/// These consist of:
/// - Optional Type Qualifier Lists and optional Assignment Expressions - `[ type-qualifier-list? assignment-expression? ]`
/// - Optional Type Qualifier Lists and Assignment Expressions - `[ static type-qualifier-list? assignment-expression ]`
/// - Type Qualifier Lists and Assignment Expressions - `[ type-qualifier-list static assignment-expression ]`
/// - Optional Type Qualifier Lists - `[ type-qualifier-list? * ]`
/// - Parameter Type Lists - `( parameter-type-list )`
/// - or optional Identifier Lists - `( identifier-list? )`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DeclPostfix {
    Opt(Option<TypeQualifierList>,Option<Box<AssignmentExpr>>),  // [ type-qualifier-list? assignment-expression? ]
    Static(Option<TypeQualifierList>,Box<AssignmentExpr>),       // [ static type-qualifier-list? assignment-expression ] or [ type-qualifier-list static assignment-expression ]
    Point(Option<TypeQualifierList>),                            // [ type-qualifier-list? * ]
    Param(ParameterTypeList),                                    // ( parameter-type-list )
    IdentList(Option<IdentifierList>),                           // ( identifier-list? )
}
impl AST for DeclPostfix {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::decl_postfix => {
                let mut qual=None;  // type-qualifier-list?
                let mut bracket=false;  // [ ]
                let mut mul=false;      // *
                let mut stat=false;     // static
                for pair in pair.into_inner() {
                    match pair.as_rule() {
                        Rule::type_qual => qual=Some(TypeQualifierList::take(pair)?),                           // type-qualifier-list
                        Rule::assign_expr => {
                            if stat { return Ok(Self::Static(qual, Box::new(AssignmentExpr::take(pair)?))) }    // [ type-qualifier-list? static assignment-expression ]
                            return Ok(Self::Opt(qual, Some(Box::new(AssignmentExpr::take(pair)?))))             // [ type-qualifier-list? assignment-expression ]
                        },
                        Rule::param_type_list => return Ok(Self::Param(ParameterTypeList::take(pair)?)),        // ( parameter-type-list )
                        Rule::ident_list => return Ok(Self::IdentList(Some(IdentifierList::take(pair)?))),      // ( identifier-list )
                        Rule::op_br|Rule::cl_br => bracket=true,    // [ ]
                        Rule::mul => mul=true,                      // *
                        Rule::stat => stat=true,                    // static
                        _ => return Err(rule_mismatch!(pair))
                    }
                }
                if mul { Ok(Self::Point(qual)) }                // [ type-qualifier-list? * ]
                else if bracket { Ok(Self::Opt(qual, None)) }   // [ type-qualifier-list? ]
                else { Ok(Self::IdentList(None)) }              // ( )
            },
            _ => Err(rule_mismatch!(pair,decl_postfix))
        }
    }
}

/// C Pointer
/// 
/// These consist of:
/// - Optional Type Qualifier Lists - `* type-qualifier-list? * type-qualifier-list? ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Pointer(pub NonEmptyVec<Option<TypeQualifierList>>);    // * type-qualifier-list? * type-qualifier-list? ...
impl AST for Pointer {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::pointer => {
                let mut v=vec![];
                let mut elem=None;  // type-qualifier-list?
                for pair in pair.into_inner() {
                    match pair.as_rule() {
                        Rule::type_qual_list => elem=Some(TypeQualifierList::take(pair)?),  // type-qualifier-list
                        Rule::mul => { v.push(elem); elem=None },   // * type-qualifier-list? <- stored in `elem`
                        _ => return Err(rule_mismatch!(pair))
                    }
                }
                safe_remove(&mut v, 0, rule_mismatch!("Pointer",Some))?; // First push was elem::init (Pointer starts with *)
                v.push(elem);   // Last element was not in due to * pushing the previous element into v
                Ok(Self(v))
            },
            _ => Err(rule_mismatch!(pair,pointer))
        }
    }
}

/// C Type Qualifier List
/// 
/// These consist of:
/// - Type Qualifiers - `type-qualifier type-qualifier ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TypeQualifierList(pub NonEmptyVec<TypeQualifier>);       // type-qualifier type-qualifier ...
list_ast!(TypeQualifierList : TypeQualifier where type_qual_list => type_qual);

/// C Parameter Type List
/// 
/// These can consist of:
/// - Parameter Lists - `parameter-list`
/// - Parameter Lists followed by an ellipsis - `parameter-list , ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ParameterTypeList {
    List(ParameterList),        // parameter-list
    TripleDot(ParameterList)    // parameter-list , ...             // <- this is the exact syntax!
}
impl AST for ParameterTypeList {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::param_type_list => {
                let mut inner=pair.into_inner();
                let params=ParameterList::take(safe_unwrap!(inner.next(),"Parameter Type List"))?;  // parameter-list
                if inner.next().is_some() { Ok(Self::TripleDot(params)) }   // parameter-list , ...
                else { Ok(Self::List(params)) }                             // parameter-list
            },
            _ => Err(rule_mismatch!(pair,param_type_list))
        }
    }
}

/// C Parameter List
/// 
/// These consist of:
/// - Parameter Declarations - `parameter-declaration , parameter-declaration , ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ParameterList(pub NonEmptyVec<ParameterDeclaration>);    // parameter-declaration , parameter-declaration , ...
list_ast!(ParameterList : ParameterDeclaration where param_list => param_decl);

/// C Parameter Declaration
/// 
/// These can consist of:
/// - Declaration Specifiers followed by a Declarator - `declaration-specifiers declarator`
/// - or Declaration Specifiers followed by an optional Abstract Declarator - `declaration-specifiers abstract-declarator?`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ParameterDeclaration {
    Decl(DeclarationSpecifiers,Box<Declarator>),                         // declaration-specifiers declarator
    Abstract(DeclarationSpecifiers,Option<Box<AbstractDeclarator>>)      // declaration-specifiers abstract-declarator?
}
impl AST for ParameterDeclaration {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::param_decl => {
                let mut inner=pair.into_inner();
                let spec=DeclarationSpecifiers::take(safe_unwrap!(inner.next(),"Parameter Declaration"))?;  // declaration-specifiers
                if let Some(pair)=inner.next() {
                    match pair.as_rule() {
                        Rule::declarator => Ok(Self::Decl(spec,Box::new(Declarator::take(pair)?))),                             // declaration-specifiers declarator
                        Rule::abstract_declarator => Ok(Self::Abstract(spec,Some(Box::new(AbstractDeclarator::take(pair)?)))),  // declaration-specifiers abstract-declarator
                        _ => Err(rule_mismatch!(pair))
                    }
                }
                else { Ok(Self::Abstract(spec,None)) }  // declaration-specifiers
            },
            _ => Err(rule_mismatch!(pair,param_decl))
        }
    }
}

/// C Identifier List
/// 
/// These consist of:
/// - Identifiers - `ident , ident , ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct IdentifierList(pub NonEmptyVec<Identifier>);     // ident , ident , ...
list_ast!(IdentifierList : Identifier where ident_list => tok_ident);
impl From<ParameterTypeList> for IdentifierList {
    fn from(value: ParameterTypeList) -> Self {
        let list=
        match value {
            ParameterTypeList::List(parameter_list)|ParameterTypeList::TripleDot(parameter_list) => parameter_list,
        };
        let mut v=vec![];
        for decl in list.0 {
            if let ParameterDeclaration::Abstract(DeclarationSpecifiers(specs), None)=decl {
                if let [Specifier::Typedef(TypedefName(ident))]=&specs[..] {
                    v.push(ident.clone());
                }
            }
        }
        Self(v)
    }
}

/// C Type Name
/// 
/// These consist of:
/// - Specifier Qualifier Lists followed by an optional Abstract Declarator - `specifier-qualifier-list abstract-declarator?`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TypeName(pub SpecifierQualifierList,pub Option<Box<AbstractDeclarator>>);     // specifier-qualifier-list abstract-declarator?
impl AST for TypeName {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::type_name => {
                let mut inner=pair.into_inner();
                let list=SpecifierQualifierList::take(safe_unwrap!(inner.next(),"Type Name"))?; // specifier-qualifier-list <- store in `list`
                if let Some(pair)=inner.next() { Ok(Self(list, Some(Box::new(AbstractDeclarator::take(pair)?)))) }  // specifier-qualifier-list abstract-declarator
                else { Ok(Self(list,None)) }    // specifier-qualifier-list
            },
            _ => Err(rule_mismatch!(pair,type_name))
        }
    }
}

/// C Abstract Declarator
/// 
/// These can consist of:
/// - Pointers - `pointer`
/// - Optional Pointers followed be a Direct Abstract Declarator - `pointer? direct-abstract-declarator`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AbstractDeclarator {
    Pointer(Pointer),                                       // pointer
    Direct(Option<Pointer>,Box<DirectAbstractDeclarator>)   // pointer? direct-abstract-declarator
}
impl AST for AbstractDeclarator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::abstract_declarator => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Abstract Declarator");
                match pair.as_rule() {
                    Rule::direct_abstract_declarator => Ok(Self::Direct(None,Box::new(DirectAbstractDeclarator::take(pair)?))), // direct-abstract-declarator
                    Rule::pointer => {
                        let point=Pointer::take(pair)?;
                        if let Some(pair)=inner.next() { Ok(Self::Direct(Some(point),Box::new(DirectAbstractDeclarator::take(pair)?))) }    // pointer direct-abstract-declarator
                        else { Ok(Self::Pointer(point)) }       // pointer
                    },
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,abstract_declarator))
        }
    }
}

/// C Direct Abstract Declarator
/// 
/// These can consist of:
/// - Abstract Declarators - `( abstract-declarator )`
/// - Optional Abstract Declarators followed by Direct Abstract Declarator Postfixes - `abstract-declarator? direct-abstract-declarator-postfix ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DirectAbstractDeclarator {
    Abstract(Box<AbstractDeclarator>),                                                   // ( abstract-declarator )
    Post(Option<Box<AbstractDeclarator>>,NonEmptyVec<DirectAbstractDeclaratorPostfix>),  // abstract-declarator? direct-abstract-declarator-postfix ...
}
impl AST for DirectAbstractDeclarator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::direct_abstract_declarator => {
                let mut decl=None;  // abstract-declarator?
                let mut v=vec![];
                for pair in pair.into_inner() {
                    match pair.as_rule() {
                        Rule::abstract_declarator => decl=Some(AbstractDeclarator::take(pair)?),    // abstract-declarator <- store in `decl`
                        Rule::direct_abstract_declarator_postfix => v.push(DirectAbstractDeclaratorPostfix::take(pair)?),   // direct-abstract-declarator-postfix
                        _ => return Err(rule_mismatch!(pair))
                    }
                }
                if v.is_empty() { Ok(Self::Abstract(Box::new(safe_unwrap!(decl,"Direct Abstract Declarator")))) }   // ( abstract-declarator )
                else { Ok(Self::Post(decl.map(Box::new), v)) }                                                      // abstract-declarator? direct-abstract-declarator-postfix ...
            },
            _ => Err(rule_mismatch!(pair,direct_abstract_declarator))
        }
    }
}

/// C Direct Abstract Declarator Postfix
/// 
/// These can consist of:
/// - Optional Parameter Type Lists - `( parameter-type-list? )`
/// - Optional Assignment Expressions - `[ assignment-expression? ]`
/// - Nothing - `[ * ]`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DirectAbstractDeclaratorPostfix {
    Parent(Option<ParameterTypeList>),  // ( parameter-type-list? )
    Assign(Option<AssignmentExpr>),     // [ assignment-expression? ]
    Pointer                             // [ * ]
}
impl AST for DirectAbstractDeclaratorPostfix {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::direct_abstract_declarator_postfix => {
                let mut inner=pair.into_inner();
                let pair=inner.next();
                pair.map_or(Ok(Self::Parent(None)) /* ( ) */, |pair| match pair.as_rule() {
                        Rule::param_type_list => Ok(Self::Parent(Some(ParameterTypeList::take(pair)?))),    // ( parameter-type-list )
                        Rule::op_br => {
                            let pair=inner.next();
                            pair.map_or(Ok(Self::Assign(None)) /* [ ] */, |pair| match pair.as_rule() {
                                Rule::assign_expr => Ok(Self::Assign(Some(AssignmentExpr::take(pair)?))),   // [ assignment-expression ]
                                Rule::mul => Ok(Self::Pointer),                                             // [ * ]
                                _ => Err(rule_mismatch!(pair))
                            })
                        },
                        _ => Err(rule_mismatch!(pair))
                    })
            },
            _ => Err(rule_mismatch!(pair,direct_abstract_declarator_postfix))
        }
    }
}


/* # Initialisers # */


/// C Initialiser
/// 
/// These can consist of:
/// - Assignment Expressions - `assignment-expression`
/// - Initialiser Lists - `{ initializer-list }`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Initialiser {
    Assign(AssignmentExpr),     // assignment-expression
    Init(Box<InitialiserList>)  // { initializer-list } or { initializer-list , }
}
impl AST for Initialiser {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::init => {
                let pair=safe_unwrap!(pair.into_inner().next(),"Initialiser");
                match pair.as_rule() {
                    Rule::assign_expr => Ok(Self::Assign(AssignmentExpr::take(pair)?)),         // assignment-expression
                    Rule::init_list => Ok(Self::Init(Box::new(InitialiserList::take(pair)?))),  // { initializer-list }
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,init))
        }
    }
}

/// C Initialiser List
/// 
/// These consist of:
/// - Optional Designations followed by Initialisers - `designation? initializer , designation? initializer , ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct InitialiserList(pub NonEmptyVec<(Option<Designation>,Initialiser)>); // designation? initializer , designation? initializer , ...
impl AST for InitialiserList {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::init_list => {
                let mut v=vec![];
                let mut des=None;   // designation?
                for pair in pair.into_inner() {
                    match pair.as_rule() {
                        Rule::designation => des=Some(Designation::take(pair)?),    // designation
                        Rule::init => { v.push((des,Initialiser::take(pair)?)); des=None }, // designation? initializer
                        _ => return Err(rule_mismatch!(pair))
                    }
                }
                Ok(Self(v))
            },
            _ => Err(rule_mismatch!(pair,init_list))
        }
    }
}

/// C Designation
/// 
/// These consist of:
/// - Designator Lists - `designator-list =`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Designation(pub DesignatorList);             // designator-list =
impl AST for Designation {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::designation => {
                let pair=safe_unwrap!(pair.into_inner().next(),"Designator");
                match pair.as_rule() {
                    Rule::designator_list => Ok(Self(DesignatorList::take(pair)?)), // designator-list
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,designator))
        }
    }
}

/// C Designator List
/// 
/// These consist of:
/// - Designators - `designator designator ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct DesignatorList(pub NonEmptyVec<Designator>); // designator designator ...
list_ast!(DesignatorList : Designator where designator_list => designator);

/// C Designator
/// 
/// These can consist of:
/// - Constant Expressions (for arrays) - `[ constant-expression ]`
/// - Identifiers (for structs and unions) - `. ident`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Designator {
    Const(ConstExpr),           // [ constant-expression ]
    Ident(Identifier)           // . identifier
}
impl AST for Designator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::designator => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Designator");
                match pair.as_rule() {
                    Rule::tok_ident => Ok(Self::Ident(Identifier::take(pair)?)),    // [ constant-expression ]
                    Rule::const_expr => Ok(Self::Const(ConstExpr::take(pair)?)),    // . ident
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,designator))
        }
    }
}


/* # Struct and Union # */


/// C Struct (or Union) Specifier
/// 
/// These consists of:
/// - A Struct or Union Specifier followed by an optional Identifier and a Struct Declaration List - `struct-or-union identifier? { struct-declaration-list }`
/// - A Struct or Union Specifier followed by an Identifier - `struct-or-union identifier`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum StructSpecifier {
    Full(StructOrUnion,Option<Identifier>,Box<StructDeclarationList>), // struct-or-union identifier? { struct-declaration-list }
    Decl(StructOrUnion,Identifier)                                     // struct-or-union identifier
}
impl AST for StructSpecifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::struct_spec => {
                let mut inner=pair.into_inner();
                let str_uni=StructOrUnion::take(safe_unwrap!(inner.next(),"Struct Specifier"))?;
                let pair=safe_unwrap!(inner.next(),"Struct Specifier");
                match pair.as_rule() {
                    Rule::struct_declaration_list => Ok(Self::Full(str_uni, None, Box::new(StructDeclarationList::take(pair)?))),
                    Rule::tok_ident => {
                        let ident=Identifier::take(pair)?;
                        if let Some(pair)=inner.next() { Ok(Self::Full(str_uni, Some(ident), Box::new(StructDeclarationList::take(pair)?))) }
                        else { Ok(Self::Decl(str_uni, ident)) }
                    },
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,struct_spec))
        }
    }
}

/// C Struct or Union
/// 
/// These consists of:
/// - Struct - `struct`
/// - or Union - `union`
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum StructOrUnion {
    Struct,
    Union
}
impl AST for StructOrUnion {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_str() {
            "struct" => Ok(Self::Struct),
            "union" => Ok(Self::Union),
            _ => Err(rule_mismatch!(pair))
        }
    }
}
impl Display for StructOrUnion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Struct => write!(f,"struct"),
            Self::Union => write!(f,"union"),
        }
    }
}

/// C Struct Declaration List
/// 
/// These consists of:
/// - Struct Declarations - `struct-declaration ; struct-declaration ; ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct StructDeclarationList(pub NonEmptyVec<StructDeclaration>);   // struct-declaration ; struct-declaration ; ...
list_ast!(StructDeclarationList : StructDeclaration where struct_declaration_list => struct_declaration);

/// C Struct Declaration
/// 
/// These consists of:
/// - Specifier Qualifier Lists followed by Struct Declarator Lists - `specifier-qualifier-list struct-declarator-list`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct StructDeclaration(pub Box<SpecifierQualifierList>,pub StructDeclaratorList);  // specifier-qualifier-list struct-declarator-list
impl AST for StructDeclaration {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::struct_declaration => {
                let mut inner=pair.into_inner();
                let list=SpecifierQualifierList::take(safe_unwrap!(inner.next(),"Struct Declaration"))?;    // specifier-qualifier-list
                Ok(Self(Box::new(list),StructDeclaratorList::take(safe_unwrap!(inner.next(),"Struct Declaration"))?))               // specifier-qualifier-list struct-declarator-list
            },
            _ => Err(rule_mismatch!(pair,struct_declaration))
        }
    }
}

/// C Specifier Qualifier List
/// 
/// These consists of:
/// - Specifier Qualifiers - `specifier-qualifier specifier-qualifier ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct SpecifierQualifierList(pub Vec<SpecifierQualifier>); // type-specifier type-qualifier type-specifier ...
impl AST for SpecifierQualifierList {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        let mut v=vec![];
        match pair.as_rule() {
            Rule::spec_qual_list => {
                for pair in pair.into_inner() { v.push(SpecifierQualifier::take(pair)?); }  // specifier-qualifier
                Ok(Self(v))     // specifier-qualifier specifier-qualifier ...
            },
            _ => Err(rule_mismatch!(pair,spec_qual_list))
        }
    }
}

/// C Specifier Qualifier
/// 
/// These can consists of:
/// - Specifiers - `type_spec`
/// - Qualifiers - `type_qual`
/// - or Type definitions - `typedef`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum SpecifierQualifier {
    Spec(TypeSpecifier),    // type_spec
    Typedef(TypedefName),   // typedef
    Qualif(TypeQualifier)   // type_qual
}
impl AST for SpecifierQualifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::type_qual => Ok(Self::Qualif(TypeQualifier::take(pair)?)),    // type_qual
            Rule::type_spec => Ok(Self::Spec(TypeSpecifier::take(pair)?)),      // type_spec
            Rule::typedef_name => Ok(Self::Typedef(TypedefName::take(pair)?)),  // typedef
            _ => Err(rule_mismatch!(pair))
        }
    }
}

/// C Struct Declarator List
/// 
/// These consists of:
/// - Struct Declarators - `struct-declarator, struct-declarator, ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct StructDeclaratorList(pub NonEmptyVec<StructDeclarator>);     // struct-declarator, struct-declarator, ...
list_ast!(StructDeclaratorList : StructDeclarator where struct_declarator_list => struct_declarator);

/// C Struct Declarator
/// 
/// These consists of:
/// - Declarators - `declarator`
/// - Optional Declarators followed by Constant Expressions - `declarator? : constant-expression`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum StructDeclarator {
    Decl(Box<Declarator>),                        // declarator
    Const(Option<Box<Declarator>>,Box<ConstExpr>) // declarator? : constant-expression
}
impl AST for StructDeclarator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::struct_declarator => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Struct Declarator");
                match pair.as_rule() {
                    Rule::declarator => {
                        let decl=Declarator::take(pair)?;
                        if let Some(pair)=inner.next() { Ok(Self::Const(Some(Box::new(decl)), Box::new(ConstExpr::take(pair)?))) }  // declarator : const-expr
                        else { Ok(Self::Decl(Box::new(decl))) }     // declarator
                    },
                    Rule::const_expr => Ok(Self::Const(None, Box::new(ConstExpr::take(pair)?))),    // : const-expr
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,struct_declarator))
        }
    }
}

/* # Enum # */

/// C Enumerator Specifier
/// 
/// These consists of:
/// - Optional Identifiers with Enumerator Lists - `enum ident? { enum-list }`
/// - Identifiers - `enum ident`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum EnumSpecifier {
    Full(Option<Identifier>,Box<EnumeratorList>),    // enum identifier? { enumerator-list } or enum identifier? { enumerator-list , }
    Decl(Identifier)                                 // enum identifier
}
impl AST for EnumSpecifier {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::enum_spec => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Enum Specifier");
                match pair.as_rule() {
                    Rule::enum_list => Ok(Self::Full(None, Box::new(EnumeratorList::take(pair)?))), // enum { enum-list }
                    Rule::tok_ident => {
                        let ident=Identifier::take(pair)?;
                        if let Some(pair)=inner.next() { Ok(Self::Full(Some(ident), Box::new(EnumeratorList::take(pair)?))) } // enum ident { enum-list }
                        else { Ok(Self::Decl(ident)) } // enum ident
                    },
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,enum_spec))
        }
    }
}

/// C Enumerator List
/// 
/// This consists of:
/// - Enumerators - `enumerator, enumerator, ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct EnumeratorList(pub NonEmptyVec<Enumerator>); // enumerator, enumerator, ...
list_ast!(EnumeratorList : Enumerator where enum_list => enumerator);

/// C Enumerator Constant
/// 
/// This consists of:
/// - Enum Constant - `enum-const`
/// - Enum Constant with a Constant Expression - `enum-const = const-expr`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Enumerator {
    Const(EnumConst),                  // enumeration-constant
    ConstWithVal(EnumConst,Box<ConstExpr>)  // enumeration-constant = constant-expression
}
impl AST for Enumerator {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::enumerator => {
                let mut inner=pair.into_inner();
                let enum_const=EnumConst::take(safe_unwrap!(inner.next(),"Enumerator"))?;
                if let Some(const_expr)=inner.next() { Ok(Self::ConstWithVal(enum_const, Box::new(ConstExpr::take(const_expr)?))) } // enum-const = const-expr
                else { Ok(Self::Const(enum_const)) } // enum-const
            },
            _ => Err(rule_mismatch!(pair,enumerator))
        }
    }
}

/// C Enum Constant
/// 
/// This consists of:
/// - Identifier - `ident`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct EnumConst(pub Identifier);
impl AST for EnumConst {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::enum_const => {
                let pair=safe_unwrap!(pair.into_inner().next(),"Enum Constant");
                match pair.as_rule() {
                    Rule::tok_ident => Ok(Self(Identifier::take(pair)?)),
                    _ => Err(rule_mismatch!(pair,tok_ident))
                }
            },
            _ => Err(rule_mismatch!(pair,enum_const))
        }
    }
}