domainforge_core/parser/
mod.rs1use crate::graph::Graph;
2use pest_derive::Parser;
3use std::path::PathBuf;
4
5#[derive(Parser)]
6#[grammar = "grammar/sea.pest"]
7pub struct SeaParser;
8
9pub mod ast;
10pub mod ast_convert;
11pub mod ast_schema;
12pub mod error;
13pub mod lint;
14pub mod printer;
15pub mod profiles;
16pub mod string_utils;
17
18pub use ast::parse_expression_from_str;
19pub use ast::parse_source;
20pub use ast::Ast;
21pub use ast::AstNode;
22pub use error::{ParseError, ParseResult};
23pub use lint::*;
24pub use printer::PrettyPrinter;
25pub use profiles::{Profile, ProfileRegistry};
26pub use string_utils::unescape_string;
27
28#[derive(Debug, Clone, Default)]
33pub struct ParseOptions {
34 pub default_namespace: Option<String>,
37 pub namespace_registry: Option<crate::registry::NamespaceRegistry>,
39 pub entry_path: Option<PathBuf>,
41 pub active_profile: Option<String>,
43 pub tolerate_profile_warnings: bool,
45}
46
47pub fn parse(source: &str) -> ParseResult<Ast> {
49 ast::parse_source(source)
50}
51
52pub fn parse_to_graph(source: &str) -> ParseResult<Graph> {
54 let ast = parse(source)?;
55 graph_from_parsed_source(source, ast, &ParseOptions::default())
56}
57
58fn graph_from_parsed_source(source: &str, ast: Ast, options: &ParseOptions) -> ParseResult<Graph> {
59 if !ast.declarations.iter().any(|declaration| {
60 let node = match &declaration.node {
61 AstNode::Export(inner) => &inner.node,
62 node => node,
63 };
64 matches!(node, AstNode::Entity { body: Some(_), .. })
65 }) {
66 return ast::ast_to_graph_with_options(ast, options);
67 }
68
69 let effective_source = if ast.metadata.namespace.is_some() {
70 source.to_string()
71 } else {
72 let namespace = options.default_namespace.as_deref().unwrap_or("default");
73 let namespace = serde_json::to_string(namespace)
74 .expect("serializing a Rust string as a SEA string literal cannot fail");
75 format!("@namespace {namespace}\n{source}")
76 };
77 let sources = serde_json::json!({ "main.sea": effective_source }).to_string();
78 crate::application::resolve_application_graph("main.sea", &sources).map_err(|diagnostics| {
79 ParseError::Validation(
80 diagnostics
81 .iter()
82 .map(|diagnostic| diagnostic.message.as_str())
83 .collect::<Vec<_>>()
84 .join("; "),
85 )
86 })
87}
88
89pub fn parse_to_graph_with_options(source: &str, options: &ParseOptions) -> ParseResult<Graph> {
112 match (&options.namespace_registry, &options.entry_path) {
113 (Some(registry), Some(path)) => {
114 let mut resolver = crate::module::resolver::ModuleResolver::new(registry)?;
115 let ast = resolver.validate_entry(path, source)?;
116 resolver.validate_dependencies(path, &ast)?;
117 ast::ast_to_graph_with_options(ast, options)
118 }
119 (Some(_), None) => Err(ParseError::Validation(
120 "Namespace registry provided without entry path".to_string(),
121 )),
122 _ => {
123 if let Some(path) = &options.entry_path {
124 log::warn!(
125 "Entry path '{}' provided without namespace registry; module resolution skipped",
126 path.display()
127 );
128 }
129 let ast = parse(source)?;
130 graph_from_parsed_source(source, ast, options)
131 }
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn test_entity_declaration_syntax() {
141 let source = r#"
142 Entity "Warehouse A" in logistics
143 "#;
144
145 let result = parse(source);
146 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
147 }
148
149 #[test]
150 fn test_resource_declaration_syntax() {
151 let source = r#"
152 Resource "Camera Units" units in inventory
153 "#;
154
155 let result = parse(source);
156 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
157 }
158
159 #[test]
160 fn test_flow_declaration_syntax() {
161 let source = r#"
162 Flow "Camera Units" from "Warehouse" to "Factory" quantity 100
163 "#;
164
165 let result = parse(source);
166 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
167 }
168
169 #[test]
170 fn test_policy_simple_syntax() {
171 let source = r#"
172 Policy check_quantity as: Flow.quantity > 0
173 "#;
174
175 let result = parse(source);
176 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
177 }
178
179 #[test]
180 fn test_complex_policy_syntax() {
181 let source = r#"
182 Policy flow_constraints as:
183 (Flow.quantity > 0) and (Entity.name != "")
184 "#;
185
186 let result = parse(source);
187 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
188 }
189
190 #[test]
191 fn test_nested_expressions() {
192 let source = r#"
193 Policy multi_condition as:
194 (A or B) and (C or (D and E))
195 "#;
196
197 let result = parse(source);
198 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
199 }
200
201 #[test]
202 fn test_comments_ignored() {
203 let source = r#"
204 // This is a comment
205 Entity "Test" in domain
206 // Another comment
207 "#;
208
209 let result = parse(source);
210 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
211 }
212
213 #[test]
214 fn test_multiple_declarations() {
215 let source = r#"
216 Entity "Warehouse" in logistics
217 Resource "Cameras" units
218 Flow "Cameras" from "Warehouse" to "Factory" quantity 50
219 "#;
220
221 let result = parse(source);
222 assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
223 }
224}