Skip to main content

flm_core/core/registry/
order.rs

1//! The order of features: the chains that state it, and how the registry
2//! build places the features in their final order.
3//!
4//! # Chains
5//!
6//! A **chain** is a statement that some features come in a given order:
7//! the text `a < b < c` places the feature `a` before `b`, and `b` before
8//! `c` ([`FeatureChain`]). Chains name features, never packages. A package
9//! carries the chains it needs
10//! ([`PackageEntry::feature_order`](super::PackageEntry::feature_order)), and
11//! the embedding program gives the chains of a document
12//! ([`RegistryBuilder::feature_order`](super::RegistryBuilder::feature_order)).
13//! The build combines every chain it is given: the union of their statements.
14//!
15//! [`FeatureChain::parse`] reads a chain from its text and checks two things
16//! only: that the text has the form `NAME < NAME < … < NAME`, with two or more
17//! names, and that no name appears twice in it. Whether the names are features
18//! of the registry, and whether the chains contradict each other, is known
19//! only when the registry is built.
20//!
21//! # The final order
22//!
23//! The **implicit order** of the features is the order in which they were
24//! added to the [`RegistryBuilder`](super::RegistryBuilder): each package after
25//! the packages it uses, each package's features in the package's order. Before
26//! the features register, the build places them in their **final order**:
27//!
28//! 1. Each chain is reduced to the features of the registry, in the order
29//!    written: with no feature `x`, the chain `a < x < b` becomes `a < b`. A
30//!    statement about a feature that is not in the registry is thus ignored, a
31//!    misspelled name included.
32//! 2. Two features that are consecutive in a reduced chain are ordered. A
33//!    feature is **explicitly before** another when a sequence of such steps
34//!    leads from the first to the second; the sequence passes only through
35//!    features of the registry. The chains `a < x` and `x < b` place `a`
36//!    before `b` only when `x` is a feature of the registry, while the single
37//!    chain `a < x < b` places `a` before `b` in any case.
38//! 3. The features are sorted so that each comes after every feature
39//!    explicitly before it. At each step, among the features whose explicit
40//!    predecessors are all placed, the one that comes first in the implicit
41//!    order is placed next.
42//!
43//! The sort does not keep the implicit order of every pair of features that
44//! the chains leave unordered: with the implicit order `x`, `y`, `z` and the
45//! single chain `z < x`, the final order is `y`, `z`, `x`. Without any chain,
46//! the final order is the implicit order.
47//!
48//! Chains that order a feature before itself, through features of the
49//! registry, make the build fail with [`BuildError::FeatureOrderCycle`]; the
50//! features then register in their implicit order, so that the first phase of
51//! the build reports its other errors with the cycle. A cycle that passes
52//! through a feature that is not in the registry disappears with the
53//! reduction.
54//!
55//! The final order is the registration order everywhere: the features register
56//! in that order, so it decides the order of the scope stack of the language
57//! (where two features define one name, the definition of the feature placed
58//! last applies), the numbering of what they declare, and the ties between
59//! stages. Whether two features that define one name may do so without an
60//! override depends on whether the feature placed last is explicitly after
61//! the other (see [`crate::lang::mint::packages`]).
62
63use 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/// One chain of the feature order: feature names in the order they are to be
73/// registered, and the text that says where the chain comes from.
74///
75/// The chain `a < b < c` states that the feature `a` comes before `b` and `b`
76/// before `c`. The [module documentation](self) gives how the registry build
77/// combines chains and places the features. Read a chain from its text with
78/// [`FeatureChain::parse`].
79///
80/// `Display` writes the names separated by ` < `.
81///
82/// # Examples
83///
84/// ```
85/// use flm_core::core::registry::FeatureChain;
86///
87/// let chain = FeatureChain::parse("math-mathjax < phfqit", "package phfpack")?;
88/// assert_eq!(chain.names(), ["math-mathjax", "phfqit"]);
89/// assert_eq!(chain.origin(), "package phfpack");
90/// assert_eq!(chain.to_string(), "math-mathjax < phfqit");
91/// # Ok::<(), flm_core::core::registry::ChainError>(())
92/// ```
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct FeatureChain {
95    names: Vec<FeatureName>,
96    origin: String,
97}
98
99impl FeatureChain {
100    /// Reads a chain from `text`, a list of feature names separated by `<`,
101    /// such as `math-mathjax < phfqit`; `origin` says where the chain comes
102    /// from, for messages.
103    ///
104    /// A name is one or more characters, none of them whitespace or `<`.
105    /// Whitespace around each `<` and at either end of the text is allowed.
106    /// The function checks two things only: that the text has the form
107    /// `NAME < NAME < … < NAME`, with two or more names, and that no name
108    /// appears twice. It does not check that the names are features of any
109    /// registry.
110    ///
111    /// The origin is a text the caller chooses, such as `package phfpack` or
112    /// `front matter of doc.flm, line 4`; the registry build quotes it when
113    /// the chain is part of a cycle ([`BuildError::FeatureOrderCycle`]).
114    ///
115    /// # Errors
116    ///
117    /// [`ChainError::NotAChain`] when the text does not have the form, and
118    /// [`ChainError::RepeatedName`] when a name appears twice.
119    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    /// The feature names, in the order the chain places them.
141    pub fn names(&self) -> &[FeatureName] {
142        &self.names
143    }
144
145    /// The text that says where the chain comes from, as given to
146    /// [`FeatureChain::parse`] or [`FeatureChain::with_origin`].
147    pub fn origin(&self) -> &str {
148        &self.origin
149    }
150
151    /// Returns the chain with the origin `origin` in place of its own: for a
152    /// caller that reads a chain before it knows where the chain is written
153    /// (the line of a file, the name of a package).
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use flm_core::core::registry::FeatureChain;
159    ///
160    /// let chain = FeatureChain::parse("math-mathjax < phfqit", "feature_order[1]")?;
161    /// let chain = chain.with_origin("package phfpack");
162    /// assert_eq!(chain.origin(), "package phfpack");
163    /// assert_eq!(chain.to_string(), "math-mathjax < phfqit");
164    /// # Ok::<(), flm_core::core::registry::ChainError>(())
165    /// ```
166    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/// A text that [`FeatureChain::parse`] cannot read as a chain.
179///
180/// `Display` writes the message, which quotes the text as written.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub enum ChainError {
183    /// The text does not have the form `NAME < NAME < … < NAME` with two or
184    /// more names: it holds a single name, an empty name, or a name with
185    /// whitespace in it.
186    NotAChain {
187        /// The text as written.
188        text: String,
189    },
190    /// The text names one feature twice.
191    RepeatedName {
192        /// The text as written.
193        text: String,
194        /// The name that appears twice.
195        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
218/// The features of a build in their final order, and the explicit order
219/// between them.
220pub(crate) struct Placement {
221    /// The features, in their final order.
222    pub(crate) features: Vec<Arc<dyn FlmFeature>>,
223    /// Every pair `(a, b)` of features such that `a` is explicitly before `b`.
224    pub(crate) explicitly_before: BTreeSet<(FeatureName, FeatureName)>,
225    /// [`BuildError::FeatureOrderCycle`] when the reduced chains order a
226    /// feature before itself; the features then keep their implicit order.
227    pub(crate) cycle: Option<BuildError>,
228}
229
230/// Places `features`, given in their implicit order, in their final order
231/// under `chains`, as the [module documentation](self) describes.
232///
233/// When the reduced chains order a feature before itself, the placement keeps
234/// the implicit order and carries [`BuildError::FeatureOrderCycle`]
235/// ([`Placement::cycle`]). The error gives one cycle, from the feature of the
236/// cycle that comes first in the implicit order, and every chain that orders
237/// two consecutive features of the cycle.
238pub(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
314/// Sorts `nodes` so that every node comes after the nodes `preds` gives for
315/// it, taking at each step, among the nodes whose predecessors are all placed,
316/// the one that comes first in `nodes` (Kahn's algorithm with a priority
317/// queue). The registry build sorts features with it, and the plan builder
318/// sorts stages with it.
319///
320/// `preds` holds an entry for every node of `nodes`. A predecessor that is not
321/// among `nodes` is never placed, so a node that has one is never placed
322/// either.
323///
324/// When some nodes cannot be placed, returns one cycle among them: each node
325/// of the returned list comes before the next, and the last before the first.
326/// The search starts from the least node left unplaced and follows, from each
327/// node, its least predecessor left unplaced.
328pub(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        // Any character but whitespace and `<` belongs to a name: no other
438        // character is treated specially.
439        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        // Philippe's example: every feature loaded but `x`.
467        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        // The chain through `x` says nothing about `a` and `c`; the single
475        // chain `a < x < c` would.
476        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        // The example of the guides: the chain `z < x` moves `x` after `z`,
484        // so the pair `x`, `y` does not keep its implicit order.
485        let placement = placed(&["x", "y", "z"], &["z < x"]);
486        assert_eq!(order_of(&placement), ["y", "z", "x"]);
487        // Features no chain names keep their implicit order around the others.
488        let placement = placed(&["p", "b", "q", "a", "r"], &["a < b"]);
489        assert_eq!(order_of(&placement), ["p", "q", "a", "b", "r"]);
490        // A chain that agrees with the implicit order changes nothing.
491        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        // The features keep their implicit order.
505        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        // 4 comes before 2, 2 before 3 and 3 before 4; the search starts from 2.
536        assert_eq!(sort_by_priority(&[1, 2, 3, 4], &preds), Err(vec![3, 4, 2]));
537    }
538}