use crate::{
Enum, Function, GlobalStatement, Include, IncludeBuilder, RenderOptions, ScopeBuilder, Struct,
TypeDef, Union, Variable, VariableBuilder,
};
#[derive(Debug, Clone)]
pub enum HeaderGuard {
PragmaOnce,
Ifndef(String),
}
#[derive(Debug, Clone)]
pub struct Module {
name: String,
guard: HeaderGuard,
self_include: bool,
header: Vec<GlobalStatement>,
source: Vec<GlobalStatement>,
}
impl Module {
pub fn new(name: &str) -> ModuleBuilder {
ModuleBuilder::new(name)
}
pub fn name(&self) -> &str {
&self.name
}
pub fn header_stmts(&self) -> &[GlobalStatement] {
&self.header
}
pub fn source_stmts(&self) -> &[GlobalStatement] {
&self.source
}
pub fn header(&self) -> String {
self.header_with(RenderOptions::default())
}
pub fn header_with(&self, opts: RenderOptions) -> String {
let body = render_with(&self.header, opts);
match &self.guard {
HeaderGuard::PragmaOnce => {
if body.is_empty() {
"#pragma once\n".to_string()
} else {
format!("#pragma once\n\n{body}")
}
}
HeaderGuard::Ifndef(g) => {
format!("#ifndef {g}\n#define {g}\n\n{body}\n#endif /* {g} */\n")
}
}
}
pub fn source(&self) -> String {
self.source_with(RenderOptions::default())
}
pub fn source_with(&self, opts: RenderOptions) -> String {
let body = render_with(&self.source, opts);
if self.self_include {
if body.is_empty() {
format!("#include \"{}.h\"\n", self.name)
} else {
format!("#include \"{}.h\"\n\n{body}", self.name)
}
} else {
body
}
}
}
fn render_with(stmts: &[GlobalStatement], opts: RenderOptions) -> String {
crate::render(
&ScopeBuilder::new()
.global_statements(stmts.to_vec())
.build(),
opts,
)
}
fn default_guard(name: &str) -> String {
let stem = name.rsplit(['/', '\\']).next().unwrap_or(name);
let stem = stem.split('.').next().unwrap_or(stem);
let mut out = String::new();
for ch in stem.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_uppercase());
} else {
out.push('_');
}
}
if out.is_empty() {
out.push_str("MODULE");
}
if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
out.insert(0, '_');
}
out.push_str("_H");
out
}
pub struct ModuleBuilder {
name: String,
guard: HeaderGuard,
self_include: bool,
header: Vec<GlobalStatement>,
source: Vec<GlobalStatement>,
}
impl ModuleBuilder {
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
guard: HeaderGuard::Ifndef(default_guard(name)),
self_include: true,
header: vec![],
source: vec![],
}
}
pub fn pragma_once(mut self) -> Self {
self.guard = HeaderGuard::PragmaOnce;
self
}
pub fn include_guard(mut self, macro_name: &str) -> Self {
self.guard = HeaderGuard::Ifndef(macro_name.to_string());
self
}
pub fn no_self_include(mut self) -> Self {
self.self_include = false;
self
}
pub fn header_stmt(mut self, stmt: GlobalStatement) -> Self {
self.header.push(stmt);
self
}
pub fn source_stmt(mut self, stmt: GlobalStatement) -> Self {
self.source.push(stmt);
self
}
pub fn header_include_system(self, path: &str) -> Self {
self.header_include_impl(IncludeBuilder::new_system_with_str(path).build())
}
pub fn header_include(self, path: &str) -> Self {
self.header_include_impl(IncludeBuilder::new_with_str(path).build())
}
pub fn source_include_system(self, path: &str) -> Self {
self.source_include_impl(IncludeBuilder::new_system_with_str(path).build())
}
pub fn source_include(self, path: &str) -> Self {
self.source_include_impl(IncludeBuilder::new_with_str(path).build())
}
fn header_include_impl(mut self, inc: Include) -> Self {
self.header.push(GlobalStatement::Include(inc));
self
}
fn source_include_impl(mut self, inc: Include) -> Self {
self.source.push(GlobalStatement::Include(inc));
self
}
pub fn typedef(mut self, td: TypeDef) -> Self {
self.header.push(GlobalStatement::TypeDef(td));
self
}
pub fn struct_(mut self, s: Struct) -> Self {
self.header.push(GlobalStatement::Struct(s));
self
}
pub fn enum_(mut self, e: Enum) -> Self {
self.header.push(GlobalStatement::Enum(e));
self
}
pub fn union_(mut self, u: Union) -> Self {
self.header.push(GlobalStatement::Union(u));
self
}
pub fn function(mut self, f: Function) -> Self {
if f.is_prototype() {
self.header.push(GlobalStatement::Function(f));
} else if f.storage.is_static() {
self.source.push(GlobalStatement::Function(f));
} else {
self.header
.push(GlobalStatement::Function(f.to_prototype()));
self.source.push(GlobalStatement::Function(f));
}
self
}
pub fn global(mut self, v: Variable) -> Self {
if v.storage.is_extern() {
self.header.push(GlobalStatement::Variable(v));
} else if v.storage.is_static() {
self.source.push(GlobalStatement::Variable(v));
} else {
let mut decl = VariableBuilder::new(v.name.clone(), v.t.clone()).make_extern();
if let Some(doc) = &v.doc {
decl = decl.doc(doc.clone());
}
self.header.push(GlobalStatement::Variable(decl.build()));
self.source.push(GlobalStatement::Variable(v));
}
self
}
pub fn header_newline(mut self) -> Self {
self.header.push(GlobalStatement::NewLine);
self
}
pub fn source_newline(mut self) -> Self {
self.source.push(GlobalStatement::NewLine);
self
}
pub fn header_raw(mut self, raw: &str) -> Self {
self.header.push(GlobalStatement::Raw(raw.to_string()));
self
}
pub fn source_raw(mut self, raw: &str) -> Self {
self.source.push(GlobalStatement::Raw(raw.to_string()));
self
}
pub fn build(self) -> Module {
Module {
name: self.name,
guard: self.guard,
self_include: self.self_include,
header: self.header,
source: self.source,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
fn defn(name: &str) -> Function {
FunctionBuilder::new_with_str(name, Type::new(BaseType::Int).build())
.param(ParameterBuilder::new_with_str("x", Type::new(BaseType::Int).build()).build())
.body(
BlockBuilder::new()
.statement(Statement::Return(Some(Expr::Ident("x".to_string()))))
.build(),
)
.build()
}
#[test]
fn header_and_source_split() {
let m = Module::new("math_utils")
.header_include_system("stdint.h")
.function(defn("identity"))
.build();
let header = m.header();
assert_eq!(
header,
"#ifndef MATH_UTILS_H\n#define MATH_UTILS_H\n\n#include <stdint.h>\nint identity(int x);\n\n#endif /* MATH_UTILS_H */\n"
);
let source = m.source();
assert_eq!(
source,
"#include \"math_utils.h\"\n\nint identity(int x) {\n return x;\n}\n"
);
}
#[test]
fn static_function_stays_in_source() {
let f = FunctionBuilder::new_with_str("helper", Type::new(BaseType::Void).build())
.make_static()
.body(BlockBuilder::new().build())
.build();
let m = Module::new("m").function(f).build();
assert!(!m.header().contains("helper"));
assert!(m.source().contains("static void helper(void)"));
}
#[test]
fn public_global_becomes_extern_in_header() {
let v = VariableBuilder::new_with_str("counter", Type::new(BaseType::Int).build())
.value(Expr::Int(0))
.build();
let m = Module::new("state").pragma_once().global(v).build();
let header = m.header();
assert_eq!(header, "#pragma once\n\nextern int counter;\n");
let source = m.source();
assert_eq!(source, "#include \"state.h\"\n\nint counter = 0;\n");
}
#[test]
fn prototype_goes_to_header_only() {
let proto = FunctionBuilder::new_with_str("f", Type::new(BaseType::Int).build()).build();
let m = Module::new("m").no_self_include().function(proto).build();
assert!(m.header().contains("int f(void);"));
assert_eq!(m.source(), "");
}
}