use std::fmt::{self, Write};
use crate::escape::{escape_c_char, escape_c_str};
use crate::{Format, Formatter, Type};
use tamacro::{DisplayFromConstSymbol, DisplayFromFormat, FormatFromConstSymbol};
fn format_c_double(num: f64) -> String {
if num.is_nan() {
"NAN".to_string()
} else if num.is_infinite() {
if num < 0.0 {
"-INFINITY".to_string()
} else {
"INFINITY".to_string()
}
} else {
let s = format!("{num}");
if s.contains('.') || s.contains('e') || s.contains('E') {
s
} else {
format!("{s}.0")
}
}
}
fn format_c_float(num: f32) -> String {
if num.is_nan() {
"NAN".to_string()
} else if num.is_infinite() {
if num < 0.0 {
"-INFINITY".to_string()
} else {
"INFINITY".to_string()
}
} else {
let s = format!("{num}");
if s.contains('.') || s.contains('e') || s.contains('E') {
format!("{s}f")
} else {
format!("{s}.0f")
}
}
}
#[derive(Debug, Clone, DisplayFromFormat)]
pub enum Expr {
Int(i64),
UInt(u64),
Double(f64),
Float(f32),
Bool(bool),
Char(char),
Str(String),
Ident(String),
Binary {
left: Box<Expr>,
op: BinOp,
right: Box<Expr>,
},
Parenthesized { expr: Box<Expr> },
Unary { op: UnaryOp, expr: Box<Expr> },
Assign {
lvalue: Box<Expr>,
op: AssignOp,
value: Box<Expr>,
},
Ternary {
cond: Box<Expr>,
lexpr: Box<Expr>,
rexpr: Box<Expr>,
},
FnCall { name: Box<Expr>, args: Vec<Expr> },
MemAccess { expr: Box<Expr>, member: String },
PtrMemAccess { expr: Box<Expr>, member: String },
ArrIndex { arr: Box<Expr>, idx: Box<Expr> },
Cast { t: Type, expr: Box<Expr> },
SizeOf(Type),
AlignOf(Type),
OffsetOf {
t: Type,
member: String,
},
StrLit {
prefix: EncodingPrefix,
value: String,
},
CharLit {
prefix: EncodingPrefix,
value: char,
},
InitArr(Vec<(Option<usize>, Expr)>),
InitStruct(Vec<(Option<String>, Expr)>),
CompoundLiteral {
t: Type,
init: Box<Expr>,
},
IntLit {
value: i128,
base: IntBase,
suffix: IntSuffix,
},
Raw(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EncodingPrefix {
#[default]
None,
Wide,
Utf8,
Utf16,
Utf32,
}
impl EncodingPrefix {
pub fn as_str(self) -> &'static str {
match self {
EncodingPrefix::None => "",
EncodingPrefix::Wide => "L",
EncodingPrefix::Utf8 => "u8",
EncodingPrefix::Utf16 => "u",
EncodingPrefix::Utf32 => "U",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IntBase {
#[default]
Dec,
Hex,
Oct,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IntSuffix {
#[default]
None,
U,
L,
UL,
LL,
ULL,
}
impl IntSuffix {
fn as_str(self) -> &'static str {
match self {
IntSuffix::None => "",
IntSuffix::U => "U",
IntSuffix::L => "L",
IntSuffix::UL => "UL",
IntSuffix::LL => "LL",
IntSuffix::ULL => "ULL",
}
}
}
impl Expr {
pub fn new_ident(name: String) -> Self {
Self::Ident(name)
}
pub fn new_ident_with_str(name: &str) -> Self {
Self::new_ident(name.to_string())
}
pub fn new_null() -> Self {
Self::new_ident("NULL".to_string())
}
pub fn new_binary(left: Expr, op: BinOp, right: Expr) -> Self {
Self::Binary {
left: Box::new(left),
op,
right: Box::new(right),
}
}
pub fn new_parenthesized(expr: Expr) -> Self {
Self::Parenthesized {
expr: Box::new(expr),
}
}
pub fn new_unary(expr: Expr, op: UnaryOp) -> Self {
Self::Unary {
expr: Box::new(expr),
op,
}
}
pub fn new_assign(lvalue: Expr, op: AssignOp, value: Expr) -> Self {
Self::Assign {
lvalue: Box::new(lvalue),
op,
value: Box::new(value),
}
}
pub fn new_ternary(cond: Expr, lexpr: Expr, rexpr: Expr) -> Self {
Self::Ternary {
cond: Box::new(cond),
lexpr: Box::new(lexpr),
rexpr: Box::new(rexpr),
}
}
pub fn new_fn_call(name: Expr, args: Vec<Expr>) -> Self {
Self::FnCall {
name: Box::new(name),
args,
}
}
pub fn new_fn_call_with_name(name: String, args: Vec<Expr>) -> Self {
Self::FnCall {
name: Box::new(Self::Ident(name)),
args,
}
}
pub fn new_mem_access(expr: Expr, member: String) -> Self {
Self::MemAccess {
expr: Box::new(expr),
member,
}
}
pub fn new_mem_access_with_str(expr: Expr, member: &str) -> Self {
Self::new_mem_access(expr, member.to_string())
}
pub fn new_ptr_mem_access(expr: Expr, member: String) -> Self {
Self::PtrMemAccess {
expr: Box::new(expr),
member,
}
}
pub fn new_ptr_mem_access_with_str(expr: Expr, member: &str) -> Self {
Self::new_ptr_mem_access(expr, member.to_string())
}
pub fn new_arr_index(arr: Expr, idx: Expr) -> Self {
Self::ArrIndex {
arr: Box::new(arr),
idx: Box::new(idx),
}
}
pub fn new_cast(t: Type, expr: Expr) -> Self {
Self::Cast {
t,
expr: Box::new(expr),
}
}
pub fn new_compound_literal(t: Type, init: Expr) -> Self {
Self::CompoundLiteral {
t,
init: Box::new(init),
}
}
pub fn new_int_lit(value: i128, suffix: IntSuffix) -> Self {
Self::IntLit {
value,
base: IntBase::Dec,
suffix,
}
}
pub fn new_hex(value: i128, suffix: IntSuffix) -> Self {
Self::IntLit {
value,
base: IntBase::Hex,
suffix,
}
}
pub fn new_sizeof(t: Type) -> Self {
Self::SizeOf(t)
}
pub fn new_alignof(t: Type) -> Self {
Self::AlignOf(t)
}
pub fn new_offsetof(t: Type, member: &str) -> Self {
Self::OffsetOf {
t,
member: member.to_string(),
}
}
pub fn new_str_lit(prefix: EncodingPrefix, value: &str) -> Self {
Self::StrLit {
prefix,
value: value.to_string(),
}
}
pub fn new_char_lit(prefix: EncodingPrefix, value: char) -> Self {
Self::CharLit { prefix, value }
}
pub fn new_init_arr_in_order(exprs: Vec<Expr>) -> Self {
Self::InitArr(exprs.into_iter().map(|expr| (None, expr)).collect())
}
pub fn new_init_arr_designated(x: Vec<usize>, y: Vec<Expr>) -> Self {
assert!(x.len() == y.len());
Self::InitArr(x.into_iter().map(Some).zip(y).collect())
}
pub fn new_init_struct_in_order(exprs: Vec<Expr>) -> Self {
Self::InitStruct(exprs.into_iter().map(|expr| (None, expr)).collect())
}
pub fn new_init_struct_designated(x: Vec<String>, y: Vec<Expr>) -> Self {
assert!(x.len() == y.len());
Self::InitStruct(x.into_iter().map(Some).zip(y).collect())
}
}
const PREC_ASSIGN: u8 = 2; const PREC_TERNARY: u8 = 3; const PREC_LOGIC_OR: u8 = 4; const PREC_LOGIC_AND: u8 = 5; const PREC_BIT_OR: u8 = 6; const PREC_BIT_XOR: u8 = 7; const PREC_BIT_AND: u8 = 8; const PREC_EQ: u8 = 9; const PREC_REL: u8 = 10; const PREC_SHIFT: u8 = 11; const PREC_ADD: u8 = 12; const PREC_MUL: u8 = 13; const PREC_UNARY: u8 = 14; const PREC_POSTFIX: u8 = 15; const PREC_PRIMARY: u8 = 16;
impl BinOp {
pub fn precedence(&self) -> u8 {
use BinOp::*;
match self {
Mul | Div | Mod => PREC_MUL,
Add | Sub => PREC_ADD,
LShift | RShift => PREC_SHIFT,
LT | LTE | GT | GTE => PREC_REL,
Eq | NEq => PREC_EQ,
BitAnd => PREC_BIT_AND,
XOr => PREC_BIT_XOR,
BitOr => PREC_BIT_OR,
And => PREC_LOGIC_AND,
Or => PREC_LOGIC_OR,
}
}
}
impl Expr {
pub fn precedence(&self) -> u8 {
use Expr::*;
match self {
IntLit { value, .. } if *value < 0 => PREC_UNARY,
Int(n) if *n < 0 => PREC_UNARY,
Int(_)
| UInt(_)
| Double(_)
| Float(_)
| Bool(_)
| Char(_)
| Str(_)
| Ident(_)
| Parenthesized { .. }
| SizeOf(_)
| AlignOf(_)
| OffsetOf { .. }
| StrLit { .. }
| CharLit { .. }
| InitArr(_)
| InitStruct(_)
| CompoundLiteral { .. }
| IntLit { .. }
| Raw(_) => PREC_PRIMARY,
FnCall { .. } | MemAccess { .. } | PtrMemAccess { .. } | ArrIndex { .. } => {
PREC_POSTFIX
}
Unary { op, .. } if matches!(op, UnaryOp::Inc | UnaryOp::Dec) => PREC_POSTFIX,
Unary { .. } | Cast { .. } => PREC_UNARY,
Binary { op, .. } => op.precedence(),
Ternary { .. } => PREC_TERNARY,
Assign { .. } => PREC_ASSIGN,
}
}
fn fmt_paren_if(&self, fmt: &mut Formatter<'_>, parens: bool) -> fmt::Result {
if parens {
write!(fmt, "(")?;
self.format(fmt)?;
write!(fmt, ")")
} else {
self.format(fmt)
}
}
}
fn needs_separating_space(op: &str, operand: &str) -> bool {
matches!(
(op.chars().last(), operand.chars().next()),
(Some('-'), Some('-')) | (Some('+'), Some('+')) | (Some('&'), Some('&'))
)
}
fn format_comma_separated<T>(
fmt: &mut Formatter<'_>,
items: &[T],
mut each: impl FnMut(&mut Formatter<'_>, &T) -> fmt::Result,
) -> fmt::Result {
for (i, item) in items.iter().enumerate() {
if i > 0 {
write!(fmt, ", ")?;
}
each(fmt, item)?;
}
Ok(())
}
impl Format for Expr {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
use Expr::*;
match self {
Int(num) => write!(fmt, "{num}"),
UInt(num) => write!(fmt, "{num}u"),
Double(num) => write!(fmt, "{}", format_c_double(*num)),
Float(num) => write!(fmt, "{}", format_c_float(*num)),
Bool(b) => write!(fmt, "{}", if *b { "true" } else { "false" }),
Char(c) => write!(fmt, "'{}'", escape_c_char(*c)),
Str(s) => write!(fmt, "\"{}\"", escape_c_str(s)),
Ident(name) => write!(fmt, "{name}"),
Binary { left, op, right } => {
let p = op.precedence();
left.fmt_paren_if(fmt, left.precedence() < p)?;
write!(fmt, " ")?;
op.format(fmt)?;
write!(fmt, " ")?;
right.fmt_paren_if(fmt, right.precedence() <= p)
}
Parenthesized { expr } => {
write!(fmt, "(")?;
expr.format(fmt)?;
write!(fmt, ")")
}
Unary { op, expr } => {
if matches!(op, UnaryOp::Inc | UnaryOp::Dec) {
expr.fmt_paren_if(fmt, expr.precedence() < PREC_POSTFIX)?;
op.format(fmt)
} else {
op.format(fmt)?;
if expr.precedence() < PREC_UNARY {
write!(fmt, "(")?;
expr.format(fmt)?;
write!(fmt, ")")
} else {
let operand = crate::render(&**expr, fmt.options());
if needs_separating_space(&op.to_string(), &operand) {
write!(fmt, " ")?;
}
write!(fmt, "{operand}")
}
}
}
Assign { lvalue, op, value } => {
lvalue.fmt_paren_if(fmt, lvalue.precedence() <= PREC_ASSIGN)?;
write!(fmt, " ")?;
op.format(fmt)?;
write!(fmt, " ")?;
value.fmt_paren_if(fmt, value.precedence() < PREC_ASSIGN)
}
Ternary { cond, lexpr, rexpr } => {
cond.fmt_paren_if(fmt, cond.precedence() <= PREC_TERNARY)?;
write!(fmt, " ? ")?;
lexpr.format(fmt)?;
write!(fmt, " : ")?;
rexpr.fmt_paren_if(fmt, rexpr.precedence() < PREC_TERNARY)
}
FnCall { name, args } => {
name.fmt_paren_if(fmt, name.precedence() < PREC_POSTFIX)?;
write!(fmt, "(")?;
format_comma_separated(fmt, args, |fmt, arg| arg.format(fmt))?;
write!(fmt, ")")
}
MemAccess { expr, member } => {
expr.fmt_paren_if(fmt, expr.precedence() < PREC_POSTFIX)?;
write!(fmt, ".{member}")
}
PtrMemAccess { expr, member } => {
expr.fmt_paren_if(fmt, expr.precedence() < PREC_POSTFIX)?;
write!(fmt, "->{member}")
}
ArrIndex { arr, idx } => {
arr.fmt_paren_if(fmt, arr.precedence() < PREC_POSTFIX)?;
write!(fmt, "[")?;
idx.format(fmt)?;
write!(fmt, "]")
}
Cast { t, expr } => {
write!(fmt, "(")?;
t.format(fmt)?;
write!(fmt, ")")?;
expr.fmt_paren_if(fmt, expr.precedence() < PREC_UNARY)
}
SizeOf(t) => {
write!(fmt, "sizeof(")?;
t.format(fmt)?;
write!(fmt, ")")
}
AlignOf(t) => {
let kw = if fmt.c23_keywords() {
"alignof"
} else {
"_Alignof"
};
write!(fmt, "{kw}(")?;
t.format(fmt)?;
write!(fmt, ")")
}
OffsetOf { t, member } => {
write!(fmt, "offsetof(")?;
t.format(fmt)?;
write!(fmt, ", {member})")
}
StrLit { prefix, value } => {
write!(fmt, "{}\"{}\"", prefix.as_str(), escape_c_str(value))
}
CharLit { prefix, value } => {
write!(fmt, "{}'{}'", prefix.as_str(), escape_c_char(*value))
}
InitArr(v) => {
write!(fmt, "{{")?;
format_comma_separated(fmt, v, |fmt, (idx, expr)| {
if let Some(idx) = idx {
write!(fmt, "[{idx}]=")?;
}
expr.format(fmt)
})?;
write!(fmt, "}}")
}
InitStruct(v) => {
write!(fmt, "{{")?;
format_comma_separated(fmt, v, |fmt, (name, expr)| {
if let Some(name) = name {
write!(fmt, ".{name}=")?;
}
expr.format(fmt)
})?;
write!(fmt, "}}")
}
CompoundLiteral { t, init } => {
write!(fmt, "(")?;
t.format(fmt)?;
write!(fmt, ")")?;
init.format(fmt)
}
IntLit {
value,
base,
suffix,
} => {
let neg = *value < 0;
let mag = value.unsigned_abs();
if neg {
write!(fmt, "-")?;
}
match base {
IntBase::Dec => write!(fmt, "{mag}")?,
IntBase::Hex => write!(fmt, "0x{mag:X}")?,
IntBase::Oct => write!(fmt, "0{mag:o}")?,
}
write!(fmt, "{}", suffix.as_str())
}
Raw(s) => write!(fmt, "{s}"),
}
}
}
#[derive(Debug, Clone, DisplayFromConstSymbol, FormatFromConstSymbol)]
pub enum BinOp {
#[symbol = "+"]
Add,
#[symbol = "-"]
Sub,
#[symbol = "*"]
Mul,
#[symbol = "/"]
Div,
#[symbol = "%"]
Mod,
#[symbol = "=="]
Eq,
#[symbol = "!="]
NEq,
#[symbol = ">"]
GT,
#[symbol = "<"]
LT,
#[symbol = ">="]
GTE,
#[symbol = "<="]
LTE,
#[symbol = "&&"]
And,
#[symbol = "||"]
Or,
#[symbol = "&"]
BitAnd,
#[symbol = "|"]
BitOr,
#[symbol = "^"]
XOr,
#[symbol = "<<"]
LShift,
#[symbol = ">>"]
RShift,
}
#[derive(Debug, Clone, DisplayFromConstSymbol, FormatFromConstSymbol)]
pub enum UnaryOp {
#[symbol = "++"]
Inc,
#[symbol = "--"]
Dec,
#[symbol = "++"]
PreInc,
#[symbol = "--"]
PreDec,
#[symbol = "-"]
Neg,
#[symbol = "!"]
LogicNeg,
#[symbol = "~"]
BitNot,
#[symbol = "&"]
AddrOf,
#[symbol = "*"]
Deref,
}
#[derive(Debug, Clone, DisplayFromConstSymbol, FormatFromConstSymbol)]
pub enum AssignOp {
#[symbol = "="]
Assign,
#[symbol = "+="]
AddAssign,
#[symbol = "-="]
SubAssign,
#[symbol = "*="]
MulAssign,
#[symbol = "/="]
DivAssign,
#[symbol = "%="]
ModAssign,
#[symbol = "&="]
BitAndAssign,
#[symbol = "|="]
BitOrAssign,
#[symbol = "^="]
BitXOrAssign,
#[symbol = "<<="]
LShiftAssign,
#[symbol = ">>="]
RShiftAssign,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
#[test]
fn binary() {
let b = Expr::new_binary(
Expr::new_binary(Expr::Int(123), BinOp::LT, Expr::Int(321)),
BinOp::BitOr,
Expr::new_binary(Expr::Double(1.23), BinOp::Sub, Expr::Float(3.21)),
);
let res = "123 < 321 | 1.23 - 3.21f";
assert_eq!(b.to_string(), res);
}
#[test]
fn parenthesized() {
let p = Expr::new_binary(
Expr::Int(3),
BinOp::Mul,
Expr::new_parenthesized(Expr::new_binary(Expr::Int(123), BinOp::Add, Expr::Int(321))),
);
let res = "3 * (123 + 321)";
assert_eq!(p.to_string(), res);
}
#[test]
fn unary() {
let u = Expr::new_unary(
Expr::new_unary(
Expr::new_sizeof(Type::new(BaseType::Struct("some_struct".to_string())).build()),
UnaryOp::Inc,
),
UnaryOp::Neg,
);
let res = "-sizeof(struct some_struct)++";
assert_eq!(u.to_string(), res);
}
#[test]
fn assign() {
let a = Expr::new_assign(
Expr::Ident("abc".to_string()),
AssignOp::SubAssign,
Expr::Int(123),
);
let res = "abc -= 123";
assert_eq!(a.to_string(), res);
let b = Expr::new_assign(
Expr::Ident("abc".to_string()),
AssignOp::BitAndAssign,
Expr::Bool(false),
);
let res = "abc &= false";
assert_eq!(b.to_string(), res);
}
#[test]
fn ternary() {
let t = Expr::new_ternary(
Expr::Bool(true),
Expr::Str("hello".to_string()),
Expr::Str("olleh".to_string()),
);
let res = r#"true ? "hello" : "olleh""#;
assert_eq!(t.to_string(), res);
}
#[test]
fn fncall() {
let f = Expr::new_fn_call(Expr::Ident("some_func".to_string()), vec![]);
let res = "some_func()";
assert_eq!(f.to_string(), res);
let f2 = Expr::new_fn_call(
Expr::Ident("some_func".to_string()),
vec![
Expr::Char('a'),
Expr::new_sizeof(Type::new(BaseType::Char).build()),
],
);
let res2 = "some_func('a', sizeof(char))";
assert_eq!(f2.to_string(), res2);
}
#[test]
fn mem_access() {
let m = Expr::new_mem_access(Expr::Ident("person".to_string()), "age".to_string());
let res = "person.age";
assert_eq!(m.to_string(), res);
}
#[test]
fn ptr_mem_access() {
let m = Expr::new_ptr_mem_access_with_str(Expr::new_ident_with_str("person"), "age");
assert_eq!(m.to_string(), "person->age");
let chained = Expr::new_ptr_mem_access_with_str(
Expr::new_ptr_mem_access_with_str(Expr::new_ident_with_str("a"), "b"),
"c",
);
assert_eq!(chained.to_string(), "a->b->c");
let deref = Expr::new_ptr_mem_access_with_str(
Expr::new_unary(Expr::new_ident_with_str("pp"), UnaryOp::Deref),
"x",
);
assert_eq!(deref.to_string(), "(*pp)->x");
let mixed = Expr::new_mem_access_with_str(
Expr::new_ptr_mem_access_with_str(Expr::new_ident_with_str("node"), "next"),
"value",
);
assert_eq!(mixed.to_string(), "node->next.value");
}
#[test]
fn arr_index() {
let a = Expr::new_arr_index(Expr::Ident("some_arr".to_string()), Expr::Int(5));
let res = "some_arr[5]";
assert_eq!(a.to_string(), res);
}
#[test]
fn cast() {
let c = Expr::new_cast(
Type::new(BaseType::Void).make_pointer().build(),
Expr::Ident("something".to_string()),
);
let res = "(void *)something";
assert_eq!(c.to_string(), res);
}
#[test]
fn int_literals_with_suffixes() {
assert_eq!(Expr::new_int_lit(1, IntSuffix::ULL).to_string(), "1ULL");
assert_eq!(Expr::new_int_lit(-5, IntSuffix::L).to_string(), "-5L");
assert_eq!(Expr::new_hex(255, IntSuffix::U).to_string(), "0xFFU");
assert_eq!(Expr::new_hex(4096, IntSuffix::None).to_string(), "0x1000");
assert_eq!(
Expr::IntLit {
value: 42,
base: IntBase::Oct,
suffix: IntSuffix::None
}
.to_string(),
"052"
);
}
#[test]
fn compound_literal() {
let cl = Expr::new_compound_literal(
Type::base(BaseType::TypeDef("Point".to_string())),
Expr::new_init_struct_in_order(vec![Expr::Int(1), Expr::Int(2)]),
);
assert_eq!(cl.to_string(), "(Point){1, 2}");
let access = Expr::new_mem_access_with_str(cl, "x");
assert_eq!(access.to_string(), "(Point){1, 2}.x");
}
#[test]
fn encoding_prefixed_literals() {
assert_eq!(
Expr::new_str_lit(EncodingPrefix::Wide, "hi").to_string(),
"L\"hi\""
);
assert_eq!(
Expr::new_str_lit(EncodingPrefix::Utf8, "hi").to_string(),
"u8\"hi\""
);
assert_eq!(
Expr::new_str_lit(EncodingPrefix::Utf16, "hi").to_string(),
"u\"hi\""
);
assert_eq!(
Expr::new_str_lit(EncodingPrefix::Utf32, "hi").to_string(),
"U\"hi\""
);
assert_eq!(
Expr::new_char_lit(EncodingPrefix::Wide, 'x').to_string(),
"L'x'"
);
assert_eq!(
Expr::new_str_lit(EncodingPrefix::Wide, "a\"b").to_string(),
"L\"a\\\"b\""
);
}
#[test]
fn alignof_and_offsetof() {
let a = Expr::new_alignof(Type::base(BaseType::Int));
assert_eq!(a.to_string(), "_Alignof(int)");
let c23 = render(
&a,
RenderOptions {
c23_keywords: true,
..Default::default()
},
);
assert_eq!(c23, "alignof(int)");
let o = Expr::new_offsetof(Type::base(BaseType::Struct("S".to_string())), "field");
assert_eq!(o.to_string(), "offsetof(struct S, field)");
}
#[test]
fn c23_alignof_spelling_propagates_through_unary() {
let e = Expr::new_unary(Expr::new_alignof(Type::base(BaseType::Int)), UnaryOp::Neg);
assert_eq!(e.to_string(), "-_Alignof(int)");
let c23 = render(
&e,
RenderOptions {
c23_keywords: true,
..Default::default()
},
);
assert_eq!(c23, "-alignof(int)");
}
#[test]
fn prefix_and_postfix_inc_dec() {
let id = || Expr::new_ident_with_str("a");
assert_eq!(Expr::new_unary(id(), UnaryOp::Inc).to_string(), "a++");
assert_eq!(Expr::new_unary(id(), UnaryOp::Dec).to_string(), "a--");
assert_eq!(Expr::new_unary(id(), UnaryOp::PreInc).to_string(), "++a");
assert_eq!(Expr::new_unary(id(), UnaryOp::PreDec).to_string(), "--a");
let deref_post = Expr::new_unary(
Expr::new_unary(Expr::new_ident_with_str("p"), UnaryOp::Inc),
UnaryOp::Deref,
);
assert_eq!(deref_post.to_string(), "*p++");
}
#[test]
fn precedence_parenthesization() {
let a = || Box::new(Expr::Ident("a".to_string()));
let b = || Box::new(Expr::Ident("b".to_string()));
let c = || Box::new(Expr::Ident("c".to_string()));
let e = Expr::Binary {
left: a(),
op: BinOp::Add,
right: Box::new(Expr::Binary {
left: b(),
op: BinOp::Mul,
right: c(),
}),
};
assert_eq!(e.to_string(), "a + b * c");
let e = Expr::Binary {
left: Box::new(Expr::Binary {
left: a(),
op: BinOp::Add,
right: b(),
}),
op: BinOp::Mul,
right: c(),
};
assert_eq!(e.to_string(), "(a + b) * c");
let left_nested = Expr::Binary {
left: Box::new(Expr::Binary {
left: a(),
op: BinOp::Sub,
right: b(),
}),
op: BinOp::Sub,
right: c(),
};
assert_eq!(left_nested.to_string(), "a - b - c");
let right_nested = Expr::Binary {
left: a(),
op: BinOp::Sub,
right: Box::new(Expr::Binary {
left: b(),
op: BinOp::Sub,
right: c(),
}),
};
assert_eq!(right_nested.to_string(), "a - (b - c)");
}
#[test]
fn precedence_unary_and_mixed() {
let a = || Box::new(Expr::Ident("a".to_string()));
let b = || Box::new(Expr::Ident("b".to_string()));
let e = Expr::Unary {
op: UnaryOp::Deref,
expr: Box::new(Expr::Binary {
left: a(),
op: BinOp::Add,
right: b(),
}),
};
assert_eq!(e.to_string(), "*(a + b)");
let e = Expr::Unary {
op: UnaryOp::Neg,
expr: Box::new(Expr::Unary {
op: UnaryOp::Neg,
expr: a(),
}),
};
assert_eq!(e.to_string(), "- -a");
let e = Expr::FnCall {
name: Box::new(Expr::Unary {
op: UnaryOp::Deref,
expr: Box::new(Expr::Ident("fp".to_string())),
}),
args: vec![*a()],
};
assert_eq!(e.to_string(), "(*fp)(a)");
let e = Expr::MemAccess {
expr: Box::new(Expr::Unary {
op: UnaryOp::Deref,
expr: Box::new(Expr::Ident("p".to_string())),
}),
member: "x".to_string(),
};
assert_eq!(e.to_string(), "(*p).x");
}
#[test]
fn precedence_assign_and_ternary() {
let a = || Box::new(Expr::Ident("a".to_string()));
let b = || Box::new(Expr::Ident("b".to_string()));
let c = || Box::new(Expr::Ident("c".to_string()));
let e = Expr::Assign {
lvalue: a(),
op: AssignOp::Assign,
value: Box::new(Expr::Assign {
lvalue: b(),
op: AssignOp::Assign,
value: c(),
}),
};
assert_eq!(e.to_string(), "a = b = c");
let e = Expr::Ternary {
cond: a(),
lexpr: b(),
rexpr: Box::new(Expr::Assign {
lvalue: c(),
op: AssignOp::Assign,
value: Box::new(Expr::Int(0)),
}),
};
assert_eq!(e.to_string(), "a ? b : (c = 0)");
}
#[test]
fn sizeof() {
let s = Expr::new_sizeof(Type::new(BaseType::Struct("some_struct".to_string())).build());
let res = "sizeof(struct some_struct)";
assert_eq!(s.to_string(), res);
}
#[test]
fn init_arr() {
let i = Expr::new_init_arr_in_order(vec![Expr::Int(1), Expr::Int(3), Expr::Int(2)]);
let res = "{1, 3, 2}";
assert_eq!(i.to_string(), res);
let i2 = Expr::new_init_arr_designated(
vec![0, 1, 2],
vec![Expr::Float(1.1), Expr::Float(2.1), Expr::Float(4.4)],
);
let res2 = "{[0]=1.1f, [1]=2.1f, [2]=4.4f}";
assert_eq!(i2.to_string(), res2);
}
#[test]
fn init_struct() {
let i = Expr::new_init_struct_in_order(vec![
Expr::Str("abc".to_string()),
Expr::Int(15),
Expr::Char('x'),
]);
let res = "{\"abc\", 15, 'x'}";
assert_eq!(i.to_string(), res);
let i2 = Expr::new_init_struct_designated(
vec!["name".to_string(), "age".to_string()],
vec![Expr::Str("bichanna".to_string()), Expr::Int(18)],
);
let res2 = "{.name=\"bichanna\", .age=18}";
assert_eq!(i2.to_string(), res2);
}
#[test]
fn uint_suffix() {
assert_eq!(Expr::UInt(42).to_string(), "42u");
assert_eq!(
Expr::UInt(18446744073709551615).to_string(),
"18446744073709551615u"
);
}
#[test]
fn string_escaping() {
assert_eq!(
Expr::Str("a\"b\\c\nd".to_string()).to_string(),
r#""a\"b\\c\nd""#
);
assert_eq!(Expr::Str("x\0y".to_string()).to_string(), r#""x\000y""#);
}
#[test]
fn char_escaping() {
assert_eq!(Expr::Char('\n').to_string(), r"'\n'");
assert_eq!(Expr::Char('\'').to_string(), r"'\''");
assert_eq!(Expr::Char('\\').to_string(), r"'\\'");
assert_eq!(Expr::Char('a').to_string(), "'a'");
}
#[test]
fn float_literals() {
assert_eq!(Expr::Float(1.0).to_string(), "1.0f");
assert_eq!(Expr::Double(2.0).to_string(), "2.0");
assert_eq!(Expr::Float(0.5).to_string(), "0.5f");
assert_eq!(Expr::Double(3.5).to_string(), "3.5");
assert_eq!(Expr::Double(f64::INFINITY).to_string(), "INFINITY");
assert_eq!(Expr::Double(f64::NEG_INFINITY).to_string(), "-INFINITY");
assert_eq!(Expr::Float(f32::NAN).to_string(), "NAN");
}
}