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_empty(&self) -> bool {
168 self.by_parent.is_empty() && self.peers.is_empty()
169 }
170
171 pub fn resolve(&self, method: &str) -> Option<String> {
177 if self.is_empty() {
178 return None;
179 }
180 let segs: Vec<&str> = method.split('.').collect();
181 if segs.len() < 3 {
182 return None;
183 }
184 let last = segs.len() - 1;
185 let mut cur = segs[0].to_string();
186 let mut through = false;
187 let mut i = 1;
188 while i < last {
189 let seg = segs[i];
190 let literal = format!("{cur}.{seg}");
191 if self.known.contains(&literal) {
192 cur = literal;
193 i += 1;
194 continue;
195 }
196 if let Some(typed) = self.peers.get(&(cur.clone(), seg.to_string())) {
198 if i + 1 >= last {
199 return None;
200 }
201 cur = slot_path(&cur, seg);
202 through = true;
203 i += 2;
204 if !typed {
205 return Some(cur);
206 }
207 continue;
208 }
209 let (slot, typed) = self.by_parent.get(&cur)?;
210 cur = slot_path(&cur, slot);
211 through = true;
212 i += 1;
213 if !typed {
214 return Some(cur);
215 }
216 }
217 through.then(|| format!("{cur}.{}", segs[last]))
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224 use crate::plexus::schema::{MethodSchema, PluginSchema};
225
226 fn planet() -> PluginSchema {
227 let mut p = PluginSchema::leaf(
228 "planet",
229 "1.0",
230 "a planet",
231 vec![MethodSchema::new("info", "d", "h"), MethodSchema::new("rename", "d", "h")],
232 );
233 p.roles.insert("viewer".into(), vec!["planet.info".into()]);
234 p
235 }
236
237 fn solar(typed: bool) -> PluginSchema {
238 let role = MethodRole::DynamicChild {
239 list_method: Some("names".into()),
240 search_method: None,
241 child: typed.then(|| Box::new(planet())),
242 };
243 PluginSchema::leaf(
244 "solar",
245 "1.0",
246 "the system",
247 vec![MethodSchema::new("names", "d", "h"), MethodSchema::new("planet", "d", "h").with_role(role)],
248 )
249 }
250
251 #[test]
252 fn a_typed_slot_is_a_schema_at_its_path() {
253 let (mut typed, mut untyped) = (vec![], vec![]);
254 slot_schemas(&solar(true), &mut typed, &mut untyped);
255 assert!(untyped.is_empty());
256 assert_eq!(typed.len(), 1);
257 assert_eq!(typed[0].namespace, "solar.{planet}");
258 let grants: Vec<_> = typed[0].methods.iter().map(|m| m.grant.clone().unwrap()).collect();
259 assert_eq!(grants, ["solar.{planet}.info", "solar.{planet}.rename"]);
260 assert_eq!(typed[0].roles["viewer"], ["solar.{planet}.info"]);
261 }
262
263 #[test]
264 fn an_untyped_slot_is_its_path() {
265 let (mut typed, mut untyped) = (vec![], vec![]);
266 slot_schemas(&solar(false), &mut typed, &mut untyped);
267 assert!(typed.is_empty());
268 assert_eq!(untyped, ["solar.{planet}"]);
269 }
270
271 #[test]
272 fn a_literal_path_resolves_to_its_slot_and_a_static_child_wins() {
273 let (mut typed, mut untyped) = (vec![], vec![]);
274 let s = solar(true);
275 slot_schemas(&s, &mut typed, &mut untyped);
276 let mut moons = PluginSchema::leaf("solar.luna", "1.0", "a static child", vec![]);
277 moons.methods.push(MethodSchema::new("info", "d", "h"));
278 let all: Vec<PluginSchema> = vec![s, moons].into_iter().chain(typed).collect();
279 let slots = Slots::of(all.iter(), &untyped);
280 assert_eq!(slots.resolve("solar.earth.info").as_deref(), Some("solar.{planet}.info"));
281 assert_eq!(slots.resolve("solar.luna.info"), None, "a static child wins");
282 assert_eq!(slots.resolve("solar.names"), None);
283 assert_eq!(slots.resolve("other.earth.info"), None);
284 }
285
286 #[test]
287 fn an_untyped_slot_resolves_to_the_slot_whole() {
288 let (mut typed, mut untyped) = (vec![], vec![]);
289 let s = solar(false);
290 slot_schemas(&s, &mut typed, &mut untyped);
291 let slots = Slots::of([&s], &untyped);
292 assert_eq!(slots.resolve("solar.earth.info").as_deref(), Some("solar.{planet}"));
293 assert_eq!(slots.resolve("solar.earth.deep.er").as_deref(), Some("solar.{planet}"));
294 }
295
296 #[test]
297 fn a_nested_slot_is_the_same_rule_one_level_at_a_time() {
298 let moon = PluginSchema::leaf("moon", "1.0", "a moon", vec![MethodSchema::new("phase", "d", "h")]);
299 let mut p = planet();
300 p.methods.push(MethodSchema::new("moon", "d", "h").with_role(MethodRole::DynamicChild {
301 list_method: None,
302 search_method: None,
303 child: Some(Box::new(moon)),
304 }));
305 let s = PluginSchema::leaf(
306 "solar",
307 "1.0",
308 "the system",
309 vec![MethodSchema::new("planet", "d", "h").with_role(MethodRole::DynamicChild {
310 list_method: None,
311 search_method: None,
312 child: Some(Box::new(p)),
313 })],
314 );
315 let (mut typed, mut untyped) = (vec![], vec![]);
316 slot_schemas(&s, &mut typed, &mut untyped);
317 let names: Vec<_> = typed.iter().map(|t| t.namespace.as_str()).collect();
318 assert_eq!(names, ["solar.{planet}.{moon}", "solar.{planet}"]);
319 assert_eq!(typed[0].methods[0].grant.as_deref(), Some("solar.{planet}.{moon}.phase"));
320 let all: Vec<PluginSchema> = std::iter::once(s).chain(typed).collect();
321 let slots = Slots::of(all.iter(), &untyped);
322 assert_eq!(slots.resolve("solar.earth.luna.phase").as_deref(), Some("solar.{planet}.{moon}.phase"));
323 }
324}