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
//! C Expressions
//! 
//! This module defines types associated with C expressions, which are parsed in 
//! a recursive manner. Important definitions include:
//! - `ConstExpr`, which signifies a(n unchecked) C99 constant expresssion
//! - `Expression`, which signifies a C99 expression
use pest::iterators::Pair;

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

use super::{decl::{InitialiserList, TypeName}, defs::{bin_ast, list_ast, Rule, AST}, tt::{Identifier, Literal}};


/// C Primary Expressions
/// 
/// These can be:
/// - Literals - `literal`
/// - Identifiers - `ident`
/// - or Expressions - `( expr )`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum PrimaryExpr {
    Literal(Literal),       // literal
    Ident(Identifier),      // ident
    Expr(Box<Expression>)   // ( expr )
}
impl AST for PrimaryExpr {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::primary_expr => {
                let pair=safe_unwrap!(pair.into_inner().next(),"Primary Expression");
                match pair.as_rule() {
                    Rule::tok_lit => Ok(Self::Literal(Literal::take(pair)?)),        // literal
                    Rule::tok_ident => Ok(Self::Ident(Identifier::take(pair)?)),     // ident
                    Rule::expr => Ok(Self::Expr(Box::new(Expression::take(pair)?))), // ( expr )
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,primary_expr))
        }
    }
}

/// C Argument Expression List
/// 
/// Helper struct for `Postfix`
/// 
/// Contains:
/// - Some Assignment Expressions - `assign_expr, assign_expr, ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ArgumentExprList(pub Vec<AssignmentExpr>);
list_ast!(ArgumentExprList : AssignmentExpr where arg_expr_list => assign_expr);
/// C Postfix
/// 
/// Helper enum for `PostfixExpr`.
/// 
/// Postfixes can contain:
/// - Expressions (indexing) - `[ expr ]`
/// - Argument Expression Lists (function call) - `( arg_expr_list )`
/// - Identifiers (field access) - `. ident`/`-> ident`
/// - Nothing (increment, decrement) - `++`/`--`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Postfix {
    Brackets(Box<Expression>),  // [ expr ]
    Function(ArgumentExprList), // ( arg_expr_list )
    Dot(Identifier),            // . ident
    Arrow(Identifier),          // -> ident
    Inc,                        // ++
    Dec,                        // --
}
impl AST for Postfix {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::postfix => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Postfix Expression");
                match pair.as_rule() {
                    Rule::expr => Ok(Self::Brackets(Box::new(Expression::take(pair)?))),  // [ expr ]
                    Rule::op_parent => {
                        let pair=safe_unwrap!(inner.next(),"Open Parenthesis");
                        match pair.as_rule() {
                            Rule::cl_parent => Ok(Self::Function(ArgumentExprList(vec![]))),                   // ( )
                            Rule::arg_expr_list => Ok(Self::Function(ArgumentExprList::take(pair)?)),          // ( arg_expr_list )
                            _ => Err(rule_mismatch!(pair))
                        }
                    }
                    Rule::dot => {
                        let pair=safe_unwrap!(inner.next(),"Right-hand-side of Postfix Expression");
                        if matches!(pair.as_rule(),Rule::tok_ident) { Ok(Self::Dot(Identifier::take(pair)?)) }  // . ident
                        else { Err(rule_mismatch!(pair,tok_ident)) }
                    },
                    Rule::arrow => {
                        let pair=safe_unwrap!(inner.next(),"Right-hand-side of Postfix Expression");
                        if matches!(pair.as_rule(),Rule::tok_ident) { Ok(Self::Arrow(Identifier::take(pair)?)) } // -> ident
                        else { Err(rule_mismatch!(pair,tok_ident)) }
                    }
                    Rule::inc => Ok(Self::Inc), // ++
                    Rule::dec => Ok(Self::Dec), // --
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,postfix))
        }
    }
}
/// C Postfix Expression
/// 
/// These can be:
/// - Primary Expressions with Postfixes (expression) - `primary postfix postfix ...`
/// - Type Names with Initialiser Lists (casted compound literals) - `(type) { init_list, init_list, ... }`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum PostfixExpr {
    Primary(Box<PrimaryExpr>,Vec<Postfix>),  // primary postfix postfix ...
    List(Box<TypeName>,Vec<InitialiserList>) // (type) { init_list, init_list, ... }
}
impl AST for PostfixExpr {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        sum!(PrimaryOrTy;PrimaryExpr;TypeName);
        let mut postfix=vec![];
        let mut init=vec![];
        match pair.as_rule() {
            Rule::postfix_expr => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Postfix Expression");
                let primary_or_ty=
                match pair.as_rule() {
                    Rule::primary_expr => PrimaryOrTy::A(PrimaryExpr::take(pair)?), // primary
                    Rule::type_name => PrimaryOrTy::B(TypeName::take(pair)?),       // type
                    _ => return Err(rule_mismatch!(pair))
                };
                for pair in inner {
                    match pair.as_rule() {
                        Rule::postfix => postfix.push(Postfix::take(pair)?),        // postfix
                        Rule::init_list => init.push(InitialiserList::take(pair)?), // init_list
                        _ => return Err(rule_mismatch!(pair))
                    }
                }
                match primary_or_ty {
                    PrimaryOrTy::A(primary_expr) => Ok(Self::Primary(Box::new(primary_expr), postfix)),
                    PrimaryOrTy::B(type_name) => Ok(Self::List(Box::new(type_name), init)),
                }
            },
            _ => Err(rule_mismatch!(pair,postfix_expr))
        }
    }
}

