sea_core/graph/
to_ast.rs

1use 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        // Entities
20        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            declarations.push(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            });
33        }
34
35        // Resources
36        let mut resources: Vec<&Resource> = self.resources.values().collect();
37        resources.sort_by(|a, b| {
38            a.name()
39                .cmp(b.name())
40                .then_with(|| a.namespace().cmp(b.namespace()))
41        });
42        for resource in resources {
43            declarations.push(AstNode::Resource {
44                name: resource.name().to_string(),
45                unit_name: None,
46                domain: map_domain(resource.namespace()),
47            });
48        }
49
50        Ast {
51            metadata: FileMetadata::default(),
52            declarations,
53        }
54    }
55}