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
//! Rust Statements
//! 
//! This module contains definitions associated with C statements interpreted inside Rust.
//! 
//! Important definitions:
//! - `RStmt`, which signifies a C style Rust statement
use std::{collections::VecDeque, fmt::Display};

use crate::{ccarp::error::{c2rust_err, safe_unwrap, unimpl_err, CCErr, Result}, ccarp_c::stmt::*};

use super::{defs::{print_vec, CastInto, Context, NoReturn, RFrom, RInto}, rustdecl::{form_unsafe_expr, RDecl, RType}, rustexpr::{RConstExpr, RExpr}};

/// Rust Statement
/// 
/// This signifies a Rust Statement, which can be one of:
/// - A Compound Statement
/// - An Expression Statement
/// - A Selection Statement
/// - An Iteration Statement
/// - A Jump Statement
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RStmt {
    Compound(CompoundRStmt),
    Expr(RExprStmt),
    Selection(RSelectionStmt),
    Iter(Option<RBlockItem>,RIterStmt),
    Jump(RJumpStmt)
}
impl RFrom<Statement> for RStmt {
    fn rfrom(value: Statement, context: &mut Context) -> Result<Self> {
        match value {
            Statement::Compound(compound_stmt) => Ok(Self::Compound(compound_stmt.rinto(context)?)),
            Statement::Expr(expr_stmt) => Ok(Self::Expr(expr_stmt.rinto(context)?)),
            Statement::Selection(selection_stmt) => Ok(Self::Selection(selection_stmt.rinto(context)?)),
            Statement::Iter(iter_stmt) => {
                let (block,iter)=iter_stmt.rinto(context)?;
                Ok(Self::Iter(block,iter))
            },
            Statement::Jump(jump_stmt) => Ok(Self::Jump(jump_stmt.rinto(context)?)),
            Statement::Labeled(_) => Err(unimpl_err!("Labeled Statements are unimplemented!")),
        }
    }
}
impl Display for RStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Compound(compound_rstmt) => write!(f,"{compound_rstmt}"),
            Self::Expr(rexpr_stmt) => write!(f,"{rexpr_stmt}"),
            Self::Selection(rselection_stmt) => write!(f,"{rselection_stmt}"),
            Self::Iter(rblock_item, riter_stmt) => {
                match rblock_item {
                    Some(item) => write!(f,"{item}\n{riter_stmt}"),
                    None => write!(f,"{riter_stmt}"),
                }
            },
            Self::Jump(rjump_stmt) => write!(f,"{rjump_stmt}"),
        }
    }
}

fn remove_last_break_from_stmt(s: Statement) -> Option<Statement> {
    match s {
        Statement::Labeled(labeled_stmt) => {
            match labeled_stmt {
                LabeledStmt::Label(..) => Some(Statement::Labeled(labeled_stmt)),
                LabeledStmt::Case(const_expr, statement) => {
                    let res=remove_last_break_from_stmt(*statement).unwrap_or(Statement::Compound(CompoundStmt(None)));
                    Some(Statement::Labeled(LabeledStmt::Case(const_expr, Box::new(res))))
                },
                LabeledStmt::Default(statement) => {
                    let res=remove_last_break_from_stmt(*statement).unwrap_or(Statement::Compound(CompoundStmt(None)));
                    Some(Statement::Labeled(LabeledStmt::Default(Box::new(res))))
                },
            }
        },
        Statement::Compound(compound_stmt) => {
            match compound_stmt.0 {
                Some(mut list) => {
                    if let Some(last)=list.0.pop() {
                        match last {
                            BlockItem::Decl(_) => list.0.push(last),
                            BlockItem::Stmt(statement) => {
                                if let Some(stmt)=remove_last_break_from_stmt(*statement) {
                                    list.0.push(BlockItem::Stmt(Box::new(stmt)));
                                }
                            },
                        }
                    }
                    Some(Statement::Compound(CompoundStmt(Some(list))))
                },
                None => Some(Statement::Compound(compound_stmt)),
            }
        },
        Statement::Jump(jump_stmt) => {
            match jump_stmt {
                JumpStmt::Break => None,
                _ => Some(Statement::Jump(jump_stmt))
            }
        },
        _ => Some(s)
    }
}

