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//! (among the ordinary declarations of a name in a mode, or among its weak ones
58//! where it has none, the definition of the feature placed last applies), the
59//! numbering of what they declare, and the ties between stages. Whether two
60//! such features may define one name without an override depends on whether
61//! the feature placed last is explicitly after the other (see
62//! [`crate::lang::mint::packages`]).
63
64use 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/// One chain of the feature order: feature names in the order they are to be
74/// registered, and the text that says where the chain comes from.
75///
76/// The chain `a < b < c` states that the feature `a` comes before `b` and `b`
77/// before `c`. The [module documentation](self) gives how the registry build
78/// combines chains and places the features. Read a chain from its text with
79/// [`FeatureChain::parse`].
80///
81/// `Display` writes the names separated by ` < `.
82///
83/// # Examples
84///
85/// ```
86/// use flm_core::core::registry::FeatureChain;
87///
88/// let chain = FeatureChain::parse("userdefs < mymacros", "package mymacros")?;
89/// assert_eq!(chain.names(), ["userdefs", "mymacros"]);
90/// assert_eq!(chain.origin(), "package mymacros");
91/// assert_eq!(chain.to_string(), "userdefs < mymacros");
92/// # Ok::<(), flm_core::core::registry::ChainError>(())
93/// ```
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct FeatureChain {
96    names: Vec<FeatureName>,
97    origin: String,
98}
99
100impl FeatureChain {
101    /// Reads a chain from `text`, a list of feature names separated by `<`,
102    /// such as `userdefs < mymacros`; `origin` says where the chain comes
103    /// from, for messages.
104    ///
105    /// A name is one or more characters, none of them whitespace or `<`.
106    /// Whitespace around each `<` and at either end of the text is allowed.
107    /// The function checks two things only: that the text has the form
108    /// `NAME < NAME < … < NAME`, with two or more names, and that no name
109    /// appears twice. It does not check that the names are features of any
110    /// registry.
111    ///
112    /// The origin is a text the caller chooses, such as `package mymacros` or
113    /// `front matter of doc.flm, line 4`; the registry build quotes it when
114    /// the chain is part of a cycle ([`BuildError::FeatureOrderCycle`]).
115    ///
116    /// # Errors
117    ///
118    /// [`ChainError::NotAChain`] when the text does not have the form, and
119    /// [`ChainError::RepeatedName`] when a name appears twice.
120    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    /// The feature names, in the order the chain places them.
142    pub fn names(&self) -> &[FeatureName] {
143        &self.names
144    }
145
146    /// The text that says where the chain comes from, as given to
147    /// [`FeatureChain::parse`] or [`FeatureChain::with_origin`].
148    pub fn origin(&self) -> &str {
149        &self.origin
150    }
151
152    /// Returns the chain with the origin `origin` in place of its own: for a
153    /// caller that reads a chain before it knows where the chain is written
154    /// (the line of a file, the name of a package).
155    ///
156    /// # Examples
157    ///
158    /// ```
159    /// use flm_core::core::registry::FeatureChain;
160    ///
161    /// let chain = FeatureChain::parse("userdefs < mymacros", "feature_order[1]")?;
162    /// let chain = chain.with_origin("package mymacros");
163    /// assert_eq!(chain.origin(), "package mymacros");
164    /// assert_eq!(chain.to_string(), "userdefs < mymacros");
165    /// # Ok::<(), flm_core::core::registry::ChainError>(())
166    /// ```
167    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/// A text that [`FeatureChain::parse`] cannot read as a chain.
180///
181/// `Display` writes the message, which quotes the text as written.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub enum ChainError {
184    /// The text does not have the form `NAME < NAME < … < NAME` with two or
185    /// more names: it holds a single name, an empty name, or a name with
186    /// whitespace in it.
187    NotAChain {
188        /// The text as written.
189        text: String,
190    },
191    /// The text names one feature twice.
192    RepeatedName {
193        /// The text as written.
194        text: String,
195        /// The name that appears twice.
196        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
219/// The features of a build in their final order, and the explicit order
220/// between them.
221pub(crate) struct Placement {
222    /// The features, in their final order.
223    pub(crate) features: Vec<Arc<dyn FlmFeature>>,
224    /// Every pair `(a, b)` of features such that `a` is explicitly before `b`.
225    pub(crate) explicitly_before: BTreeSet<(FeatureName, FeatureName)>,
226    /// [`BuildError::FeatureOrderCycle`] when the reduced chains order a
227    /// feature before itself; the features then keep their implicit order.
228    pub(crate) cycle: Option<BuildError>,
229}
230
231/// Places `features`, given in their implicit order, in their final order
232/// under `chains`, as the [module documentation](self) describes.
233///
234/// When the reduced chains order a feature before itself, the placement keeps
235/// the implicit order and carries [`BuildError::FeatureOrderCycle`]
236/// ([`Placement::cycle`]). The error gives one cycle, from the feature of the
237/// cycle that comes first in the implicit order, and every chain that orders
238/// two consecutive features of the cycle.
239pub(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
315/// Sorts `nodes` so that every node comes after the nodes `preds` gives for
316/// it, taking at each step, among the nodes whose predecessors are all placed,
317/// the one that comes first in `nodes` (Kahn's algorithm with a priority
318/// queue). The registry build sorts features with it, and the plan builder
319/// sorts stages with it.
320///
321/// `preds` holds an entry for every node of `nodes`. A predecessor that is not
322/// among `nodes` is never placed, so a node that has one is never placed
323/// either.
324///
325/// When some nodes cannot be placed, returns one cycle among them: each node
326/// of the returned list comes before the next, and the last before the first.
327/// The search starts from the least node left unplaced and follows, from each
328/// node, its least predecessor left unplaced.
329pub(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        // Any character but whitespace and `<` belongs to a name: no other
439        // character is treated specially.
440        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        // Philippe's example: every feature loaded but `x`.
468        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        // The chain through `x` says nothing about `a` and `c`; the single
476        // chain `a < x < c` would.
477        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        // The example of the guides: the chain `z < x` moves `x` after `z`,
485        // so the pair `x`, `y` does not keep its implicit order.
486        let placement = placed(&["x", "y", "z"], &["z < x"]);
487        assert_eq!(order_of(&placement), ["y", "z", "x"]);
488        // Features no chain names keep their implicit order around the others.
489        let placement = placed(&["p", "b", "q", "a", "r"], &["a < b"]);
490        assert_eq!(order_of(&placement), ["p", "q", "a", "b", "r"]);
491        // A chain that agrees with the implicit order changes nothing.
492        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        // The features keep their implicit order.
506        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        // 4 comes before 2, 2 before 3 and 3 before 4; the search starts from 2.
537        assert_eq!(sort_by_priority(&[1, 2, 3, 4], &preds), Err(vec![3, 4, 2]));
538    }
539}