use std::fmt::{self, Write};
use crate::{Expr, Format, Formatter};
use tamacro::DisplayFromFormat;
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct StaticAssert {
pub cond: Expr,
pub message: String,
}
impl StaticAssert {
pub fn new(cond: Expr, message: String) -> Self {
Self { cond, message }
}
pub fn new_with_str(cond: Expr, message: &str) -> Self {
Self::new(cond, message.to_string())
}
}
impl Format for StaticAssert {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
let keyword = if fmt.c23_keywords() {
"static_assert"
} else {
"_Static_assert"
};
write!(fmt, "{keyword}(")?;
self.cond.format(fmt)?;
write!(fmt, ", \"{}\")", crate::escape::escape_c_str(&self.message))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
fn size_check() -> StaticAssert {
StaticAssert::new_with_str(
Expr::new_binary(
Expr::new_sizeof(Type::base(BaseType::TypeDef("Value".to_string()))),
BinOp::Eq,
Expr::Int(16),
),
"ABI: Value must be 16 bytes",
)
}
#[test]
fn c11_and_c23_spelling() {
let sa = size_check();
assert_eq!(
sa.to_string(),
"_Static_assert(sizeof(Value) == 16, \"ABI: Value must be 16 bytes\")"
);
let c23 = render(
&sa,
RenderOptions {
c23_keywords: true,
..Default::default()
},
);
assert_eq!(
c23,
"static_assert(sizeof(Value) == 16, \"ABI: Value must be 16 bytes\")"
);
}
#[test]
fn as_global_and_statement() {
let global = GlobalStatement::StaticAssert(size_check());
let scope = ScopeBuilder::new().global_statement(global).build();
assert_eq!(
scope.to_string(),
"_Static_assert(sizeof(Value) == 16, \"ABI: Value must be 16 bytes\");\n"
);
let block = BlockBuilder::new()
.statement(Statement::StaticAssert(size_check()))
.build();
assert_eq!(
block.to_string(),
"_Static_assert(sizeof(Value) == 16, \"ABI: Value must be 16 bytes\");\n"
);
}
}