/// Rust Labeled Statement
/// 
/// This is only used inside a Match Statement. This signifies the body of
/// a match statement.
/// 
/// This can be either:
/// - A Pattern - `const-expr => statement`
/// - or a Default arm - `_ => statement`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RLabeledStmt {
    Pattern(Vec<RConstExpr>,RStmt),
    Default(RStmt)
}
impl RFrom<LabeledStmt> for RLabeledStmt {
    fn rfrom(value: LabeledStmt, context: &mut Context) -> Result<Self> {
        match value {
            LabeledStmt::Label(..) => Err(unimpl_err!("Labeled Statements are unimplemented!")),
            LabeledStmt::Case(const_expr, statement) => {
                let mut pattern=vec![RConstExpr::rfrom(const_expr, context)?];
                let mut q=VecDeque::new();
                q.push_back(*statement);
                let mut statement=None;
                while let Some(stmt)=q.pop_front() {
                    match stmt {
                        Statement::Labeled(labeled_stmt) => {
                            match labeled_stmt {
                                LabeledStmt::Label(..) => return Err(unimpl_err!("Labeled Statements are unimplemented!")),
                                LabeledStmt::Case(const_expr, stmt) => {
                                    pattern.push(RConstExpr::rfrom(const_expr, context)?);
                                    q.push_back(*stmt);
                                },
                                LabeledStmt::Default(statement) => {
                                    return Ok(Self::Default((*statement).rinto(context)?))
                                },
                            }
                        },
                        Statement::Compound(compound_stmt) => {
                            statement=Some(Statement::Compound(compound_stmt.clone()));
                            if let Some(list)=compound_stmt.0 {
                                for elem in list.0 {
                                    match elem {
                                        BlockItem::Decl(_) => break,
                                        BlockItem::Stmt(statement) => q.push_back(*statement),
                                    }
                                }
                            }
                        },
                        _ => {
                            statement=Some(stmt);
                            break;
                        }
                    }
                }
                let mut list=BlockItemList(vec![BlockItem::Stmt(Box::new(statement.unwrap_or(Statement::Compound(CompoundStmt(None)))))]);
                for stmt in q {
                    list.0.push(BlockItem::Stmt(Box::new(stmt)));
                }
                Ok(Self::Pattern(pattern, Statement::Compound(CompoundStmt(Some(list))).rinto(context)?))
            },
            LabeledStmt::Default(statement) => {
                Ok(Self::Default((*statement).rinto(context)?))
            },
        }
    }
}
impl Display for RLabeledStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pattern(items, rstmt) => write!(f,"{} => {rstmt},",print_vec(items, "|")),
            Self::Default(rstmt) => write!(f,"_ => {rstmt},"),
        }
    }
}

/// Rust Compound Statement
/// 
/// Consists of an optional List of Block Items.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct CompoundRStmt(pub Option<RBlockItemList>);
impl RFrom<CompoundStmt> for CompoundRStmt {
    fn rfrom(value: CompoundStmt, context: &mut Context) -> Result<Self> {
        Ok(Self(value.0.map(|x| x.rinto(context)).transpose()?))
    }
}
impl Display for CompoundRStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            Some(list) => write!(f,"{{\n{list}\n}}"),
            None => write!(f,"{{}}"),
        }
    }
}

/// Rust Block Item List
/// 
/// Consists of a List of Block Items.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RBlockItemList(pub Vec<RBlockItem>);
impl RFrom<BlockItemList> for RBlockItemList {
    fn rfrom(value: BlockItemList, context: &mut Context) -> Result<Self> {
        let mut v=vec![];
        for x in value.0 { v.push(x.rinto(context)?); }
        Ok(Self(v))
    }
}
impl Display for RBlockItemList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f,"{}",print_vec(&self.0, "\n"))
    }
}

/// Rust Block Item
/// 
/// Can be either:
/// - A Declaration
/// - or a Statement
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RBlockItem {
    Decl(RDecl),
    Stmt(Box<RStmt>)
}
impl RFrom<BlockItem> for RBlockItem {
    fn rfrom(value: BlockItem, context: &mut Context) -> Result<Self> {
        match value {
            BlockItem::Decl(declaration) => Ok(Self::Decl(declaration.rinto(context)?)),
            BlockItem::Stmt(statement) => Ok(Self::Stmt(Box::new((*statement).rinto(context)?))),
        }
    }
}
impl Display for RBlockItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Decl(rdecl) => write!(f,"{rdecl}"),
            Self::Stmt(rstmt) => write!(f,"{rstmt}"),
        }
    }
}

