Skip to main content

oxilean_codegen/c_backend/
cexpr_traits.rs

1//! # CExpr - Trait Implementations
2//!
3//! This module contains trait implementations for `CExpr`.
4//!
5//! ## Implemented Traits
6//!
7//! - `Display`
8//!
9//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)
10
11use crate::lcnf::*;
12
13use super::types::CExpr;
14use std::fmt;
15
16impl fmt::Display for CExpr {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        match self {
19            CExpr::Var(name) => write!(f, "{}", name),
20            CExpr::IntLit(n) => write!(f, "{}LL", n),
21            CExpr::UIntLit(n) => write!(f, "{}ULL", n),
22            CExpr::StringLit(s) => {
23                write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
24            }
25            CExpr::Call(name, args) => {
26                write!(f, "{}(", name)?;
27                for (i, a) in args.iter().enumerate() {
28                    if i > 0 {
29                        write!(f, ", ")?;
30                    }
31                    write!(f, "{}", a)?;
32                }
33                write!(f, ")")
34            }
35            CExpr::BinOp(op, lhs, rhs) => write!(f, "({} {} {})", lhs, op, rhs),
36            CExpr::UnaryOp(op, expr) => write!(f, "({}{})", op, expr),
37            CExpr::FieldAccess(expr, field, is_arrow) => {
38                if *is_arrow {
39                    write!(f, "{}->{}", expr, field)
40                } else {
41                    write!(f, "{}.{}", expr, field)
42                }
43            }
44            CExpr::ArrayAccess(arr, idx) => write!(f, "{}[{}]", arr, idx),
45            CExpr::Cast(ty, expr) => write!(f, "(({})({})", ty, expr),
46            CExpr::SizeOf(ty) => write!(f, "sizeof({})", ty),
47            CExpr::Null => write!(f, "NULL"),
48            CExpr::Ternary(cond, t, e) => write!(f, "({} ? {} : {})", cond, t, e),
49            CExpr::Initializer(ty, fields) => {
50                write!(f, "({})", ty)?;
51                write!(f, "{{")?;
52                for (i, (name, val)) in fields.iter().enumerate() {
53                    if i > 0 {
54                        write!(f, ", ")?;
55                    }
56                    write!(f, ".{} = {}", name, val)?;
57                }
58                write!(f, "}}")
59            }
60        }
61    }
62}