Skip to main content

vibe/
topology_decl.rs

1//! Declarative VibeScript `geometry` and `topology` complex parser and capability lowerer.
2//!
3//! Implements ยง6 of the POET Geometry-Topology Complex architecture ("Geometries Harbour Many Graphs"):
4//! - `geometry <Name> : <ComplexKind> { ... graph <G> : <Morphology> { ... } }`
5//! - Standalone `topology <Name> : <Morphology> { ... }` syntactic sugar (desugars into a host
6//!   `GeometryDecl` of kind `MetricPointCloud10D` harbouring a single primary `HarbouredGraphDecl` at `slot = 0`).
7//! - Deterministic lowering to `Topology.define_geometry`, `Topology.harbour_graph`, and `Poet.topology_bind`.
8
9use std::collections::BTreeMap;
10
11use crate::ast::{Arg, Block, Expr, ExprKind, Literal, NamedArg, Stmt};
12use crate::error::{DiagCode, Diagnostic};
13use crate::lex::TokenKind;
14use crate::parse::Parser;
15use crate::span::Span;
16use crate::value::Value;
17
18/// Boundary source/sink degree predicates on a harboured graph (`boundary { sources: ...; sinks: ...; }`).
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct BoundaryDecl {
21    pub sources: Option<String>,
22    pub sinks: Option<String>,
23}
24
25/// A single `graph <Name> : <Morphology> { ... }` harboured inside a host `GeometryDecl`.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct HarbouredGraphDecl {
28    pub span: Span,
29    pub name: String,
30    pub slot: u16,
31    pub morphology: String,
32    pub role: String,
33    pub anchors: Vec<String>,
34    pub weights: Option<String>,
35    pub edge_binding: Vec<String>,
36    pub invariants: Vec<String>,
37    pub boundary: Option<BoundaryDecl>,
38}
39
40/// A declarative `geometry <Name> : <ComplexKind> { ... }` harbouring $M \ge 1$ graphs.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct GeometryDecl {
43    pub span: Span,
44    pub name: String,
45    pub complex_kind: String,
46    pub satisfies: Option<String>,
47    pub manifold: Option<String>,
48    pub v_register: Option<u64>,
49    pub w_domain: Option<u64>,
50    pub metric: Option<String>,
51    pub metric_axes: Vec<String>,
52    pub cells_source: Option<String>,
53    pub operators: Vec<String>,
54    pub harboured_graphs: Vec<HarbouredGraphDecl>,
55    pub is_standalone_topology_sugar: bool,
56}
57
58/// Deterministic `capability.invoke` call descriptor lowered from a `GeometryDecl`.
59#[derive(Debug, Clone, PartialEq)]
60pub struct TopologyInvokeDescriptor {
61    pub capability_id: &'static str,
62    pub args: Value,
63}
64
65impl GeometryDecl {
66    /// Lowers this `GeometryDecl` and its harboured graphs into deterministic
67    /// `Topology.define_geometry`, `Topology.harbour_graph`, and `Poet.topology_bind` descriptors.
68    pub fn lower_to_invokes(&self) -> Vec<TopologyInvokeDescriptor> {
69        let mut out = Vec::with_capacity(self.harboured_graphs.len() + 2);
70        let mut def_map = BTreeMap::new();
71        def_map.insert("name".into(), Value::String(self.name.clone()));
72        def_map.insert("complex_kind".into(), Value::String(self.complex_kind.clone()));
73        def_map.insert("harboured_graph_count".into(), Value::U64(self.harboured_graphs.len() as u64));
74        if let Some(s) = &self.satisfies { def_map.insert("satisfies".into(), Value::String(s.clone())); }
75        if let Some(m) = &self.manifold { def_map.insert("manifold".into(), Value::String(m.clone())); }
76        if let Some(v) = self.v_register { def_map.insert("v_register".into(), Value::U64(v)); }
77        if let Some(w) = self.w_domain { def_map.insert("w_domain".into(), Value::U64(w)); }
78        if let Some(metric) = &self.metric { def_map.insert("metric".into(), Value::String(metric.clone())); }
79        if !self.metric_axes.is_empty() {
80            def_map.insert("metric_axes".into(), Value::List(self.metric_axes.iter().cloned().map(Value::String).collect()));
81        }
82        if let Some(src) = &self.cells_source { def_map.insert("cells_source".into(), Value::String(src.clone())); }
83        if !self.operators.is_empty() {
84            def_map.insert("operators".into(), Value::List(self.operators.iter().cloned().map(Value::String).collect()));
85        }
86        out.push(TopologyInvokeDescriptor { capability_id: "Topology.define_geometry", args: Value::Record(def_map) });
87
88        for g in &self.harboured_graphs {
89            let mut g_map = BTreeMap::new();
90            g_map.insert("geometry".into(), Value::String(self.name.clone()));
91            g_map.insert("name".into(), Value::String(g.name.clone()));
92            g_map.insert("slot".into(), Value::U64(g.slot as u64));
93            g_map.insert("morphology".into(), Value::String(g.morphology.clone()));
94            g_map.insert("role".into(), Value::String(g.role.clone()));
95            g_map.insert("anchors".into(), Value::List(g.anchors.iter().cloned().map(Value::String).collect()));
96            g_map.insert("invariants".into(), Value::List(g.invariants.iter().cloned().map(Value::String).collect()));
97            if let Some(w) = &g.weights { g_map.insert("weights".into(), Value::String(w.clone())); }
98            if !g.edge_binding.is_empty() {
99                g_map.insert("edge_binding".into(), Value::List(g.edge_binding.iter().cloned().map(Value::String).collect()));
100            }
101            if let Some(b) = &g.boundary {
102                if let Some(src) = &b.sources { g_map.insert("boundary_sources".into(), Value::String(src.clone())); }
103                if let Some(snk) = &b.sinks { g_map.insert("boundary_sinks".into(), Value::String(snk.clone())); }
104            }
105            out.push(TopologyInvokeDescriptor { capability_id: "Topology.harbour_graph", args: Value::Record(g_map) });
106        }
107
108        let mut bind_map = BTreeMap::new();
109        bind_map.insert("geometry".into(), Value::String(self.name.clone()));
110        bind_map.insert("complex_kind".into(), Value::String(self.complex_kind.clone()));
111        bind_map.insert("manifold".into(), Value::String(self.manifold.clone().unwrap_or_else(|| "Spatial".into())));
112        bind_map.insert("harboured_graph_count".into(), Value::U64(self.harboured_graphs.len() as u64));
113        bind_map.insert("active_graph_slot".into(), Value::U64(0));
114        out.push(TopologyInvokeDescriptor { capability_id: "Poet.topology_bind", args: Value::Record(bind_map) });
115        out
116    }
117
118    /// Lowers this declaration to an AST `Block` of capability invoke statements.
119    pub fn lower_to_block(&self) -> Block {
120        let span = self.span;
121        let stmts = self.lower_to_invokes().into_iter().map(|desc| {
122            let (fam, method) = desc.capability_id.split_once('.').unwrap_or(("Topology", desc.capability_id));
123            let callee = Expr {
124                span,
125                kind: ExprKind::Member {
126                    recv: Box::new(Expr { span, kind: ExprKind::Ident(fam.to_string()) }),
127                    name: method.to_string(),
128                },
129            };
130            let args = match desc.args {
131                Value::Record(map) => map.into_iter().map(|(k, v)| {
132                    Arg::Named(NamedArg { span, name: k, value: value_to_ast_expr(&v, span) })
133                }).collect(),
134                _ => Vec::new(),
135            };
136            Stmt::Expr { span, expr: Expr { span, kind: ExprKind::Call { callee: Box::new(callee), args } } }
137        }).collect();
138        Block { span, stmts }
139    }
140}
141
142fn value_to_ast_expr(v: &Value, span: Span) -> Expr {
143    let kind = match v {
144        Value::String(s) => ExprKind::Literal(Literal::String(s.clone())),
145        Value::U64(n) => ExprKind::Literal(Literal::UInt(*n)),
146        Value::I64(n) => ExprKind::Literal(Literal::Int(*n)),
147        Value::Bool(b) => ExprKind::Literal(Literal::Bool(*b)),
148        Value::List(items) => ExprKind::List(items.iter().map(|i| value_to_ast_expr(i, span)).collect()),
149        _ => ExprKind::Literal(Literal::Null),
150    };
151    Expr { span, kind }
152}
153
154/// Parses a single `geometry <Name> : <ComplexKind> { ... }` or standalone `topology <Name> : <Morphology> { ... }`.
155pub fn parse_geometry_or_topology(src: &str) -> Result<GeometryDecl, Diagnostic> {
156    let mut parser = Parser::new(src)?;
157    parser.parse_geometry_or_topology_decl()
158}
159
160/// Parses all `geometry` and `topology` declarations in a VibeScript source snippet, skipping `construct` or other items.
161pub fn parse_geometry_blocks(src: &str) -> Result<Vec<GeometryDecl>, Diagnostic> {
162    let mut parser = Parser::new(src)?;
163    let mut out = Vec::new();
164    while parser.cur.kind != TokenKind::Eof {
165        if parser.looks_like_geometry_or_topology() {
166            out.push(parser.parse_geometry_or_topology_decl()?);
167        } else {
168            parser.cur = parser.lex.next_token()?;
169        }
170    }
171    Ok(out)
172}
173
174impl<'a> Parser<'a> {
175    pub(crate) fn looks_like_geometry_or_topology(&self) -> bool {
176        let tok = self.cur.span.slice(self.lex.source());
177        if tok != "geometry" && tok != "topology" { return false; }
178        let rest = self.lex.source()[self.cur.span.end as usize..].trim_start();
179        let ident_len = rest.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').map(char::len_utf8).sum::<usize>();
180        ident_len > 0 && rest[ident_len..].trim_start().starts_with(':')
181    }
182
183    pub(crate) fn parse_geometry_or_topology_decl(&mut self) -> Result<GeometryDecl, Diagnostic> {
184        let start = self.cur.span.start;
185        let kw = self.cur.span.slice(self.lex.source()).to_string();
186        self.cur = self.lex.next_token()?;
187        let name = self.take_any_ident()?;
188        self.expect_tok(TokenKind::Colon, "expected ':' after geometry/topology name")?;
189        let header_kind = self.take_any_ident()?;
190        self.expect_tok(TokenKind::LBrace, "expected '{' to open geometry/topology body")?;
191
192        if kw == "topology" {
193            let mut graph = self.parse_harboured_graph_body(start, name.clone(), 0, header_kind)?;
194            if graph.role.is_empty() { graph.role = "SemanticOverlay".into(); }
195            if graph.anchors.is_empty() { graph.anchors.push("SemanticQuin".into()); }
196            let end = self.expect_tok(TokenKind::RBrace, "expected '}' after topology body")?.end;
197            graph.span = Span::new(start, end);
198            return Ok(GeometryDecl {
199                span: Span::new(start, end), name, complex_kind: "MetricPointCloud10D".into(),
200                satisfies: None, manifold: Some("Spatial".into()), v_register: Some(0), w_domain: None,
201                metric: Some("Euclidean".into()), metric_axes: Vec::new(), cells_source: None,
202                operators: Vec::new(), harboured_graphs: vec![graph], is_standalone_topology_sugar: true,
203            });
204        }
205
206        let mut decl = GeometryDecl {
207            span: Span::new(start, start), name, complex_kind: header_kind,
208            satisfies: None, manifold: None, v_register: None, w_domain: None,
209            metric: None, metric_axes: Vec::new(), cells_source: None,
210            operators: Vec::new(), harboured_graphs: Vec::new(), is_standalone_topology_sugar: false,
211        };
212
213        while self.cur.kind != TokenKind::RBrace && self.cur.kind != TokenKind::Eof {
214            let key = self.take_any_ident()?;
215            if key == "graph" {
216                let g_start = self.cur.span.start;
217                let g_name = self.take_any_ident()?;
218                self.expect_tok(TokenKind::Colon, "expected ':' after graph name")?;
219                let morph = self.take_any_ident()?;
220                self.expect_tok(TokenKind::LBrace, "expected '{' after graph morphology")?;
221                let slot = decl.harboured_graphs.len() as u16;
222                let mut g = self.parse_harboured_graph_body(g_start, g_name, slot, morph)?;
223                let g_end = self.expect_tok(TokenKind::RBrace, "expected '}' after graph block")?.end;
224                g.span = Span::new(g_start, g_end);
225                decl.harboured_graphs.push(g);
226                continue;
227            }
228            self.expect_tok(TokenKind::Colon, "expected ':' after geometry property")?;
229            match key.as_str() {
230                "satisfies" => decl.satisfies = Some(self.take_scalar_text()?),
231                "manifold" => {
232                    decl.manifold = Some(self.take_scalar_text()?);
233                    if self.cur.kind == TokenKind::LParen {
234                        self.cur = self.lex.next_token()?;
235                        while self.cur.kind != TokenKind::RParen && self.cur.kind != TokenKind::Eof {
236                            let pk = self.take_any_ident()?;
237                            self.expect_tok(TokenKind::Colon, "expected ':'")?;
238                            let pv = self.take_scalar_text()?.parse::<u64>().unwrap_or(0);
239                            if pk == "v_register" { decl.v_register = Some(pv); }
240                            else if pk == "w_domain" { decl.w_domain = Some(pv); }
241                            if self.cur.kind == TokenKind::Comma { self.cur = self.lex.next_token()?; }
242                        }
243                        self.expect_tok(TokenKind::RParen, "expected ')'")?;
244                    }
245                }
246                "metric" => {
247                    decl.metric = Some(self.take_any_ident()?);
248                    if self.cur.kind == TokenKind::LParen { self.skip_balanced_parens(&mut decl.metric_axes)?; }
249                }
250                "cells" => {
251                    let first = self.take_scalar_text()?;
252                    if self.cur.kind == TokenKind::LParen {
253                        self.cur = self.lex.next_token()?;
254                        decl.cells_source = Some(self.take_scalar_text()?);
255                        self.expect_tok(TokenKind::RParen, "expected ')' after cells source")?;
256                    } else {
257                        decl.cells_source = Some(first);
258                    }
259                }
260                "operators" => decl.operators = self.take_string_or_ident_list()?,
261                _ => { let _ = self.take_string_or_ident_list()?; }
262            }
263            if self.cur.kind == TokenKind::Semicolon { self.cur = self.lex.next_token()?; }
264        }
265        let end = self.expect_tok(TokenKind::RBrace, "expected '}' after geometry body")?.end;
266        decl.span = Span::new(start, end);
267        Ok(decl)
268    }
269
270    fn parse_harboured_graph_body(&mut self, start: u32, name: String, slot: u16, morphology: String) -> Result<HarbouredGraphDecl, Diagnostic> {
271        let mut graph = HarbouredGraphDecl {
272            span: Span::new(start, start), name, slot, morphology, role: "Primal1Skeleton".into(),
273            anchors: Vec::new(), weights: None, edge_binding: Vec::new(), invariants: Vec::new(), boundary: None,
274        };
275        while self.cur.kind != TokenKind::RBrace && self.cur.kind != TokenKind::Eof {
276            let key = self.take_any_ident()?;
277            if key == "boundary" {
278                self.expect_tok(TokenKind::LBrace, "expected '{' after boundary")?;
279                let mut b = BoundaryDecl::default();
280                while self.cur.kind != TokenKind::RBrace && self.cur.kind != TokenKind::Eof {
281                    let bk = self.take_any_ident()?;
282                    self.expect_tok(TokenKind::Colon, "expected ':' after boundary key")?;
283                    let bv = self.take_scalar_text()?;
284                    if bk == "sources" { b.sources = Some(bv); } else if bk == "sinks" { b.sinks = Some(bv); }
285                    if self.cur.kind == TokenKind::Semicolon { self.cur = self.lex.next_token()?; }
286                }
287                self.expect_tok(TokenKind::RBrace, "expected '}' after boundary")?;
288                graph.boundary = Some(b);
289                if self.cur.kind == TokenKind::Semicolon { self.cur = self.lex.next_token()?; }
290                continue;
291            }
292            self.expect_tok(TokenKind::Colon, "expected ':' after graph property")?;
293            match key.as_str() {
294                "role" => graph.role = self.take_scalar_text()?,
295                "anchors" => graph.anchors = self.take_string_or_ident_list()?,
296                "weights" => graph.weights = Some(self.take_scalar_text()?),
297                "edge_binding" => graph.edge_binding = self.take_string_or_ident_list()?,
298                "invariants" => graph.invariants = self.take_string_or_ident_list()?,
299                _ => { let _ = self.take_string_or_ident_list()?; }
300            }
301            if self.cur.kind == TokenKind::Semicolon { self.cur = self.lex.next_token()?; }
302        }
303        Ok(graph)
304    }
305
306    fn expect_tok(&mut self, kind: TokenKind, msg: &str) -> Result<Span, Diagnostic> {
307        if self.cur.kind == kind {
308            let sp = self.cur.span;
309            self.cur = self.lex.next_token()?;
310            Ok(sp)
311        } else {
312            Err(Diagnostic::new(DiagCode::E001, self.cur.span, msg.to_string()))
313        }
314    }
315
316    fn take_any_ident(&mut self) -> Result<String, Diagnostic> {
317        if matches!(self.cur.kind, TokenKind::Ident | TokenKind::Keyword) {
318            let s = self.cur.span.slice(self.lex.source()).to_string();
319            self.cur = self.lex.next_token()?;
320            Ok(s)
321        } else {
322            Err(Diagnostic::new(DiagCode::E001, self.cur.span, "expected identifier"))
323        }
324    }
325
326    fn take_scalar_text(&mut self) -> Result<String, Diagnostic> {
327        let raw = self.cur.span.slice(self.lex.source()).to_string();
328        match self.cur.kind {
329            TokenKind::String => {
330                self.cur = self.lex.next_token()?;
331                Ok(raw.trim_matches('"').to_string())
332            }
333            TokenKind::Ident | TokenKind::Keyword | TokenKind::Int | TokenKind::Float => {
334                self.cur = self.lex.next_token()?;
335                if self.cur.kind == TokenKind::Colon {
336                    self.cur = self.lex.next_token()?;
337                    let local = self.cur.span.slice(self.lex.source()).to_string();
338                    self.cur = self.lex.next_token()?;
339                    return Ok(format!("{raw}:{local}"));
340                }
341                Ok(raw)
342            }
343            _ => Err(Diagnostic::new(DiagCode::E001, self.cur.span, "expected value")),
344        }
345    }
346
347    fn take_string_or_ident_list(&mut self) -> Result<Vec<String>, Diagnostic> {
348        if self.cur.kind == TokenKind::LBracket {
349            self.cur = self.lex.next_token()?;
350            let mut items = Vec::new();
351            while self.cur.kind != TokenKind::RBracket && self.cur.kind != TokenKind::Eof {
352                items.push(self.take_scalar_text()?);
353                if self.cur.kind == TokenKind::Comma { self.cur = self.lex.next_token()?; }
354            }
355            self.expect_tok(TokenKind::RBracket, "expected ']'")?;
356            Ok(items)
357        } else {
358            Ok(vec![self.take_scalar_text()?])
359        }
360    }
361
362    fn skip_balanced_parens(&mut self, axes: &mut Vec<String>) -> Result<(), Diagnostic> {
363        self.expect_tok(TokenKind::LParen, "expected '('")?;
364        let mut depth = 1usize;
365        while depth > 0 && self.cur.kind != TokenKind::Eof {
366            match self.cur.kind {
367                TokenKind::LParen => { depth += 1; self.cur = self.lex.next_token()?; }
368                TokenKind::RParen => { depth -= 1; self.cur = self.lex.next_token()?; }
369                TokenKind::LBracket => *axes = self.take_string_or_ident_list()?,
370                _ => self.cur = self.lex.next_token()?,
371            }
372        }
373        Ok(())
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn parses_geometry_harbouring_multiple_graphs_and_lowers() {
383        let src = r#"
384        geometry NorthSpringCatchment : MixedCellComplex3D {
385            satisfies: CatchmentHydrology;
386            manifold: "research" (v_register: 0, w_domain: 3);
387            metric: Euclidean10D(axes: [x, y, z, t, alpha, mu, sigma]);
388            cells: source("catchment_corridor.10d");
389            operators: [BoundaryExact, CotangentLaplacian, HodgeStar];
390
391            graph PrimalMesh : SymmetricGraph {
392                role: Primal1Skeleton;
393                anchors: Cell0Vertex;
394                invariants: [SYMMETRIC, SPATIAL_METRIC];
395            }
396
397            graph SubsurfaceFluxDual : DirectedMultigraph {
398                role: PoincareDual;
399                anchors: Cell3Volume;
400                weights: HodgeStarRatio;
401                invariants: [MANIFOLD_CLOSED, SPATIAL_METRIC];
402            }
403
404            graph WatershedDrainage : DeterministicDAG {
405                role: CausalFlux;
406                anchors: Cell2Face;
407                edge_binding: ["qualia:drains_to"];
408                invariants: [ACYCLIC, TRANSITIVE, TEMPORAL_MONOTONIC];
409                boundary {
410                    sources: "in_degree == 0";
411                    sinks: "out_degree == 0";
412                }
413            }
414        }
415        "#;
416        let decl = parse_geometry_or_topology(src).expect("should parse geometry block");
417        assert_eq!(decl.name, "NorthSpringCatchment");
418        assert_eq!(decl.complex_kind, "MixedCellComplex3D");
419        assert_eq!(decl.satisfies.as_deref(), Some("CatchmentHydrology"));
420        assert_eq!(decl.cells_source.as_deref(), Some("catchment_corridor.10d"));
421        assert_eq!(decl.harboured_graphs.len(), 3);
422        assert_eq!(decl.harboured_graphs[0].name, "PrimalMesh");
423        assert_eq!(decl.harboured_graphs[1].name, "SubsurfaceFluxDual");
424        assert_eq!(decl.harboured_graphs[2].name, "WatershedDrainage");
425        assert_eq!(
426            decl.harboured_graphs[2].boundary.as_ref().and_then(|b| b.sources.as_deref()),
427            Some("in_degree == 0")
428        );
429
430        let invokes = decl.lower_to_invokes();
431        assert_eq!(invokes.len(), 5);
432        assert_eq!(invokes[0].capability_id, "Topology.define_geometry");
433        assert_eq!(invokes[1].capability_id, "Topology.harbour_graph");
434        assert_eq!(invokes[2].capability_id, "Topology.harbour_graph");
435        assert_eq!(invokes[3].capability_id, "Topology.harbour_graph");
436        assert_eq!(invokes[4].capability_id, "Poet.topology_bind");
437    }
438
439    #[test]
440    fn parses_standalone_topology_sugar_into_metric_point_cloud() {
441        let src = r#"
442        topology WordNetHierarchy : DeterministicDAG {
443            edge_binding: [rdfs:subClassOf, skos:broader];
444            invariants: [ACYCLIC, TRANSITIVE];
445        }
446        "#;
447        let decl = parse_geometry_or_topology(src).expect("should parse standalone topology sugar");
448        assert!(decl.is_standalone_topology_sugar);
449        assert_eq!(decl.name, "WordNetHierarchy");
450        assert_eq!(decl.complex_kind, "MetricPointCloud10D");
451        assert_eq!(decl.harboured_graphs.len(), 1);
452        assert_eq!(decl.harboured_graphs[0].morphology, "DeterministicDAG");
453        assert_eq!(decl.harboured_graphs[0].edge_binding, vec!["rdfs:subClassOf", "skos:broader"]);
454    }
455}