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