1use std::cmp::Reverse;
65use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
66use std::fmt;
67use std::sync::Arc;
68
69use crate::core::registry::builder::BuildError;
70use crate::core::registry::feature::FlmFeature;
71use crate::model::names::FeatureName;
72
73#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct FeatureChain {
96 names: Vec<FeatureName>,
97 origin: String,
98}
99
100impl FeatureChain {
101 pub fn parse(text: &str, origin: impl Into<String>) -> Result<FeatureChain, ChainError> {
121 let mut names: Vec<FeatureName> = Vec::new();
122 for piece in text.split('<') {
123 let name = piece.trim();
124 if name.is_empty() || name.contains(char::is_whitespace) {
125 return Err(ChainError::NotAChain { text: text.to_string() });
126 }
127 if names.iter().any(|seen| seen.as_str() == name) {
128 return Err(ChainError::RepeatedName {
129 text: text.to_string(),
130 name: FeatureName::from(name),
131 });
132 }
133 names.push(FeatureName::from(name));
134 }
135 if names.len() < 2 {
136 return Err(ChainError::NotAChain { text: text.to_string() });
137 }
138 Ok(FeatureChain { names, origin: origin.into() })
139 }
140
141 pub fn names(&self) -> &[FeatureName] {
143 &self.names
144 }
145
146 pub fn origin(&self) -> &str {
149 &self.origin
150 }
151
152 pub fn with_origin(self, origin: impl Into<String>) -> FeatureChain {
168 FeatureChain { origin: origin.into(), ..self }
169 }
170}
171
172impl fmt::Display for FeatureChain {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 let names: Vec<&str> = self.names.iter().map(|name| name.as_str()).collect();
175 f.write_str(&names.join(" < "))
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
183pub enum ChainError {
184 NotAChain {
188 text: String,
190 },
191 RepeatedName {
193 text: String,
195 name: FeatureName,
197 },
198}
199
200impl fmt::Display for ChainError {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 match self {
203 ChainError::NotAChain { text } => write!(
204 f,
205 "the chain `{text}` must have the form `NAME < NAME < … < NAME`, with two or \
206 more feature names"
207 ),
208 ChainError::RepeatedName { text, name } => write!(
209 f,
210 "each feature must appear only once in the chain `{text}`, but `{name}` appears \
211 more than once"
212 ),
213 }
214 }
215}
216
217impl std::error::Error for ChainError {}
218
219pub(crate) struct Placement {
222 pub(crate) features: Vec<Arc<dyn FlmFeature>>,
224 pub(crate) explicitly_before: BTreeSet<(FeatureName, FeatureName)>,
226 pub(crate) cycle: Option<BuildError>,
229}
230
231pub(crate) fn place(features: Vec<Arc<dyn FlmFeature>>, chains: &[FeatureChain]) -> Placement {
240 let names: Vec<FeatureName> = features.iter().map(|feature| feature.info().name).collect();
241 let mut positions: BTreeMap<&FeatureName, Vec<usize>> = BTreeMap::new();
242 for (position, name) in names.iter().enumerate() {
243 positions.entry(name).or_default().push(position);
244 }
245 let reduced: Vec<Vec<&FeatureName>> = chains
246 .iter()
247 .map(|chain| chain.names.iter().filter(|name| positions.contains_key(name)).collect())
248 .collect();
249
250 let mut successors: BTreeMap<&FeatureName, BTreeSet<&FeatureName>> = BTreeMap::new();
251 let mut preds: BTreeMap<usize, BTreeSet<usize>> =
252 (0..names.len()).map(|position| (position, BTreeSet::new())).collect();
253 for chain in &reduced {
254 for pair in chain.windows(2) {
255 successors.entry(pair[0]).or_default().insert(pair[1]);
256 for &later in &positions[pair[1]] {
257 let set = preds.get_mut(&later).expect("every position has an entry");
258 set.extend(positions[pair[0]].iter().copied());
259 }
260 }
261 }
262
263 let nodes: Vec<usize> = (0..names.len()).collect();
264 let (order, cycle) = match sort_by_priority(&nodes, &preds) {
265 Ok(order) => (order, None),
266 Err(cycle) => {
267 let least = cycle
268 .iter()
269 .enumerate()
270 .min_by_key(|(_, position)| **position)
271 .map(|(at, _)| at)
272 .unwrap_or(0);
273 let mut cycle: Vec<&FeatureName> = cycle.iter().map(|position| &names[*position]).collect();
274 cycle.rotate_left(least);
275 let steps: Vec<(&FeatureName, &FeatureName)> = (0..cycle.len())
276 .map(|at| (cycle[at], cycle[(at + 1) % cycle.len()]))
277 .collect();
278 let mut making: Vec<usize> = Vec::new();
279 for step in &steps {
280 for (index, chain) in reduced.iter().enumerate() {
281 let orders_step = chain.windows(2).any(|pair| (pair[0], pair[1]) == *step);
282 if orders_step && !making.contains(&index) {
283 making.push(index);
284 }
285 }
286 }
287 let error = BuildError::FeatureOrderCycle {
288 cycle: cycle.into_iter().cloned().collect(),
289 chains: making.into_iter().map(|index| chains[index].clone()).collect(),
290 };
291 (nodes, Some(error))
292 }
293 };
294
295 let mut explicitly_before: BTreeSet<(FeatureName, FeatureName)> = BTreeSet::new();
296 for &start in successors.keys() {
297 let mut stack: Vec<&FeatureName> = successors[start].iter().copied().collect();
298 while let Some(next) = stack.pop() {
299 if explicitly_before.insert((start.clone(), next.clone())) {
300 if let Some(further) = successors.get(next) {
301 stack.extend(further.iter().copied());
302 }
303 }
304 }
305 }
306
307 let mut slots: Vec<Option<Arc<dyn FlmFeature>>> = features.into_iter().map(Some).collect();
308 let features = order
309 .into_iter()
310 .map(|position| slots[position].take().expect("each position is placed once"))
311 .collect();
312 Placement { features, explicitly_before, cycle }
313}
314
315pub(crate) fn sort_by_priority<N: Ord + Copy>(
330 nodes: &[N],
331 preds: &BTreeMap<N, BTreeSet<N>>,
332) -> Result<Vec<N>, Vec<N>> {
333 let position: BTreeMap<N, usize> =
334 nodes.iter().enumerate().map(|(at, node)| (*node, at)).collect();
335 let mut waiting: Vec<usize> = nodes.iter().map(|node| preds[node].len()).collect();
336 let mut successors: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];
337 for (at, node) in nodes.iter().enumerate() {
338 for pred in &preds[node] {
339 if let Some(&from) = position.get(pred) {
340 successors[from].push(at);
341 }
342 }
343 }
344 let mut ready: BinaryHeap<Reverse<usize>> =
345 (0..nodes.len()).filter(|at| waiting[*at] == 0).map(Reverse).collect();
346 let mut order: Vec<N> = Vec::with_capacity(nodes.len());
347 while let Some(Reverse(at)) = ready.pop() {
348 order.push(nodes[at]);
349 for &next in &successors[at] {
350 waiting[next] -= 1;
351 if waiting[next] == 0 {
352 ready.push(Reverse(next));
353 }
354 }
355 }
356 if order.len() == nodes.len() {
357 return Ok(order);
358 }
359 let placed: BTreeSet<N> = order.into_iter().collect();
360 let live: BTreeSet<N> = nodes.iter().copied().filter(|node| !placed.contains(node)).collect();
361 let start = *live.iter().next().expect("a cycle has nodes");
362 let mut path: Vec<N> = vec![start];
363 let mut seen: BTreeMap<N, usize> = BTreeMap::from([(start, 0)]);
364 let mut cursor = start;
365 loop {
366 let next = preds[&cursor]
367 .iter()
368 .copied()
369 .find(|pred| live.contains(pred))
370 .expect("a node left unplaced has a predecessor left unplaced");
371 if let Some(&at) = seen.get(&next) {
372 let mut cycle: Vec<N> = path[at..].to_vec();
373 cycle.reverse();
374 return Err(cycle);
375 }
376 seen.insert(next, path.len());
377 path.push(next);
378 cursor = next;
379 }
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385 use crate::core::registry::builder::FeatureBuilder;
386 use crate::core::registry::feature::FeatureInfo;
387
388 struct Named(&'static str);
389
390 impl FlmFeature for Named {
391 fn info(&self) -> FeatureInfo {
392 FeatureInfo::new(self.0, self.0)
393 }
394
395 fn register(&self, _b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
396 Ok(())
397 }
398 }
399
400 fn features(names: &[&'static str]) -> Vec<Arc<dyn FlmFeature>> {
401 names.iter().map(|name| Arc::new(Named(name)) as Arc<dyn FlmFeature>).collect()
402 }
403
404 fn chains(texts: &[&str]) -> Vec<FeatureChain> {
405 texts
406 .iter()
407 .enumerate()
408 .map(|(at, text)| FeatureChain::parse(text, format!("chain {at}")).expect("a chain"))
409 .collect()
410 }
411
412 fn placed(names: &[&'static str], texts: &[&str]) -> Placement {
413 let placement = place(features(names), &chains(texts));
414 if let Some(error) = &placement.cycle {
415 panic!("the features are placed: {error}");
416 }
417 placement
418 }
419
420 fn order_of(placement: &Placement) -> Vec<String> {
421 placement.features.iter().map(|feature| feature.info().name.to_string()).collect()
422 }
423
424 fn before(placement: &Placement, a: &str, b: &str) -> bool {
425 placement.explicitly_before.contains(&(FeatureName::from(a), FeatureName::from(b)))
426 }
427
428 #[test]
429 fn a_chain_reads_names_separated_by_less_than_with_spaces_or_without() {
430 for text in ["a < b < c", "a<b<c", " a <b< c ", "a\t<\nb < c"] {
431 let chain = FeatureChain::parse(text, "here").expect("a chain");
432 assert_eq!(chain.names(), ["a", "b", "c"], "{text}");
433 assert_eq!(chain.to_string(), "a < b < c");
434 }
435 let chain = FeatureChain::parse("userdefs < mymacros", "package mymacros").expect("a chain");
436 assert_eq!(chain.names(), ["userdefs", "mymacros"]);
437 assert_eq!(chain.origin(), "package mymacros");
438 let chain = FeatureChain::parse("a>b < c.d/e", "here").expect("a chain");
441 assert_eq!(chain.names(), ["a>b", "c.d/e"]);
442 }
443
444 #[test]
445 fn a_text_not_of_the_form_is_refused_with_the_form_expected() {
446 for text in ["a", "", " ", "a <", "< a", "a < < b", "a > b", "a, b", "a b < c", "a < b c"] {
447 let error = FeatureChain::parse(text, "here").expect_err(text);
448 assert_eq!(error, ChainError::NotAChain { text: text.to_string() });
449 }
450 }
451
452 #[test]
453 fn a_name_written_twice_is_refused() {
454 let error = FeatureChain::parse("a < b < a", "here").expect_err("a name twice");
455 assert_eq!(error, ChainError::RepeatedName { text: "a < b < a".into(), name: "a".into() });
456 }
457
458 #[test]
459 fn without_chains_the_final_order_is_the_implicit_order() {
460 let placement = placed(&["c", "a", "b"], &[]);
461 assert_eq!(order_of(&placement), ["c", "a", "b"]);
462 assert!(placement.explicitly_before.is_empty());
463 }
464
465 #[test]
466 fn features_not_loaded_drop_out_of_chains() {
467 let names = ["a", "b", "c", "e", "f", "z", "z2"];
469 let placement = placed(&names, &["a < b < f < z", "a < x", "x < c", "b < z < z2", "z < e < z2"]);
470 assert!(before(&placement, "a", "e"), "through `b` and `z`");
471 assert!(!before(&placement, "a", "c") && !before(&placement, "c", "a"));
472 assert!(before(&placement, "a", "z2") && before(&placement, "f", "e"));
473 assert!(!before(&placement, "e", "f") && !before(&placement, "c", "z2"));
474 assert_eq!(order_of(&placement), ["a", "b", "c", "f", "z", "e", "z2"]);
475 let placement = placed(&["c", "a"], &["a < x < c"]);
478 assert!(before(&placement, "a", "c"));
479 assert_eq!(order_of(&placement), ["a", "c"]);
480 }
481
482 #[test]
483 fn ties_are_broken_by_the_implicit_order() {
484 let placement = placed(&["x", "y", "z"], &["z < x"]);
487 assert_eq!(order_of(&placement), ["y", "z", "x"]);
488 let placement = placed(&["p", "b", "q", "a", "r"], &["a < b"]);
490 assert_eq!(order_of(&placement), ["p", "q", "a", "b", "r"]);
491 let placement = placed(&["a", "b", "c", "d"], &["a < c", "b < d"]);
493 assert_eq!(order_of(&placement), ["a", "b", "c", "d"]);
494 }
495
496 #[test]
497 fn a_cycle_among_loaded_features_names_the_cycle_and_its_chains() {
498 let chains = vec![
499 FeatureChain::parse("b < c", "package mymacros").expect("a chain"),
500 FeatureChain::parse("p < q", "package other").expect("a chain"),
501 FeatureChain::parse("c < x < a", "front matter of doc.flm, line 4").expect("a chain"),
502 FeatureChain::parse("a < b", "package base").expect("a chain"),
503 ];
504 let placement = place(features(&["p", "a", "b", "c", "q"]), &chains);
505 assert_eq!(order_of(&placement), ["p", "a", "b", "c", "q"]);
507 let error = placement.cycle.expect("a cycle is an error");
508 match &error {
509 BuildError::FeatureOrderCycle { cycle, chains } => {
510 assert_eq!(cycle, &[FeatureName::from("a"), "b".into(), "c".into()]);
511 let made: Vec<String> = chains.iter().map(|chain| chain.to_string()).collect();
512 assert_eq!(made, ["a < b", "b < c", "c < x < a"]);
513 }
514 other => panic!("unexpected error: {other:?}"),
515 }
516 }
517
518 #[test]
519 fn a_cycle_only_through_a_feature_not_loaded_disappears() {
520 let placement = placed(&["a", "b"], &["a < x", "x < b", "b < a"]);
521 assert_eq!(order_of(&placement), ["b", "a"]);
522 assert!(before(&placement, "b", "a") && !before(&placement, "a", "b"));
523 }
524
525 #[test]
526 fn the_priority_sort_takes_the_first_ready_node_and_finds_a_cycle() {
527 let preds: BTreeMap<u32, BTreeSet<u32>> =
528 BTreeMap::from([(1, BTreeSet::new()), (2, BTreeSet::from([3])), (3, BTreeSet::new())]);
529 assert_eq!(sort_by_priority(&[1, 2, 3], &preds), Ok(vec![1, 3, 2]));
530 let preds: BTreeMap<u32, BTreeSet<u32>> = BTreeMap::from([
531 (1, BTreeSet::new()),
532 (2, BTreeSet::from([4])),
533 (3, BTreeSet::from([2])),
534 (4, BTreeSet::from([3])),
535 ]);
536 assert_eq!(sort_by_priority(&[1, 2, 3, 4], &preds), Err(vec![3, 4, 2]));
538 }
539}