use std::fmt::{self, Write};
use crate::{Formatter, Scope};
#[derive(Debug, Clone)]
pub struct IfDef {
sym: String,
then: Scope,
is_guard: bool,
other: Option<Scope>,
}
impl IfDef {
pub fn new(sym: &str) -> Self {
Self {
sym: sym.to_string(),
then: Scope::new(),
is_guard: false,
other: None,
}
}
pub fn then_scope(&mut self) -> &mut Scope {
&mut self.then
}
pub fn other_scope(&mut self) -> &mut Scope {
&mut self.then
}
pub fn guard(&mut self) -> &mut Self {
self.is_guard = true;
self
}
pub fn do_fmt(&self, fmt: &mut Formatter<'_>, only_decls: bool) -> fmt::Result {
writeln!(fmt, "\n")?;
if self.is_guard {
writeln!(fmt, "#ifndef {}", self.sym)?;
writeln!(fmt, "#define {} 1", self.sym)?;
} else {
writeln!(fmt, "#ifdef {}", self.sym)?;
}
self.then.do_fmt(fmt, only_decls)?;
if let Some(b) = &self.other {
writeln!(fmt, "#else // !{}", self.sym)?;
b.do_fmt(fmt, only_decls)?;
}
writeln!(fmt, "\n#endif // {}", self.sym)
}
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
self.do_fmt(fmt, false)
}
}