1use std::cmp::Reverse;
20use std::collections::{BTreeMap, BinaryHeap};
21use std::fmt;
22
23use crate::ids::PluginId;
24
25#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct Node {
28 pub id: PluginId,
29 pub requires: Vec<PluginId>,
30 pub priority: i32,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum OrderError {
36 Missing { plugin: PluginId, missing: PluginId },
38 Cycle { path: Vec<PluginId> },
41 Duplicate { id: PluginId },
43}
44
45impl fmt::Display for OrderError {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 match self {
48 OrderError::Missing { plugin, missing } => {
49 write!(
50 f,
51 "plugin `{plugin}` requires `{missing}`, which is not there"
52 )
53 }
54 OrderError::Cycle { path } => {
55 let names: Vec<&str> = path.iter().map(PluginId::as_str).collect();
56 write!(f, "plugins require each other: {}", names.join(" -> "))
57 }
58 OrderError::Duplicate { id } => write!(f, "two plugins have the id `{id}`"),
59 }
60 }
61}
62
63impl std::error::Error for OrderError {}
64
65pub fn order(nodes: &[Node]) -> Result<Vec<usize>, OrderError> {
67 let mut index: BTreeMap<&PluginId, usize> = BTreeMap::new();
68 for (i, n) in nodes.iter().enumerate() {
69 if index.insert(&n.id, i).is_some() {
70 return Err(OrderError::Duplicate { id: n.id.clone() });
71 }
72 }
73 let mut waiting = vec![0usize; nodes.len()];
74 let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
75 for (i, n) in nodes.iter().enumerate() {
76 for r in &n.requires {
77 let &j = index.get(r).ok_or_else(|| OrderError::Missing {
78 plugin: n.id.clone(),
79 missing: r.clone(),
80 })?;
81 waiting[i] += 1;
82 dependents[j].push(i);
83 }
84 }
85 let key = |i: usize| (nodes[i].priority, Reverse(nodes[i].id.clone()), i);
87 let mut ready: BinaryHeap<_> = (0..nodes.len())
88 .filter(|&i| waiting[i] == 0)
89 .map(key)
90 .collect();
91 let mut out = Vec::with_capacity(nodes.len());
92 while let Some((_, _, i)) = ready.pop() {
93 out.push(i);
94 for &d in &dependents[i] {
95 waiting[d] -= 1;
96 if waiting[d] == 0 {
97 ready.push(key(d));
98 }
99 }
100 }
101 if out.len() == nodes.len() {
102 return Ok(out);
103 }
104 let mut at = (0..nodes.len())
106 .find(|&i| waiting[i] > 0)
107 .expect("a plugin left");
108 let mut path: Vec<usize> = Vec::new();
109 loop {
110 if let Some(pos) = path.iter().position(|&p| p == at) {
111 let mut cycle: Vec<PluginId> =
112 path[pos..].iter().map(|&i| nodes[i].id.clone()).collect();
113 cycle.push(nodes[at].id.clone());
114 return Err(OrderError::Cycle { path: cycle });
115 }
116 path.push(at);
117 at = nodes[at]
118 .requires
119 .iter()
120 .map(|r| index[r])
121 .find(|&j| waiting[j] > 0)
122 .expect("a plugin in a cycle requires another left");
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 fn n(id: &'static str, requires: &[&'static str], priority: i32) -> Node {
131 Node {
132 id: PluginId::from_static(id),
133 requires: requires.iter().map(|r| PluginId::from_static(r)).collect(),
134 priority,
135 }
136 }
137
138 fn ids(nodes: &[Node]) -> Vec<&str> {
139 order(nodes)
140 .unwrap()
141 .into_iter()
142 .map(|i| nodes[i].id.as_str())
143 .collect()
144 }
145
146 #[test]
147 fn requirements_then_priority_then_id() {
148 let nodes = [
149 n("theme", &[], 100),
150 n("pages", &["theme", "shell"], 0),
151 n("shell", &["theme"], 0),
152 n("about", &[], 0),
153 n("debug", &["shell"], 50),
154 ];
155 assert_eq!(ids(&nodes), ["theme", "about", "shell", "debug", "pages"]);
156 let mut rev = nodes.to_vec();
158 rev.reverse();
159 assert_eq!(ids(&rev), ["theme", "about", "shell", "debug", "pages"]);
160 }
161
162 #[test]
163 fn errors_are_typed_and_name_the_plugins() {
164 let missing = order(&[n("a", &["ghost"], 0)]).unwrap_err();
165 assert_eq!(
166 missing,
167 OrderError::Missing {
168 plugin: PluginId::from_static("a"),
169 missing: PluginId::from_static("ghost")
170 }
171 );
172 let cycle = order(&[
173 n("x", &[], 0),
174 n("a", &["b"], 0),
175 n("b", &["c"], 0),
176 n("c", &["a"], 0),
177 ])
178 .unwrap_err();
179 assert_eq!(
180 cycle.to_string(),
181 "plugins require each other: a -> b -> c -> a"
182 );
183 let dup = order(&[n("a", &[], 0), n("a", &[], 1)]).unwrap_err();
184 assert!(matches!(dup, OrderError::Duplicate { .. }));
185 assert_eq!(
186 order(&[n("s", &["s"], 0)]).unwrap_err().to_string(),
187 "plugins require each other: s -> s"
188 );
189 }
190}