use std::fmt::{self, Write};
use crate::*;
use tamacro::DisplayFromFormat;
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Scope {
pub doc: Option<DocComment>,
pub global_stmts: Vec<GlobalStatement>,
}
impl Scope {
pub fn new() -> ScopeBuilder {
ScopeBuilder::new()
}
}
impl Format for Scope {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
if let Some(doc) = &self.doc {
doc.format(fmt)?;
}
for stmt in &self.global_stmts {
stmt.format(fmt)?;
}
Ok(())
}
}
pub struct ScopeBuilder {
doc: Option<DocComment>,
global_stmts: Vec<GlobalStatement>,
}
impl Default for ScopeBuilder {
fn default() -> Self {
Self::new()
}
}
impl ScopeBuilder {
pub fn new() -> Self {
Self {
doc: None,
global_stmts: vec![],
}
}
pub fn doc(mut self, doc: DocComment) -> Self {
self.doc = Some(doc);
self
}
pub fn global_statements(mut self, global_stmts: Vec<GlobalStatement>) -> Self {
self.global_stmts = global_stmts;
self
}
pub fn global_statement(mut self, global_stmt: GlobalStatement) -> Self {
self.global_stmts.push(global_stmt);
self
}
pub fn new_line(self) -> Self {
self.global_statement(GlobalStatement::NewLine)
}
pub fn build(self) -> Scope {
Scope {
doc: self.doc,
global_stmts: self.global_stmts,
}
}
}
#[derive(Debug, Clone, DisplayFromFormat)]
pub enum GlobalStatement {
Comment(Comment),
Enum(Enum),
Struct(Struct),
Function(Function),
Union(Union),
Variable(Variable),
TypeDef(TypeDef),
ErrorDirective(ErrorDirective),
IfDefDirective(IfDefDirective),
IfDirective(IfDirective),
Include(Include),
LineDirective(LineDirective),
Macro(Macro),
PragmaDirective(PragmaDirective),
WarningDirective(WarningDirective),
Raw(String),
StaticAssert(StaticAssert),
Located {
loc: SourceLoc,
stmt: Box<GlobalStatement>,
},
NewLine,
}
impl GlobalStatement {
pub fn located(self, loc: SourceLoc) -> GlobalStatement {
GlobalStatement::Located {
loc,
stmt: Box::new(self),
}
}
}
impl Format for GlobalStatement {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
use GlobalStatement::*;
match self {
Comment(c) => c.format(fmt),
Enum(e) => e.format(fmt),
Struct(s) => s.format(fmt),
Function(f) => f.format(fmt),
Union(u) => u.format(fmt),
Variable(v) => {
v.format(fmt)?;
writeln!(fmt, ";")
}
TypeDef(t) => t.format(fmt),
ErrorDirective(e) => e.format(fmt),
IfDefDirective(i) => i.format(fmt),
IfDirective(i) => i.format(fmt),
Include(i) => i.format(fmt),
LineDirective(l) => l.format(fmt),
Macro(m) => m.format(fmt),
PragmaDirective(p) => p.format(fmt),
WarningDirective(w) => w.format(fmt),
Raw(r) => writeln!(fmt, "{r}"),
StaticAssert(sa) => {
sa.format(fmt)?;
writeln!(fmt, ";")
}
Located { loc, stmt } => {
fmt.sync_line(loc)?;
stmt.format(fmt)
}
NewLine => writeln!(fmt),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scope() {
let s = ScopeBuilder::new()
.global_statement(GlobalStatement::WarningDirective(
WarningDirectiveBuilder::new_with_str("some warning").build(),
))
.new_line()
.global_statement(GlobalStatement::Include(
IncludeBuilder::new_system_with_str("stdio.h").build(),
))
.build();
let res = r#"#warning "some warning"
#include <stdio.h>
"#;
assert_eq!(s.to_string(), res);
let s = ScopeBuilder::new()
.global_statements(vec![
GlobalStatement::Comment(CommentBuilder::new().comment_with_str("Hello").build()),
GlobalStatement::NewLine,
GlobalStatement::Function(
FunctionBuilder::new_with_str("some_func", Type::new(BaseType::Bool).build())
.body(
BlockBuilder::new()
.statement(Statement::Return(None))
.build(),
)
.doc(
DocCommentBuilder::new()
.line_str("this is a function")
.build(),
)
.build(),
),
])
.build();
let res = r#"// Hello
/// this is a function
bool some_func(void) {
return;
}
"#;
assert_eq!(s.to_string(), res);
}
#[test]
fn global_variable_terminated() {
let s = ScopeBuilder::new()
.global_statements(vec![
GlobalStatement::Variable(
VariableBuilder::new_with_str("counter", Type::new(BaseType::Int).build())
.value(Expr::Int(0))
.build(),
),
GlobalStatement::Variable(
VariableBuilder::new_with_str("flag", Type::new(BaseType::Bool).build())
.build(),
),
])
.build();
assert_eq!(s.to_string(), "int counter = 0;\nbool flag;\n");
}
}