/// C Unary Expression
/// 
/// These can consist of:
/// - Postfix Expressions - `post_expr`
/// - Cast Expressions - `unary_op cast_expr`
/// - Unary Expressions - `++`/`--`/`sizeof` + `unary`
/// - Type Names - `sizeof ( type )`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum UnaryExpr {
    Postfix(Box<PostfixExpr>),
    Inc(Box<UnaryExpr>),            // ++ unary
    Dec(Box<UnaryExpr>),            // -- unary
    Ref(Box<CastExpr>),             // & cast
    Deref(Box<CastExpr>),           // * cast
    Plus(Box<CastExpr>),            // + cast
    Minus(Box<CastExpr>),           // - cast
    Bnot(Box<CastExpr>),            // ~ cast
    Not(Box<CastExpr>),             // ! cast
    Sizeof(Box<UnaryExpr>),         // sizeof unary
    SizeofType(Box<TypeName>)       // sizeof ( type )
}
impl AST for UnaryExpr {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        macro_rules! ret {
            ($i:ident, $ty:ty, $inner:expr, $e:expr) => {
                Ok(Self::$i(Box::new(<$ty>::take(safe_unwrap!($inner.next(),$e))?)))
            };
        }
        match pair.as_rule() {
            Rule::unary_expr => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Unary Expression");
                match pair.as_rule() {
                    Rule::postfix_expr => Ok(Self::Postfix(Box::new(PostfixExpr::take(pair)?))),
                    Rule::inc => ret!(Inc,Self,inner,"Unary Inc Expression"), // ++ unary
                    Rule::dec => ret!(Dec,Self,inner,"Unary Dec Expression"), // -- unary
                    Rule::sizeof => {
                        let pair=safe_unwrap!(inner.next(),"Unary Sizeof Expression");
                        match pair.as_rule() {
                            Rule::unary_expr => Ok(Self::Sizeof(Box::new(Self::take(pair)?))),        // sizeof unary
                            Rule::type_name => Ok(Self::SizeofType(Box::new(TypeName::take(pair)?))), // sizeof ( type )
                            _ => Err(rule_mismatch!(pair))
                        }
                    },
                    Rule::band => ret!(Ref,CastExpr,inner,"Unary Ref Expression"),      // & cast
                    Rule::mul => ret!(Deref,CastExpr,inner,"Unary Deref Expression"),   // * cast
                    Rule::plus => ret!(Plus,CastExpr,inner,"Unary Plus Expression"),    // + cast
                    Rule::minus => ret!(Minus,CastExpr,inner,"Unary Minus Expression"), // - cast
                    Rule::bnot => ret!(Bnot,CastExpr,inner,"Unary Bnot Expression"),    // ~ cast
                    Rule::not => ret!(Not,CastExpr,inner,"Unary Not Expression"),       // ! cast
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,unary_expr))
        }
    }
}

/// C Cast Expression
/// 
/// These can be:
/// - Unary Expressions - `unary`
/// - Type Names with Cast Expressions (cast) - `( type ) cast`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum CastExpr {
    Unary(UnaryExpr),
    Cast(Box<TypeName>,Box<CastExpr>)    // ( type ) cast
}
impl AST for CastExpr {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::cast_expr => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Cast Expression");
                match pair.as_rule() {
                    Rule::unary_expr => Ok(Self::Unary(UnaryExpr::take(pair)?)), // unary
                    Rule::type_name => Ok(
                        Self::Cast(Box::new(TypeName::take(pair)?),
                        Box::new(Self::take(safe_unwrap!(inner.next(),"Cast Expression"))?))
                    ), // ( type ) cast
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,cast_expr))
        }
    }
}

