Skip to main content

weirdnet_code_spaces/
spaces.rs

1//! Spaces: a main code space plus members it calls and other spaces it imports, declared
2//! in an `@imports` header (`// @imports a, b, space:other`). This module has the parts that
3//! don't need the application's storage: reading and rewriting the header, the line-up
4//! hash an owner approves, and the cycle and depth check over a [`Graph`] the application
5//! provides.
6use crate::Profile;
7use crate::error::SpacesError;
8
9/// The deepest chain of spaces calling spaces.
10pub const MAX_DEPTH: usize = 8;
11
12/// What main declares it calls.
13#[derive(Debug, Clone, Default, PartialEq)]
14pub struct Imports {
15    /// Member aliases.
16    pub code: Vec<String>,
17    /// Space names (`space:NAME`, or the NAME of `space:NAME as ALIAS`).
18    pub spaces: Vec<String>,
19    /// (the name main calls it by, the space): `space:NAME` calls NAME, and
20    /// `space:NAME as ALIAS` calls ALIAS (what a renamed import keeps main calling).
21    pub space_aliases: Vec<(String, String)>,
22}
23
24/// One `@imports` part: `space:NAME [as ALIAS]` as (NAME, ALIAS).
25fn space_part(part: &str) -> Option<(String, Option<String>)> {
26    let (k, n) = part.split_once(':')?;
27    if !k.trim().eq_ignore_ascii_case("space") || n.trim().is_empty() {
28        return None;
29    }
30    let n = n.trim();
31    match n.split_once(" as ") {
32        Some((t, a)) if !t.trim().is_empty() && !a.trim().is_empty() => Some((t.trim().to_string(), Some(a.trim().to_string()))),
33        _ => Some((n.to_string(), None)),
34    }
35}
36
37fn header(line: &str) -> Option<(usize, usize)> {
38    let i = line.find("@imports")?;
39    let start = i + "@imports".len();
40    let rest = &line[start..];
41    let trimmed = rest.trim_end();
42    let body = trimmed.trim_end_matches("*/").trim_end_matches("-->").trim_end();
43    Some((start, start + body.len()))
44}
45
46/// Read main's `@imports` header lines (`// @imports a, b, space:other`).
47pub fn imports(source: &str) -> Imports {
48    let mut out = Imports::default();
49    for line in source.lines() {
50        let Some((a, b)) = header(line) else { continue };
51        for part in line[a..b].split(',').map(str::trim).filter(|p| !p.is_empty()) {
52            match space_part(part) {
53                Some((n, alias)) => {
54                    out.space_aliases.push((alias.unwrap_or_else(|| n.clone()), n.clone()));
55                    out.spaces.push(n);
56                }
57                None => out.code.push(part.to_string()),
58            }
59        }
60    }
61    out
62}
63
64/// `source` with space `from` imported as `to` instead (`space:from` becomes
65/// `space:to as from`, so main still calls it `from`); None when it doesn't import it.
66pub fn rename_space_import(source: &str, from: &str, to: &str) -> Option<String> {
67    let mut changed = false;
68    let lines: Vec<String> = source
69        .split_inclusive('\n')
70        .map(|line| {
71            let Some((a, b)) = header(line) else { return line.to_string() };
72            let parts: Vec<String> = line[a..b]
73                .split(',')
74                .map(|part| match space_part(part.trim()) {
75                    Some((n, alias)) if n.eq_ignore_ascii_case(from) => {
76                        changed = true;
77                        let alias = alias.unwrap_or(n);
78                        if alias.eq_ignore_ascii_case(to) { format!(" space:{to}") } else { format!(" space:{to} as {alias}") }
79                    }
80                    _ => part.to_string(),
81                })
82                .collect();
83            format!("{}{}{}", &line[..a], parts.join(","), &line[b..])
84        })
85        .collect();
86    changed.then(|| lines.concat())
87}
88
89/// What a space's approval covers: main, the kind, the members (alias, code id, pin) and
90/// the spaces main imports. Aliases and imported names are compared without case.
91#[derive(Debug, Clone, Default, PartialEq)]
92pub struct Lineup<'a> {
93    pub main_id: &'a str,
94    pub kind: &'a str,
95    /// (alias, code id, pin hash or "").
96    pub members: Vec<(&'a str, &'a str, &'a str)>,
97    /// Main's source, for its `space:` imports.
98    pub main_source: &'a str,
99}
100
101/// The line-up hash under a profile (its `lineup_domain`).
102pub fn lineup_hash(profile: &Profile, l: &Lineup) -> String {
103    let mut ms: Vec<(String, String, String)> = l.members.iter().map(|(a, c, p)| (a.to_lowercase(), c.to_string(), p.to_string())).collect();
104    ms.sort();
105    let mut sp: Vec<String> = imports(l.main_source).spaces.iter().map(|x| x.to_lowercase()).collect();
106    sp.sort();
107    sp.dedup();
108    let mut h = blake3::Hasher::new();
109    h.update(profile.lineup_domain);
110    h.update(l.main_id.as_bytes());
111    h.update(&[0]);
112    h.update(l.kind.as_bytes());
113    for (a, c, p) in &ms {
114        h.update(format!("\0m{a}\0{c}\0{p}").as_bytes());
115    }
116    for x in &sp {
117        h.update(format!("\0s{x}").as_bytes());
118    }
119    h.finalize().to_hex()[..32].to_string()
120}
121
122/// The spaces as the application stores them, for [`check_cycles`].
123pub trait Graph {
124    type Space;
125    type Error: From<SpacesError>;
126    fn name<'s>(&self, s: &'s Self::Space) -> &'s str;
127    /// The source of the space's main code.
128    fn main_source(&self, s: &Self::Space) -> Result<String, Self::Error>;
129    /// The space called `name`, if there is one.
130    fn find(&self, name: &str) -> Option<Self::Space>;
131}
132
133/// Refuse loops through main's `space:` imports (a → b → a), and chains deeper than
134/// [`MAX_DEPTH`].
135pub fn check_cycles<G: Graph>(g: &G, s: &G::Space) -> Result<(), G::Error> {
136    fn walk<G: Graph>(g: &G, s: &G::Space, path: &mut Vec<String>) -> Result<(), G::Error> {
137        let name = g.name(s);
138        if path.iter().any(|p| p.eq_ignore_ascii_case(name)) {
139            path.push(name.to_string());
140            return Err(SpacesError::invalid("space", format!("a cycle of spaces: {}", path.join(" → "))).into());
141        }
142        if path.len() >= MAX_DEPTH {
143            return Err(
144                SpacesError::invalid("space", format!("spaces call spaces more than {MAX_DEPTH} deep: {} → {}", path.join(" → "), name)).into()
145            );
146        }
147        path.push(name.to_string());
148        for n in imports(&g.main_source(s)?).spaces {
149            let t = g.find(&n).ok_or_else(|| SpacesError::invalid("space", format!("{}: main imports space:{n}, which doesn't exist", g.name(s))))?;
150            walk(g, &t, path)?;
151        }
152        path.pop();
153        Ok(())
154    }
155    walk(g, s, &mut vec![])
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use std::collections::HashMap;
162
163    #[test]
164    fn imports_and_renames() {
165        let i = imports("// @imports fast, slow, space:prices as p\n/* @imports space:other */\nfn run() {}");
166        assert_eq!(i.code, vec!["fast", "slow"]);
167        assert_eq!(i.spaces, vec!["prices", "other"]);
168        assert_eq!(i.space_aliases, vec![("p".to_string(), "prices".to_string()), ("other".to_string(), "other".to_string())]);
169        let r = rename_space_import("// @imports a, space:old\nx\n", "old", "new").unwrap();
170        assert_eq!(r, "// @imports a, space:new as old\nx\n");
171        assert_eq!(imports(&r).space_aliases, vec![("old".to_string(), "new".to_string())]);
172        assert!(rename_space_import("// @imports a\n", "old", "new").is_none());
173    }
174
175    #[test]
176    fn lineup_hash_ignores_case_and_order() {
177        let a = Lineup {
178            main_id: "m",
179            kind: "analysis",
180            members: vec![("A", "c1", ""), ("b", "c2", "pin")],
181            main_source: "// @imports space:X, space:y",
182        };
183        let b = Lineup {
184            main_id: "m",
185            kind: "analysis",
186            members: vec![("B", "c2", "pin"), ("a", "c1", "")],
187            main_source: "// @imports space:Y, space:x, space:x",
188        };
189        assert_eq!(lineup_hash(&crate::WEIRDNET, &a), lineup_hash(&crate::WEIRDNET, &b));
190        let c = Lineup { kind: "transform", ..a.clone() };
191        assert_ne!(lineup_hash(&crate::WEIRDNET, &a), lineup_hash(&crate::WEIRDNET, &c));
192        assert_eq!(lineup_hash(&crate::WEIRDNET, &a).len(), 32);
193    }
194
195    struct G(HashMap<&'static str, &'static str>);
196    impl Graph for G {
197        type Space = String;
198        type Error = SpacesError;
199        fn name<'s>(&self, s: &'s String) -> &'s str {
200            s
201        }
202        fn main_source(&self, s: &String) -> Result<String, SpacesError> {
203            Ok(self.0[s.as_str()].to_string())
204        }
205        fn find(&self, name: &str) -> Option<String> {
206            let n = name.to_lowercase();
207            self.0.contains_key(n.as_str()).then_some(n)
208        }
209    }
210
211    #[test]
212    fn cycles_depth_and_missing_imports() {
213        let g = G(HashMap::from([("a", "// @imports space:b"), ("b", "// @imports space:A"), ("c", "// @imports space:nope"), ("d", "")]));
214        let e = check_cycles(&g, &"a".to_string()).unwrap_err().to_string();
215        assert_eq!(e, "invalid space: a cycle of spaces: a → b → a");
216        let e = check_cycles(&g, &"c".to_string()).unwrap_err().to_string();
217        assert_eq!(e, "invalid space: c: main imports space:nope, which doesn't exist");
218        check_cycles(&g, &"d".to_string()).unwrap();
219        let names = ["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9"];
220        let srcs = [
221            "// @imports space:s1",
222            "// @imports space:s2",
223            "// @imports space:s3",
224            "// @imports space:s4",
225            "// @imports space:s5",
226            "// @imports space:s6",
227            "// @imports space:s7",
228            "// @imports space:s8",
229            "// @imports space:s9",
230            "",
231        ];
232        let g = G(names.iter().copied().zip(srcs).collect());
233        let e = check_cycles(&g, &"s0".to_string()).unwrap_err().to_string();
234        assert!(e.contains("more than 8 deep: s0 → s1 → s2 → s3 → s4 → s5 → s6 → s7 → s8"), "{e}");
235        check_cycles(&g, &"s2".to_string()).unwrap();
236    }
237}