1use std::collections::{HashMap, HashSet};
30
31use super::children::qualified;
32use super::schema::{MethodRole, PluginSchema};
33
34pub fn slot_path(parent: &str, slot: &str) -> String {
36 format!("{parent}.{{{slot}}}")
37}
38
39const MAX_DEPTH: usize = 8;
43
44pub fn slot_schemas(schema: &PluginSchema, typed: &mut Vec<PluginSchema>, untyped: &mut Vec<String>) {
49 walk(schema, typed, untyped, 0);
50}
51
52fn walk(schema: &PluginSchema, typed: &mut Vec<PluginSchema>, untyped: &mut Vec<String>, depth: usize) {
53 if depth >= MAX_DEPTH {
54 return;
55 }
56 for m in &schema.methods {
57 if !m.role.is_slot() {
58 continue;
59 }
60 let rel = format!("{{{}}}", m.name);
61 match m.role.slot_schema() {
62 Some(child) => {
63 for q in qualified(&schema.namespace, vec![(rel, child)]) {
64 walk(&q, typed, untyped, depth + 1);
65 typed.push(q);
66 }
67 }
68 None => untyped.push(slot_path(&schema.namespace, &m.name)),
69 }
70 }
71}
72
73std::thread_local! {
74 static BUILDING: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
78}
79
80#[doc(hidden)]
83pub struct Building(());
84
85impl Drop for Building {
86 fn drop(&mut self) {
87 BUILDING.with(|b| {
88 b.borrow_mut().pop();
89 });
90 }
91}
92
93#[doc(hidden)]
96pub fn building(name: &'static str) -> Building {
97 BUILDING.with(|b| b.borrow_mut().push(name));
98 Building(())
99}
100
101pub fn slot_type<T: super::Activation>() -> Option<Box<PluginSchema>> {
109 let name = std::any::type_name::<<T as super::Activation>::Methods>();
110 if BUILDING.with(|b| b.borrow().contains(&name)) {
111 return None;
112 }
113 T::slot_schema().map(Box::new)
114}
115
116#[derive(Debug, Default, Clone)]
118pub struct Slots {
119 by_parent: HashMap<String, (String, bool)>,
122 peers: HashMap<(String, String), bool>,
125 known: HashSet<String>,
128}
129
130impl Slots {
131 pub fn of<'a>(schemas: impl IntoIterator<Item = &'a PluginSchema>, untyped: &[String]) -> Self {
134 let mut s = Slots::default();
135 for schema in schemas {
136 s.add(schema);
137 }
138 for u in untyped {
139 s.add_untyped(u);
140 }
141 s
142 }
143
144 pub fn add(&mut self, schema: &PluginSchema) {
146 self.known.insert(schema.namespace.clone());
147 for m in &schema.methods {
148 let typed = m.role.slot_schema().is_some();
149 match &m.role {
150 MethodRole::Peer { .. } => {
151 self.peers.insert((schema.namespace.clone(), m.name.clone()), typed);
152 }
153 MethodRole::DynamicChild { .. } => {
154 self.by_parent.entry(schema.namespace.clone()).or_insert((m.name.clone(), typed));
155 }
156 _ => {}
157 }
158 }
159 }
160
161 pub fn add_untyped(&mut self, path: &str) {
163 self.known.insert(path.to_string());
164 }
165
166 pub fn is_untyped_peer_slot(&self, path: &str) -> bool {
172 let Some((parent, slot)) = path.strip_suffix('}').and_then(|p| p.rsplit_once(".{")) else { return false };
173 self.peers.get(&(parent.to_string(), slot.to_string())) == Some(&false)
174 }
175
176 pub fn is_empty(&self) -> bool {
178 self.by_parent.is_empty() && self.peers.is_empty()
179 }
180
181 pub fn resolve(&self, method: &str) -> Option<String> {
187 if self.is_empty() {
188 return None;
189 }
190 let segs: Vec<&str> = method.split('.').collect();
191 if segs.len() < 3 {
192 return None;
193 }
194 let last = segs.len() - 1;
195 let mut cur = segs[0].to_string();
196 let mut through = false;
197 let mut i = 1;
198 while i < last {
199 let seg = segs[i];
200 let literal = format!("{cur}.{seg}");
201 if self.known.contains(&literal) {
202 cur = literal;
203 i += 1;
204 continue;
205 }
206 if let Some(typed) = self.peers.get(&(cur.clone(), seg.to_string())) {
208 if i + 1 >= last {
209 return None;
210 }
211 cur = slot_path(&cur, seg);
212 through = true;
213 i += 2;
214 if !typed {
215 return Some(cur);
216 }
217 continue;
218 }
219 let (slot, typed) = self.by_parent.get(&cur)?;
220 cur = slot_path(&cur, slot);
221 through = true;
222 i += 1;
223 if !typed {
224 return Some(cur);
225 }
226 }
227 through.then(|| format!("{cur}.{}", segs[last]))
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234 use crate::plexus::schema::{MethodSchema, PluginSchema};
235
236 fn planet() -> PluginSchema {
237 let mut p = PluginSchema::leaf(
238 "planet",
239 "1.0",
240 "a planet",
241 vec![MethodSchema::new("info", "d", "h"), MethodSchema::new("rename", "d", "h")],
242 );
243 p.roles.insert("viewer".into(), vec!["planet.info".into()]);
244 p
245 }
246
247 fn solar(typed: bool) -> PluginSchema {
248 let role = MethodRole::DynamicChild {
249 list_method: Some("names".into()),
250 search_method: None,
251 child: typed.then(|| Box::new(planet())),
252 };
253 PluginSchema::leaf(
254 "solar",
255 "1.0",
256 "the system",
257 vec![MethodSchema::new("names", "d", "h"), MethodSchema::new("planet", "d", "h").with_role(role)],
258 )
259 }
260
261 #[test]
262 fn a_typed_slot_is_a_schema_at_its_path() {
263 let (mut typed, mut untyped) = (vec![], vec![]);
264 slot_schemas(&solar(true), &mut typed, &mut untyped);
265 assert!(untyped.is_empty());
266 assert_eq!(typed.len(), 1);
267 assert_eq!(typed[0].namespace, "solar.{planet}");
268 let grants: Vec<_> = typed[0].methods.iter().map(|m| m.grant.clone().unwrap()).collect();
269 assert_eq!(grants, ["solar.{planet}.info", "solar.{planet}.rename"]);
270 assert_eq!(typed[0].roles["viewer"], ["solar.{planet}.info"]);
271 }
272
273 #[test]
274 fn an_untyped_slot_is_its_path() {
275 let (mut typed, mut untyped) = (vec![], vec![]);
276 slot_schemas(&solar(false), &mut typed, &mut untyped);
277 assert!(typed.is_empty());
278 assert_eq!(untyped, ["solar.{planet}"]);
279 }
280
281 #[test]
282 fn a_literal_path_resolves_to_its_slot_and_a_static_child_wins() {
283 let (mut typed, mut untyped) = (vec![], vec![]);
284 let s = solar(true);
285 slot_schemas(&s, &mut typed, &mut untyped);
286 let mut moons = PluginSchema::leaf("solar.luna", "1.0", "a static child", vec![]);
287 moons.methods.push(MethodSchema::new("info", "d", "h"));
288 let all: Vec<PluginSchema> = vec![s, moons].into_iter().chain(typed).collect();
289 let slots = Slots::of(all.iter(), &untyped);
290 assert_eq!(slots.resolve("solar.earth.info").as_deref(), Some("solar.{planet}.info"));
291 assert_eq!(slots.resolve("solar.luna.info"), None, "a static child wins");
292 assert_eq!(slots.resolve("solar.names"), None);
293 assert_eq!(slots.resolve("other.earth.info"), None);
294 }
295
296 #[test]
297 fn an_untyped_slot_resolves_to_the_slot_whole() {
298 let (mut typed, mut untyped) = (vec![], vec![]);
299 let s = solar(false);
300 slot_schemas(&s, &mut typed, &mut untyped);
301 let slots = Slots::of([&s], &untyped);
302 assert_eq!(slots.resolve("solar.earth.info").as_deref(), Some("solar.{planet}"));
303 assert_eq!(slots.resolve("solar.earth.deep.er").as_deref(), Some("solar.{planet}"));
304 }
305
306 #[test]
307 fn a_nested_slot_is_the_same_rule_one_level_at_a_time() {
308 let moon = PluginSchema::leaf("moon", "1.0", "a moon", vec![MethodSchema::new("phase", "d", "h")]);
309 let mut p = planet();
310 p.methods.push(MethodSchema::new("moon", "d", "h").with_role(MethodRole::DynamicChild {
311 list_method: None,
312 search_method: None,
313 child: Some(Box::new(moon)),
314 }));
315 let s = PluginSchema::leaf(
316 "solar",
317 "1.0",
318 "the system",
319 vec![MethodSchema::new("planet", "d", "h").with_role(MethodRole::DynamicChild {
320 list_method: None,
321 search_method: None,
322 child: Some(Box::new(p)),
323 })],
324 );
325 let (mut typed, mut untyped) = (vec![], vec![]);
326 slot_schemas(&s, &mut typed, &mut untyped);
327 let names: Vec<_> = typed.iter().map(|t| t.namespace.as_str()).collect();
328 assert_eq!(names, ["solar.{planet}.{moon}", "solar.{planet}"]);
329 assert_eq!(typed[0].methods[0].grant.as_deref(), Some("solar.{planet}.{moon}.phase"));
330 let all: Vec<PluginSchema> = std::iter::once(s).chain(typed).collect();
331 let slots = Slots::of(all.iter(), &untyped);
332 assert_eq!(slots.resolve("solar.earth.luna.phase").as_deref(), Some("solar.{planet}.{moon}.phase"));
333 }
334}