/// C Multiplicative Expression
/// 
/// These consist of:
/// - Cast Expressions inbetween Multiplicative Operators - `cast_expr * cast_expr % ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MulExpr(pub Box<CastExpr>,pub Vec<(MulOp,CastExpr)>);
bin_ast!(MulExpr : CastExpr where mul_expr => cast_expr, mul => MulOp::Mul, div => MulOp::Div, modulo => MulOp::Mod; if "MulExpr");
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum MulOp {
    #[default]
    Mul,
    Div,
    Mod
}

/// C Additive Expression
/// 
/// These consist of:
/// - Mutiplicative Expressions inbetween Additive Operators - `mul_expr + mul_expr - ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct AddExpr(pub Box<MulExpr>,pub Vec<(AddOp,MulExpr)>);
bin_ast!(AddExpr : MulExpr where add_expr => mul_expr, plus => AddOp::Add, minus => AddOp::Sub; if "AddExpr");
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum AddOp {
    #[default]
    Add,
    Sub
}

/// C Shift Expression
/// 
/// These consist of:
/// - Additive Expressions inbetween Shift Operators - `add_expr << add_expr >> ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ShiftExpr(pub Box<AddExpr>,pub Vec<(ShiftOp,AddExpr)>);
bin_ast!(ShiftExpr : AddExpr where shift_expr => add_expr, lshift => ShiftOp::LShift, rshift => ShiftOp::RShift; if "ShiftExpr");
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum ShiftOp {
    #[default]
    LShift,
    RShift
}

/// C Relational Expression
/// 
/// These consist of:
/// - Shift Expressions inbetween Relational Operators - `shift_expr <= shift_expr > ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RelExpr(pub Box<ShiftExpr>,pub Vec<(RelOp,ShiftExpr)>);
bin_ast!(RelExpr : ShiftExpr where rel_expr => shift_expr, gt => RelOp::Gt, lt => RelOp::Lt, gte => RelOp::Gte, lte => RelOp::Lte; if "RelExpr");
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum RelOp {
    #[default]
    Gt,
    Lt,
    Gte,
    Lte
}

/// C Equality Expression
/// 
/// These consist of:
/// - Relational Expressions inbetween Equality Operators - `rel_expr == rel_expr != ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct EqExpr(pub Box<RelExpr>,pub Vec<(EqOp,RelExpr)>);
bin_ast!(EqExpr : RelExpr where eq_expr => rel_expr, eq => EqOp::Eq, neq => EqOp::Neq; if "EqExpr");
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub enum EqOp {
    #[default]
    Eq,
    Neq
}

/// C And Expression
/// 
/// These consist of:
/// - Equality Expressions - `eq_expr & eq_expr & ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct AndExpr(pub Vec<EqExpr>);
list_ast!(AndExpr : EqExpr where and_expr => eq_expr);

/// C Xor Expression
/// 
/// These consist of:
/// - And Expressions - `and_expr ^ and_expr ^ ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct XorExpr(pub Vec<AndExpr>);
list_ast!(XorExpr : AndExpr where xor_expr => and_expr);

/// C Or Expression
/// 
/// These consist of:
/// - Xor Expressions - `xor_expr | xor_expr | ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct OrExpr(pub Vec<XorExpr>);
list_ast!(OrExpr : XorExpr where or_expr => xor_expr);

/// C Logical And Expression
/// 
/// These consist of:
/// - Or Expressions - `or_expr && or_expr && ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LogAndExpr(pub Vec<OrExpr>);
list_ast!(LogAndExpr : OrExpr where log_and_expr => or_expr);

/// C Logical Or Expression
/// 
/// These consist of:
/// - Logical And Expressions - `log_and_expr || log_and_expr || ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LogOrExpr(pub Vec<LogAndExpr>);
list_ast!(LogOrExpr : LogAndExpr where log_or_expr => log_and_expr);

/// C Conditional Expression (Ternary)
/// 
/// These consist of:
/// - Logical Or Expressions with Expressions followed by Logical Or Expressions - `log_or_expr ? expr : ... log_or_expr ? expr : log_or_expr`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct CondExpr(pub Vec<(LogOrExpr,Box<Expression>)>,pub Box<LogOrExpr>);
impl AST for CondExpr {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::cond_expr => {
                let mut last=None;
                let mut v=vec![];
                for pair in pair.into_inner() {
                    match pair.as_rule() {
                        Rule::log_or_expr => last=Some(LogOrExpr::take(pair)?), // log_or_expr
                        Rule::expr => { v.push(
                            (
                                safe_unwrap!(last,"Ternary Expression"),
                                Box::new(Expression::take(pair)?)
                            )
                        ); last=None; }, // log_or_expr ? expr :
                        _ => return Err(rule_mismatch!(pair))
                    }
                }
                Ok(Self(v,Box::new(safe_unwrap!(last,"Ternary Expression"))))
            },
            _ => Err(rule_mismatch!(pair,cond_expr))
        }
    }
}

