use crate::graph::Graph;
use crate::projection::domain::ir::DomainIr;
use crate::projection::sink::ArtifactSink;
use std::collections::BTreeMap;
pub fn emit(
graph: &Graph,
model_ref: &str,
created_at: Option<String>,
sink: &mut ArtifactSink,
) -> Result<Vec<String>, String> {
let ir = DomainIr::from_graph(graph)?;
let created_at = created_at.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
let files: Vec<(String, String)> = vec![
("Cargo.toml".to_string(), cargo_toml(&ir)),
("README.md".to_string(), readme(&ir, model_ref, &created_at)),
("src/lib.rs".to_string(), lib_rs(&ir)),
("src/value_objects.rs".to_string(), value_objects(&ir)),
("src/roles.rs".to_string(), roles(&ir)),
("src/entities.rs".to_string(), entities(&ir)),
("src/errors.rs".to_string(), errors(&ir)),
("src/commands.rs".to_string(), commands(&ir)),
("src/events.rs".to_string(), events(&ir)),
("src/aggregates.rs".to_string(), aggregates(&ir)),
("src/ports.rs".to_string(), ports(&ir)),
("src/container.rs".to_string(), container(&ir)),
("tests/smoke.rs".to_string(), smoke(&ir)),
];
let mut emitted = Vec::new();
for (path, body) in &files {
sink.write(path, body)?;
emitted.push(path.clone());
}
Ok(emitted)
}
pub fn project_domain_rust_in_memory(
graph: &Graph,
model_ref: &str,
created_at: Option<String>,
) -> Result<BTreeMap<String, String>, String> {
let mut map = BTreeMap::new();
let mut sink = ArtifactSink::Memory {
prefix: String::new(),
map: &mut map,
};
emit(graph, model_ref, created_at, &mut sink)?;
Ok(map)
}
fn cargo_toml(ir: &DomainIr) -> String {
format!(
"[package]\nname = \"{slug}_domain\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\
[dependencies]\n\n[workspace]\n",
slug = ir.package_slug
)
}
fn readme(ir: &DomainIr, model_ref: &str, created_at: &str) -> String {
format!(
"# {ns} domain crate\n\nGenerated by DomainForge from `{model_ref}` at {created_at}.\n\n\
A complete, zero-dependency DDD/CQRS domain layer (Rust) up to the port boundary.\n\
Validate with `cargo check` and `cargo test`.\n",
ns = ir.namespace,
model_ref = model_ref,
created_at = created_at,
)
}
fn lib_rs(ir: &DomainIr) -> String {
let mut s = format!(
"//! {ns} domain layer (generated by DomainForge).\n\n\
pub mod value_objects;\npub mod roles;\npub mod entities;\npub mod errors;\n",
ns = ir.namespace
);
if !ir.commands.is_empty() {
s.push_str("pub mod commands;\n");
}
if !ir.events.is_empty() {
s.push_str("pub mod events;\n");
}
s.push_str("pub mod aggregates;\npub mod ports;\npub mod container;\n\n");
s.push_str("pub use value_objects::Quantity;\npub use roles::Role;\npub use errors::DomainError;\npub use container::Container;\n");
s
}
fn value_objects(ir: &DomainIr) -> String {
let mut s = String::from("use crate::errors::DomainError;\n\n");
s.push_str(
"/// A measured amount with a unit.\n///\n/// `amount: f64` is lossy by design; fixture \
quantities are integers. Use a fixed-point type if precision matters.\n\
#[derive(Debug, Clone, PartialEq)]\npub struct Quantity {\n pub amount: f64,\n pub unit: String,\n}\n",
);
for vo in &ir.value_objects {
s.push_str(&format!(
"\n/// Value object matching `{regex}`.\n///\n/// ponytail: zero-dep validation rejects \
empty strings only; the full regex is documented above (add the `regex` crate to enforce it).\n\
#[derive(Debug, Clone, PartialEq, Eq)]\npub struct {name}(pub String);\n\n\
impl {name} {{\n /// Validate and construct. Returns the value-object error on empty input.\n \
pub fn new(value: String) -> Result<Self, DomainError> {{\n if value.is_empty() {{\n \
return Err(DomainError::{err});\n }}\n Ok(Self(value))\n }}\n\n \
pub fn value(&self) -> &str {{\n &self.0\n }}\n}}\n",
regex = vo.regex,
name = vo.name,
err = vo.error_name
));
}
s
}
fn roles(ir: &DomainIr) -> String {
let mut s = String::from("/// Authority roles for the domain.\n");
if !ir.relations_doc.is_empty() {
s.push_str("///\n/// Relations:\n");
for line in &ir.relations_doc {
s.push_str(&format!("/// {line}\n"));
}
}
let variants: Vec<String> = ir.roles.iter().map(|r| format!(" {r}")).collect();
s.push_str(&format!(
"#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum Role {{\n{}\n}}\n",
variants.join(",\n")
));
s
}
fn entities(ir: &DomainIr) -> String {
let mut s = String::new();
for e in &ir.entities {
let mut fields = String::from(" pub id: String,\n pub name: String,\n");
for (fname, _) in &e.fields {
fields.push_str(&format!(" pub {fname}: Option<String>,\n"));
}
s.push_str(&format!(
"#[derive(Debug, Clone, PartialEq, Eq)]\npub struct {name} {{\n{fields}}}\n\n",
name = e.name,
fields = fields
));
}
s
}
fn errors(ir: &DomainIr) -> String {
let mut s = String::from(
"use std::fmt;\n\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum DomainError {\n",
);
for e in &ir.errors {
s.push_str(&format!(" {},\n", e.name));
}
for vo in &ir.value_objects {
s.push_str(&format!(" {},\n", vo.error_name));
}
s.push_str("}\n\nimpl fmt::Display for DomainError {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n");
for e in &ir.errors {
s.push_str(&format!(
" Self::{} => write!(f, \"{}\"),\n",
e.name, e.name
));
}
for vo in &ir.value_objects {
s.push_str(&format!(
" Self::{} => write!(f, \"Invalid {}\"),\n",
vo.error_name, vo.name
));
}
s.push_str(" }\n }\n}\n\nimpl std::error::Error for DomainError {}\n");
s
}
fn commands(ir: &DomainIr) -> String {
let mut s = String::from("use crate::value_objects::Quantity;\nuse crate::roles::Role;\n");
for c in &ir.commands {
s.push_str(&format!(
"\n#[derive(Debug, Clone, PartialEq)]\npub struct {name} {{\n pub aggregate_id: String,\n pub quantity: Quantity,\n pub issued_by: Role,\n}}\n",
name = c.name
));
}
if !ir.commands.is_empty() {
let variants: Vec<String> = ir
.commands
.iter()
.map(|c| format!(" {}({})", c.name, c.name))
.collect();
s.push_str(&format!(
"\n#[derive(Debug, Clone)]\npub enum Command {{\n{}\n}}\n",
variants.join(",\n")
));
}
s
}
fn events(ir: &DomainIr) -> String {
let mut s = String::from("use crate::value_objects::Quantity;\n");
for e in &ir.events {
s.push_str(&format!(
"\n#[derive(Debug, Clone, PartialEq)]\npub struct {name} {{\n pub aggregate_id: String,\n pub quantity: Quantity,\n pub occurred_at: String,\n}}\n",
name = e.name
));
}
if !ir.events.is_empty() {
let variants: Vec<String> = ir
.events
.iter()
.map(|e| format!(" {}({})", e.name, e.name))
.collect();
s.push_str(&format!(
"\n#[derive(Debug, Clone)]\npub enum DomainEvent {{\n{}\n}}\n",
variants.join(",\n")
));
}
s
}
fn aggregates(ir: &DomainIr) -> String {
let mut s = String::from("use crate::value_objects::Quantity;\nuse crate::roles::Role;\nuse crate::errors::DomainError;\n");
if !ir.events.is_empty() {
let names: Vec<String> = ir.events.iter().map(|e| e.name.clone()).collect();
s.push_str(&format!("use crate::events::{{{}}};\n", names.join(", ")));
}
for agg in &ir.aggregates {
s.push_str(&format!(
"\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct {name} {{\n pub id: String,\n pub name: String,\n}}\n\nimpl {name} {{\n",
name = agg.name
));
for m in &agg.methods {
match &m.event {
Some(ret) => s.push_str(&format!(
" pub fn {mname}(&self, quantity: Quantity, _issued_by: Role, occurred_at: String) -> Result<{ret}, DomainError> {{\n{guards} Ok({ret} {{ aggregate_id: self.id.clone(), quantity, occurred_at }})\n }}\n",
mname = m.name,
ret = ret,
guards = m.guard_checks.iter().map(|g| format!(" self.{}()?;\n", g.check_method)).collect::<String>()
)),
None => s.push_str(&format!(
" pub fn {mname}(&self, quantity: Quantity, _issued_by: Role) -> Result<(), DomainError> {{\n{guards} Ok(())\n }}\n",
mname = m.name,
guards = m.guard_checks.iter().map(|g| format!(" self.{}()?;\n", g.check_method)).collect::<String>()
)),
}
}
let mut seen: Vec<String> = Vec::new();
for g in agg.methods.iter().flat_map(|m| m.guard_checks.iter()) {
if seen.contains(&g.check_method) {
continue;
}
seen.push(g.check_method.clone());
let rationale = ir
.errors
.iter()
.find(|e| e.name == g.error)
.and_then(|e| e.rationale.clone())
.unwrap_or_else(|| "Policy guard.".to_string());
s.push_str(&format!(
" /// {rationale}\n pub fn {c}(&self) -> Result<(), DomainError> {{\n Ok(())\n }}\n",
c = g.check_method,
rationale = rationale
));
}
s.push_str("}\n");
}
s
}
fn ports(ir: &DomainIr) -> String {
let mut s =
String::from("use crate::errors::DomainError;\nuse crate::value_objects::Quantity;\n");
if !ir.aggregates.is_empty() {
let names: Vec<String> = ir.aggregates.iter().map(|a| a.name.clone()).collect();
s.push_str(&format!(
"use crate::aggregates::{{{}}};\n",
names.join(", ")
));
}
if !ir.events.is_empty() {
s.push_str("use crate::events::DomainEvent;\n");
}
if !ir.commands.is_empty() {
s.push_str("use crate::commands::Command;\n");
}
for agg in &ir.aggregates {
s.push_str(&format!(
"\n/// Repository port for the {name} aggregate.\npub trait {name}Repository {{\n fn get(&self, id: &str) -> Result<Option<{name}>, DomainError>;\n fn save(&self, aggregate: &{name}) -> Result<(), DomainError>;\n}}\n",
name = agg.name
));
}
if !ir.events.is_empty() {
s.push_str(
"\n/// Port: publishes domain events.\npub trait EventBus {\n fn publish(&self, event: DomainEvent) -> Result<(), DomainError>;\n}\n",
);
}
if !ir.commands.is_empty() {
s.push_str(
"\n/// Port: dispatches domain commands.\npub trait CommandBus {\n fn dispatch(&self, command: Command) -> Result<(), DomainError>;\n}\n",
);
}
s.push_str(&format!(
"\n/// CQRS read model: query ports for derived metrics.\npub trait {ns}ReadModel {{\n",
ns = ir.package_pascal
));
for q in &ir.queries {
let mut doc = format!("Metric '{}'", q.metric_name);
if let Some(u) = &q.unit {
doc.push_str(&format!(" (unit: {u})"));
}
if let Some(t) = &q.threshold {
doc.push_str(&format!(", threshold: {t}"));
}
doc.push('.');
s.push_str(&format!(
" /// {doc}\n fn {mname}(&self) -> Result<Quantity, DomainError>;\n",
doc = doc,
mname = q.name
));
}
s.push_str("}\n");
s
}
fn container(ir: &DomainIr) -> String {
let mut s = String::from("use crate::ports::*;\n");
s.push_str(&format!(
"use crate::ports::{ns}ReadModel;\n",
ns = ir.package_pascal
));
let mut fields: Vec<String> = ir
.aggregates
.iter()
.map(|a| {
format!(
" pub {slug}_repository: Box<dyn {name}Repository>",
slug = lower_snake(&a.name),
name = a.name
)
})
.collect();
if !ir.events.is_empty() {
fields.push(" pub event_bus: Box<dyn EventBus>".to_string());
}
if !ir.commands.is_empty() {
fields.push(" pub command_bus: Box<dyn CommandBus>".to_string());
}
fields.push(format!(
" pub read_model: Box<dyn {}ReadModel>",
ir.package_pascal
));
s.push_str(&format!(
"\n/// Composition root: holds every port via constructor injection.\npub struct Container {{\n{}\n}}\n\n\
impl Container {{\n pub fn new({params}) -> Self {{\n Self {{ {moves} }}\n }}\n}}\n",
fields.join(",\n"),
params = fields
.iter()
.map(|f| field_decl(f))
.collect::<Vec<_>>()
.join(", "),
moves = fields
.iter()
.map(|f| field_name(f))
.collect::<Vec<_>>()
.join(", ")
));
s
}
fn smoke(ir: &DomainIr) -> String {
let crate_name = format!("{}_domain", ir.package_slug);
let mut s = format!("use {crate_name}::Quantity;\n");
if !ir.roles.is_empty() {
s.push_str(&format!("use {crate_name}::Role;\n"));
}
for c in &ir.commands {
s.push_str(&format!(
"use {crate_name}::commands::{name};\n",
name = c.name
));
}
for e in &ir.events {
s.push_str(&format!(
"use {crate_name}::events::{name};\n",
name = e.name
));
}
for vo in &ir.value_objects {
s.push_str(&format!(
"use {crate_name}::value_objects::{name};\n",
name = vo.name
));
}
for agg in &ir.aggregates {
s.push_str(&format!(
"use {crate_name}::aggregates::{name};\n",
name = agg.name
));
}
s.push_str(&format!("use {crate_name}::DomainError;\n"));
let _ = crate_name;
s.push_str("\n#[test]\nfn constructs_and_validates() {\n");
for c in &ir.commands {
let role = ir
.roles
.first()
.cloned()
.unwrap_or_else(|| "Requester".to_string());
s.push_str(&format!(
" let _cmd = {name} {{ aggregate_id: \"a\".to_string(), quantity: Quantity {{ amount: 1.0, unit: \"u\".to_string() }}, issued_by: Role::{role} }};\n",
name = c.name, role = role
));
}
for e in &ir.events {
s.push_str(&format!(
" let _ev = {name} {{ aggregate_id: \"a\".to_string(), quantity: Quantity {{ amount: 1.0, unit: \"u\".to_string() }}, occurred_at: \"now\".to_string() }};\n",
name = e.name
));
}
for vo in &ir.value_objects {
s.push_str(&format!(
" let good = {name}::new(\"ABC-1\".to_string()).expect(\"valid value accepted\");\n assert_eq!(good.value(), \"ABC-1\");\n assert!(matches!({name}::new(String::new()), Err(DomainError::{err})));\n",
name = vo.name, err = vo.error_name
));
}
for agg in &ir.aggregates {
s.push_str(&format!(
" let {lower} = {name} {{ id: \"x\".to_string(), name: \"n\".to_string() }};\n assert_eq!({lower}.id, \"x\");\n",
name = agg.name, lower = lower_snake(&agg.name)
));
}
s.push_str("}\n");
s
}
fn lower_snake(pascal: &str) -> String {
let mut out = String::new();
for (i, ch) in pascal.chars().enumerate() {
if ch.is_ascii_uppercase() {
if i > 0 {
out.push('_');
}
out.push(ch.to_ascii_lowercase());
} else {
out.push(ch);
}
}
out
}
fn field_decl(field: &str) -> String {
field.trim_start().trim_start_matches("pub ").to_string()
}
fn field_name(field: &str) -> String {
let decl = field.trim_start().trim_start_matches("pub ");
decl.split(':').next().unwrap_or("").trim().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::parse_to_graph;
const FIXED_TS: &str = "2026-07-02T00:00:00+00:00";
fn fixture_files() -> BTreeMap<String, String> {
let src = std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures/projection_cell/basic/model.sea"),
)
.expect("fixture");
let graph = parse_to_graph(&src).expect("parses");
project_domain_rust_in_memory(&graph, "test.sea", Some(FIXED_TS.to_string()))
.expect("projects")
}
#[test]
fn emits_expected_file_set() {
let files = fixture_files();
let keys: Vec<&str> = files.keys().map(|s| s.as_str()).collect();
assert!(keys.contains(&"Cargo.toml"), "missing Cargo.toml");
assert!(keys.contains(&"src/lib.rs"), "missing lib.rs");
assert!(keys.contains(&"src/aggregates.rs"), "missing aggregates");
assert!(keys.contains(&"src/ports.rs"), "missing ports");
assert!(keys.contains(&"tests/smoke.rs"), "missing smoke");
}
#[test]
fn key_content_present() {
let files = fixture_files();
let ports = &files["src/ports.rs"];
assert!(
ports.contains("pub trait PurchaseOrderRepository"),
"missing trait"
);
let errs = &files["src/errors.rs"];
assert!(
errs.contains("RequireApprovalViolation"),
"missing error variant"
);
}
#[test]
fn deterministic() {
assert_eq!(fixture_files(), fixture_files());
}
#[test]
fn zero_dependencies() {
let files = fixture_files();
let ct = &files["Cargo.toml"];
assert!(
ct.contains("[dependencies]\n\n[workspace]"),
"must declare zero deps + workspace opt-out"
);
}
}