domainforge_core/graph/
to_ast.rs1use crate::graph::Graph;
2use crate::parser::ast::{Ast, AstNode, FileMetadata};
3use crate::primitives::{Entity, Resource};
4
5const DEFAULT_NAMESPACE: &str = "default";
6
7fn map_domain(namespace: &str) -> Option<String> {
8 if namespace != DEFAULT_NAMESPACE {
9 Some(namespace.to_string())
10 } else {
11 None
12 }
13}
14
15impl Graph {
16 pub fn to_ast(&self) -> Ast {
17 let mut declarations = Vec::new();
18
19 let mut entities: Vec<&Entity> = self.entities.values().collect();
21 entities.sort_by(|a, b| {
22 a.name()
23 .cmp(b.name())
24 .then_with(|| a.namespace().cmp(b.namespace()))
25 });
26 for entity in entities {
27 let node = AstNode::Entity {
28 name: entity.name().to_string(),
29 version: entity.version().map(|v| v.to_string()),
30 annotations: Default::default(),
31 domain: map_domain(entity.namespace()),
32 body: None,
33 };
34 declarations.push(crate::parser::ast::Spanned {
35 node,
36 line: 0,
37 column: 0,
38 });
39 }
40
41 let mut resources: Vec<&Resource> = self.resources.values().collect();
43 resources.sort_by(|a, b| {
44 a.name()
45 .cmp(b.name())
46 .then_with(|| a.namespace().cmp(b.namespace()))
47 });
48 for resource in resources {
49 let node = AstNode::Resource {
50 name: resource.name().to_string(),
51 annotations: Default::default(),
52 unit_name: None,
53 domain: map_domain(resource.namespace()),
54 };
55 declarations.push(crate::parser::ast::Spanned {
56 node,
57 line: 0,
58 column: 0,
59 });
60 }
61
62 Ast {
63 metadata: FileMetadata::default(),
64 declarations,
65 }
66 }
67}