/// C Constant Expression
/// 
/// This is an alias for `CondExpr`. In theory and in accordance with the C99 ISO, it
/// *shall not contain assignment, increment, decrement, function-call, or comma operators,
/// except when they are contained within a subexpression that is not evaluated.*
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ConstExpr(pub CondExpr);
impl AST for ConstExpr {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        match pair.as_rule() {
            Rule::const_expr => {
                let pair=safe_unwrap!(pair.into_inner().next(),"Constant Expression");
                match pair.as_rule() {
                    Rule::cond_expr => Ok(Self(CondExpr::take(pair)?)),
                    _ => Err(rule_mismatch!(pair,cond_expr))
                }
            },
            _ => Err(rule_mismatch!(pair,const_expr))
        }
    }
}

/// C Assignment Expression
/// 
/// These consist of:
/// - Conditional Expressions - `cond_expr`
/// - Unary Expressions and Assignment Expressions separated by an assignment operator - `unary = unary += ... /= cond_expr`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AssignmentExpr {
    Cond(CondExpr),
    Assign(UnaryExpr,Box<AssignmentExpr>),          // unary = assign
    MulAssign(UnaryExpr,Box<AssignmentExpr>),       // unary *= assign
    DivAssign(UnaryExpr,Box<AssignmentExpr>),       // unary /= assign
    ModAssign(UnaryExpr,Box<AssignmentExpr>),       // unary %= assign
    AddAssign(UnaryExpr,Box<AssignmentExpr>),       // unary += assign
    SubAssign(UnaryExpr,Box<AssignmentExpr>),       // unary -= assign
    LShiftAssign(UnaryExpr,Box<AssignmentExpr>),    // unary <<= assign
    RShiftAssign(UnaryExpr,Box<AssignmentExpr>),    // unary >>= assign
    AndAssign(UnaryExpr,Box<AssignmentExpr>),       // unary &= assign
    XorAssign(UnaryExpr,Box<AssignmentExpr>),       // unary ^= assign
    OrAssign(UnaryExpr,Box<AssignmentExpr>)         // unary |= assign
}
impl AST for AssignmentExpr {
    fn take(pair: Pair<Rule>) -> Result<Self> {
        macro_rules! ret {
            ($id:ident,$unary:expr,$inner:expr,$e:expr) => {
                Ok(Self::$id($unary, Box::new(Self::take(safe_unwrap!($inner.next(),$e))?)))
            };
        }
        match pair.as_rule() {
            Rule::assign_expr => {
                let mut inner=pair.into_inner();
                let pair=safe_unwrap!(inner.next(),"Assignment Expression");
                match pair.as_rule() {
                    Rule::cond_expr => Ok(Self::Cond(CondExpr::take(pair)?)),
                    Rule::unary_expr => {
                        let unary=UnaryExpr::take(pair)?;
                        let pair=safe_unwrap!(inner.next(),"Right-hand-side of Assignment Expression");
                        match pair.as_rule() {
                            Rule::assign => ret!(Assign,unary,inner,"Assign Expression"),
                            Rule::mul_assign => ret!(MulAssign,unary,inner,"MulAssign Expression"),
                            Rule::div_assign => ret!(DivAssign,unary,inner,"DivAssign Expression"),
                            Rule::mod_assign => ret!(ModAssign,unary,inner,"ModAssign Expression"),
                            Rule::add_assign => ret!(AddAssign,unary,inner,"AddAssign Expression"),
                            Rule::sub_assign => ret!(SubAssign,unary,inner,"SubAssign Expression"),
                            Rule::lshift_assign => ret!(LShiftAssign,unary,inner,"LShiftAssign Expression"),
                            Rule::rshift_assign => ret!(RShiftAssign,unary,inner,"RShiftAssign Expression"),
                            Rule::and_assign => ret!(AndAssign,unary,inner,"AndAssign Expression"),
                            Rule::xor_assign => ret!(XorAssign,unary,inner,"XorAssign Expression"),
                            Rule::or_assign => ret!(OrAssign,unary,inner,"OrAssign Expression"),
                            _ => Err(rule_mismatch!(pair))
                        }
                    },
                    _ => Err(rule_mismatch!(pair))
                }
            },
            _ => Err(rule_mismatch!(pair,assign_expr))
        }
    }
}

/// C Expression
/// 
/// These signify general expressions and variable modification in C99.
/// 
/// These consist of:
/// - Assignment Expressions - `assign, assign, ...`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Expression(pub Vec<AssignmentExpr>);
list_ast!(Expression : AssignmentExpr where expr => assign_expr);