/// Rust Expression Statement
/// 
/// Consists of an optional Expression.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RExprStmt(pub Option<RExpr>);
impl RFrom<ExprStmt> for RExprStmt {
    fn rfrom(value: ExprStmt, context: &mut Context) -> Result<Self> {
        Ok(Self(value.0.map(|x| RExpr::rfrom(x, context).map(NoReturn::simplify)).transpose()?))
    }
}
impl Display for RExprStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            Some(expr) => write!(f,"{};",form_unsafe_expr(expr)),
            None => write!(f,""),
        }
    }
}

/// Rust Selection Statement
/// 
/// Can be one of:
/// - An If Statement - `if expr { statement }`
/// - An If-Else Statement - `if expr { statement } else { statement }`
/// - A Match Statement - `match expr { labeled-statement }`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RSelectionStmt {
    If(RExpr,Box<RStmt>),
    IfElse(RExpr,Box<RStmt>,Box<RStmt>),
    Match(RExpr,Vec<RLabeledStmt>)
}
impl RFrom<SelectionStmt> for RSelectionStmt {
    fn rfrom(value: SelectionStmt, context: &mut Context) -> Result<Self> {
        match value {
            SelectionStmt::If(expression, statement) => Ok(Self::If(RExpr::rfrom(expression, context)?.cast(&RType::Bool), Box::new((*statement).rinto(context)?))),
            SelectionStmt::IfElse(expression, statement, statement1) => Ok(Self::IfElse(RExpr::rfrom(expression, context)?.cast(&RType::Bool), Box::new((*statement).rinto(context)?), Box::new((*statement1).rinto(context)?))),
            SelectionStmt::Switch(expression, statement) => {
                let rexpr=RExpr::rfrom(expression, context)?;
                if let Statement::Compound(CompoundStmt(Some(list))) = *statement {
                    let mut arms=vec![];
                    let mut label_stmt: Option<LabeledStmt>=None;
                    for item in list.0 {
                        match &mut label_stmt {
                            Some(label) => {
                                match item {
                                    BlockItem::Stmt(statement) => {
                                        let breakless=remove_last_break_from_stmt(*statement.clone()).unwrap_or(Statement::Compound(CompoundStmt(None)));
                                        if *statement==breakless { label.push_statement(breakless); }
                                        else {
                                            label.push_statement(breakless);
                                            arms.push((safe_unwrap!(label_stmt;"Label Statement","Selection Statement")).rinto(context)?);
                                            label_stmt=None;
                                        }
                                    },
                                    BlockItem::Decl(decl) => label.push_declaration(decl),
                                }
                            },
                            None => {
                                if let BlockItem::Stmt(statement)=item {
                                    if let Statement::Labeled(labeled_stmt) = *statement {
                                        label_stmt=Some(labeled_stmt);
                                    }
                                }
                            }
                        }
                    }
                    Ok(Self::Match(rexpr, arms))
                }
                else { Ok(Self::Match(rexpr, vec![])) }
            },
        }
        
    }
}
impl Display for RSelectionStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::If(rexpr, rstmt) => write!(f,"if {} {{\n{rstmt}\n}}",form_unsafe_expr(rexpr)),
            Self::IfElse(rexpr, rstmt, rstmt1) => {
                write!(f,"if {} {{\n{rstmt}\n}} else {{\n{rstmt1}\n}}",form_unsafe_expr(rexpr))
            },
            Self::Match(rexpr, rlabeled_stmts) => write!(f,"match {} {{\n{}\n}}",form_unsafe_expr(rexpr),print_vec(rlabeled_stmts, "\n")),
        }
    }
}

macro_rules! embed_last_expr {
    ($expr:expr,$into:expr) => {
        match &mut *$into {
            Statement::Compound(compound_stmt) => {
                if let Some(val)=&mut compound_stmt.0 {
                    val.0.push($expr);
                }
                else { compound_stmt.0=Some(BlockItemList(vec![$expr]))}
            },
            _ => {
                $into=Box::new(Statement::Compound(CompoundStmt(Some(BlockItemList(vec![BlockItem::Stmt($into),$expr])))));
            }
        }
    };
}

