use std::fmt::{self, Write};
use std::io;
const DEFAULT_INDENT: usize = 2;
pub trait Format {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceLoc {
pub file: String,
pub line: u64,
}
impl SourceLoc {
pub fn new(file: impl Into<String>, line: u64) -> Self {
Self {
file: file.into(),
line,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AttrStyle {
#[default]
Gnu,
C23,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndentStyle {
Spaces(usize),
Tabs,
}
impl Default for IndentStyle {
fn default() -> Self {
IndentStyle::Spaces(DEFAULT_INDENT)
}
}
impl IndentStyle {
fn step(self) -> usize {
match self {
IndentStyle::Spaces(n) => n,
IndentStyle::Tabs => 1,
}
}
fn unit(self) -> char {
match self {
IndentStyle::Spaces(_) => ' ',
IndentStyle::Tabs => '\t',
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BraceStyle {
#[default]
Attach,
NextLine,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct RenderOptions {
pub line_directives: bool,
pub attr_style: AttrStyle,
pub c23_keywords: bool,
pub indent: IndentStyle,
pub brace_style: BraceStyle,
}
pub fn render<T: Format>(item: &T, opts: RenderOptions) -> String {
let mut dst = String::new();
let mut fmt = Formatter::with_options(&mut dst, opts);
let _ = item.format(&mut fmt);
dst
}
pub fn render_to<T: Format, W: fmt::Write>(
item: &T,
dst: &mut W,
opts: RenderOptions,
) -> fmt::Result {
let mut fmt = Formatter::with_options(dst, opts);
item.format(&mut fmt)
}
pub fn render_to_io<T: Format, W: io::Write>(
item: &T,
dst: &mut W,
opts: RenderOptions,
) -> io::Result<()> {
struct IoAdapter<'w, W: io::Write> {
w: &'w mut W,
err: Option<io::Error>,
}
impl<W: io::Write> fmt::Write for IoAdapter<'_, W> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.w.write_all(s.as_bytes()).map_err(|e| {
self.err = Some(e);
fmt::Error
})
}
}
let mut adapter = IoAdapter { w: dst, err: None };
let res = {
let mut fmt = Formatter::with_options(&mut adapter, opts);
item.format(&mut fmt)
};
if let Some(e) = adapter.err {
return Err(e);
}
res.map_err(|_| io::Error::other("formatting failed"))
}
pub struct Formatter<'a> {
dst: &'a mut dyn fmt::Write,
at_line_start: bool,
spaces: usize,
indent: usize,
indent_unit: char,
opts: RenderOptions,
last_loc: Option<SourceLoc>,
}
impl fmt::Debug for Formatter<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Formatter")
.field("spaces", &self.spaces)
.field("indent", &self.indent)
.field("opts", &self.opts)
.finish_non_exhaustive()
}
}
impl<'a> Formatter<'a> {
pub fn new<W: fmt::Write>(dst: &'a mut W) -> Self {
Self::with_options(dst, RenderOptions::default())
}
pub fn with_options<W: fmt::Write>(dst: &'a mut W, opts: RenderOptions) -> Self {
Self {
dst,
at_line_start: true,
spaces: 0,
indent: opts.indent.step(),
indent_unit: opts.indent.unit(),
opts,
last_loc: None,
}
}
pub fn attr_style(&self) -> AttrStyle {
self.opts.attr_style
}
pub fn c23_keywords(&self) -> bool {
self.opts.c23_keywords
}
pub(crate) fn options(&self) -> RenderOptions {
self.opts
}
pub(crate) fn current_indent(&self) -> usize {
self.spaces
}
pub fn line_directives_enabled(&self) -> bool {
self.opts.line_directives
}
pub fn sync_line(&mut self, loc: &SourceLoc) -> fmt::Result {
if !self.opts.line_directives {
return Ok(());
}
if self.last_loc.as_ref() == Some(loc) {
return Ok(());
}
if !self.is_start_of_line() {
writeln!(self)?;
}
writeln!(
self,
"#line {} \"{}\"",
loc.line,
crate::escape::escape_c_str(&loc.file)
)?;
self.last_loc = Some(loc.clone());
Ok(())
}
pub fn block<F>(&mut self, f: F) -> fmt::Result
where
F: FnOnce(&mut Self) -> fmt::Result,
{
match self.opts.brace_style {
BraceStyle::Attach => {
if !self.is_start_of_line() {
write!(self, " ")?;
}
}
BraceStyle::NextLine => {
if !self.is_start_of_line() {
writeln!(self)?;
}
}
}
writeln!(self, "{{")?;
self.indent(f)?;
write!(self, "}}")?;
Ok(())
}
pub fn indent<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.spaces += self.indent;
let res = f(self);
self.spaces -= self.indent;
res
}
pub fn is_start_of_line(&self) -> bool {
self.at_line_start
}
}
fn write_indent(dst: &mut dyn fmt::Write, unit: char, n: usize) -> fmt::Result {
const SPACES: &str = " "; const TABS: &str = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; let filler = if unit == '\t' { TABS } else { SPACES };
let mut remaining = n;
while remaining > 0 {
let take = remaining.min(filler.len());
dst.write_str(&filler[..take])?;
remaining -= take;
}
Ok(())
}
impl Write for Formatter<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
for (idx, line) in s.split('\n').enumerate() {
if idx != 0 {
self.dst.write_char('\n')?;
self.at_line_start = true;
}
if line.is_empty() {
continue;
}
if self.at_line_start {
write_indent(self.dst, self.indent_unit, self.spaces)?;
self.at_line_start = false;
}
self.dst.write_str(line)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{BaseType, BlockBuilder, Function, FunctionBuilder, Statement, Type};
fn sample() -> Function {
FunctionBuilder::new_with_str("f", Type::base(BaseType::Void))
.body(
BlockBuilder::new()
.statement(Statement::Return(None))
.build(),
)
.build()
}
#[test]
fn stream_to_fmt_write_matches_to_string() {
let f = sample();
let mut streamed = String::new();
render_to(&f, &mut streamed, RenderOptions::default()).unwrap();
assert_eq!(streamed, f.to_string());
}
#[test]
fn stream_to_io_write() {
let f = sample();
let mut bytes: Vec<u8> = Vec::new();
render_to_io(&f, &mut bytes, RenderOptions::default()).unwrap();
assert_eq!(String::from_utf8(bytes).unwrap(), f.to_string());
}
#[test]
fn indent_spaces_width() {
let f = sample();
let out = render(
&f,
RenderOptions {
indent: IndentStyle::Spaces(4),
..Default::default()
},
);
assert_eq!(out, "void f(void) {\n return;\n}\n");
}
#[test]
fn indent_tabs() {
let f = sample();
let out = render(
&f,
RenderOptions {
indent: IndentStyle::Tabs,
..Default::default()
},
);
assert_eq!(out, "void f(void) {\n\treturn;\n}\n");
}
#[test]
fn brace_style_next_line() {
let f = sample();
let out = render(
&f,
RenderOptions {
brace_style: BraceStyle::NextLine,
..Default::default()
},
);
assert_eq!(out, "void f(void)\n{\n return;\n}\n");
}
}