/// Rust Iteration Statement
/// 
/// This can be either:
/// - A While Statement - `while expr { statement }`
/// - A Loop Statement - `loop { statement; if !expr { break; } }`
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RIterStmt {
    While(RExpr,Box<RStmt>),
    Loop(Box<RStmt>,Option<RExpr>)
}
impl RFrom<IterStmt> for (Option<RBlockItem>,RIterStmt) {
    fn rfrom(value: IterStmt, context: &mut Context) -> Result<Self> {
        match value {
            IterStmt::While(expression, statement) => Ok((None,RIterStmt::While(RExpr::rfrom(expression, context)?.cast(&RType::Bool), Box::new((*statement).rinto(context)?)))),
            IterStmt::DoWhile(statement, expression) => Ok((None,RIterStmt::Loop(Box::new((*statement).rinto(context)?), Some(RExpr::rfrom(expression, context)?.cast(&RType::Bool))))),
            IterStmt::For(expression, expression1, expression2, mut statement) => {
                let block=expression.map(|x| BlockItem::Stmt(Box::new(Statement::Expr(ExprStmt(Some(*x))))));
                embed_last_expr!(BlockItem::Stmt(Box::new(Statement::Expr(ExprStmt(expression2.map(|x| *x))))),statement);
                match expression1 {
                    Some(expr) => Ok((block.map(|x| x.rinto(context)).transpose()?,RIterStmt::While(RExpr::rfrom(*expr, context)?.cast(&RType::Bool), Box::new(RStmt::rfrom(*statement, context)?)))),
                    None => Ok((block.map(|x| x.rinto(context)).transpose()?,RIterStmt::Loop(Box::new(RStmt::rfrom(*statement, context)?),None))),
                }
            },
            IterStmt::ForDecl(declaration, expression, expression1, mut statement) => {
                let rust_decl=RDecl::rfrom(*declaration, context)?;
                embed_last_expr!(BlockItem::Stmt(Box::new(Statement::Expr(ExprStmt(expression1.map(|x| *x))))),statement);
                match expression {
                    Some(expr) => Ok((Some(RBlockItem::Decl(rust_decl)),RIterStmt::While((*expr).rinto(context)?, Box::new(RStmt::rfrom(*statement, context)?)))),
                    None => Ok((Some(RBlockItem::Decl(rust_decl)),RIterStmt::Loop(Box::new(RStmt::rfrom(*statement, context)?),None))),
                }
            },
        }
    }
}
impl Display for RIterStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::While(rexpr, rstmt) => write!(f,"while {} {{\n{rstmt}\n}}",form_unsafe_expr(rexpr)),
            Self::Loop(rstmt, rexpr) => {
                match rexpr {
                    Some(expr) => write!(f,"loop {{\n{rstmt}\nif (!{}) {{ break; }}\n}}",form_unsafe_expr(expr)),
                    None => write!(f,"loop {{\n{rstmt}\n}}"),
                }
            },
        }
    }
}

/// Rust Jump Statement
/// 
/// Can be one of:
/// - Continue
/// - Break
/// - Return
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RJumpStmt {
    Continue,
    Break,
    Return(Option<RExpr>),
    ExitcodeReturn(Option<RExpr>)
}
impl RFrom<JumpStmt> for RJumpStmt {
    fn rfrom(value: JumpStmt, context: &mut Context) -> Result<Self> {
        match value {
            JumpStmt::Goto(_) => Err(unimpl_err!("Goto Statements are unimplemented!")),
            JumpStmt::Continue => Ok(Self::Continue),
            JumpStmt::Break => Ok(Self::Break),
            JumpStmt::Return(expression) => {
                if matches!(context.return_type,RType::Unit) { Ok(Self::Return(expression.map(|x| x.rinto(context)).transpose()?)) }
                else if context.inside_main && context.return_type.is_numeric() {
                    Ok(Self::ExitcodeReturn(expression.map(|x| RExpr::rfrom(x, context).map(|y| y.cast(&RType::U8))).transpose()?))
                }
                else { Ok(Self::Return(expression.map(|x| RExpr::rfrom(x, context).map(|y| y.cast(&context.return_type))).transpose()?)) }
            }
        }
    }
}
impl Display for RJumpStmt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Continue => write!(f,"continue;"),
            Self::Break => write!(f,"break;"),
            Self::Return(rexpr) => {
                match rexpr {
                    Some(expr) => write!(f,"return {};",form_unsafe_expr(expr)),
                    None => write!(f,"return;"),
                }
            },
            Self::ExitcodeReturn(rexpr) => {
                match rexpr {
                    Some(expr) => write!(f,"return std::process::ExitCode::from({});",form_unsafe_expr(expr)),
                    None => write!(f,"return std::process::ExitCode::from(0);"),
                }
            }
        }
    }
}