Skip to main content

flm_core/core/settings/
cascade.rs

1//! Combining settings written in several ranked sources into one value per
2//! feature and key, each value keeping where it was written.
3//!
4//! A host that reads settings from several places (a program's defaults, the
5//! packages a document uses, the document's front matter, a command line, …)
6//! records every value written in a [`Cascade`], each with its *origin*: where
7//! it was written, as the host knows it. The origin is the host's own type,
8//! which implements [`CascadeOrigin`]: it gives the cascade the source's rank,
9//! and, for a source that is a package, the package's identity. The cascade
10//! decides which value results for each key by the rule below, reads the result
11//! through each feature's [settings declaration](crate::core::settings::SettingsDecl)
12//! ([`Cascade::read`]) and reports every problem found at the origin of the
13//! value at fault ([`Problem`]). The rank order, the sources and the texts that
14//! show an origin are the host's; this module reads no file, parses no
15//! notation and does not touch the machine.
16//!
17//! One rule applies to every key: the source of the highest rank that writes a
18//! key gives its value, whole, replacing what lower sources wrote. Within a rank
19//! whose origins have no [peer](CascadeOrigin::peer), the value written last
20//! wins. Every value written is kept, and the rule is applied when the settings
21//! are read.
22//!
23//! # The rule between packages
24//!
25//! Between packages (the origins of a rank that answer
26//! [`peer`](CascadeOrigin::peer) with the package's identity), the packages'
27//! uses decide. A package *reaches* the packages it uses, and the packages those
28//! reach ([`Reach`], computed by
29//! [`PackageCatalog::reach`](crate::core::registry::PackageCatalog::reach) and
30//! given to [`Cascade::with_reach`]). Among the packages that write one key, a
31//! package that another writer reaches does not count, unless it reaches that
32//! writer too. So a package wins over the packages it uses, directly or through
33//! others, without any message: a package `my-article` that uses `article` and
34//! changes one of its values gives that value. The packages that count are
35//! *peers*: sources of one rank, none of which wins over another. Peers that
36//! write the same value for a key agree; peers that write two different values
37//! are a problem, unless a source of a higher rank also writes the key and so
38//! decides it. Two packages that reach each other (a loop of uses) are peers,
39//! and so are two packages of which neither reaches the other. Neither the order
40//! of the uses nor the order in which the values are added changes the result.
41//! The settings that several packages give a workflow follow the same rule, by
42//! the packages they are written in.
43//!
44//! # Values combined key by key
45//!
46//! The marks of a feature's settings declaration ([`Mark`]) decide how a value
47//! is combined, at any depth below a key; the cascade names no feature and no
48//! key of its own.
49//!
50//! - **[`Mark::MergeObjectKeyValues`]**: the sources' values of an object that
51//!   carries the mark are combined key by key. Each key of the object is
52//!   decided by the rule above (the source of the highest rank that writes it
53//!   gives its value whole, and two peers must agree on it); where the node of
54//!   that key carries the mark too, the rule applies again one level down. The
55//!   feature's own default of the object (the default of its node,
56//!   [`default_entries`](SettingsDecl::default_entries), or the entry of the
57//!   default above it) is the lowest source, so that a source adds a key and
58//!   leaves the others. The keys are ordered by source, lowest rank first,
59//!   the default's first, each source's keys in the order written, and a
60//!   replaced key keeps its position. A value that is not an object where the
61//!   mark stands is a problem at its origin.
62//! - **[`Mark::RemoveKeyWhenValueIsFalse`]**: in an object that carries the
63//!   mark, a key whose combined value is `false` is left out, a key of the
64//!   feature's own default included.
65//! - **[`Mark::SetToDefaultWithNull`]**: a setting that carries the mark and
66//!   whose combined value is `null` is left out of the combined settings, so
67//!   that whatever reads them applies the setting's default.
68//!
69//! Nothing else is combined inside a value. Each value that the rule decides
70//! keeps the origin of the write that gives it, at every depth
71//! ([`KeyInEffect::entry_origins`], [`KeyInEffect::below`]), and
72//! [`Cascade::writes_at`] lists every source's value at one place, and
73//! [`Cascade::decided_at`] finds the place decided whole that holds it.
74//!
75//! # The fields of a workflow
76//!
77//! The fields of a workflow that packages write (`extends`, `outputs`,
78//! `demands`, `prefer`, `docs`) are values too, one per workflow and field, and
79//! follow the same rule between peers ([`Cascade::add_workflow_fields`]).
80//! [`Cascade::workflows`] returns the resulting fields per workflow, which
81//! [`workflow_def`] turns into the library's [`WorkflowDef`]; the host gives
82//! these to the library, which combines them with the workflow of that name
83//! defined by the compiled packages, if they define one
84//! ([`RegistryBuilder::workflow_fields`](crate::core::registry::RegistryBuilder::workflow_fields)).
85//! Each field keeps its origin, so that a problem with it is reported there.
86//!
87//! The settings a package gives a workflow are values of an origin that names
88//! the workflow ([`CascadeOrigin::workflow`]): such an origin may set only keys
89//! that are set per render request ([`Bind::Render`]).
90//!
91//! # Switching a feature off
92//!
93//! A source may switch a feature off ([`Cascade::switch_off`]) or on
94//! ([`Cascade::switch_on`]), and records the feature's keys apart
95//! ([`Cascade::set`]), whichever way it switches it: a source may set keys of a
96//! feature it switches off. The source of the highest rank that switches the
97//! feature decides whether it is off, and two peers of which one switches it off
98//! and the other on are a problem. So a higher source switches on a feature that
99//! a package switched off. When the feature is on, its keys are combined over
100//! every source by the rule above; when it is off, none of its keys is read,
101//! whatever source set it, the source that switched it off included. A key
102//! recorded with [`Cascade::set`] alone does not switch a feature on.
103//!
104//! # A feature that no package in use has
105//!
106//! Whatever a source writes for a feature that no package in use has, a switch
107//! either way or any key, is accepted and read by nothing: a source may keep
108//! the settings of a package that the document does not use at the moment.
109//! Since the name may be misspelled, each source that writes such a feature
110//! gives one warning, at the first origin recorded for it, returned whether or
111//! not the reading finds problems ([`ReadSettings::warnings`],
112//! [`ReadFailure::warnings`]). A source is told apart from the others by its
113//! origins' rank, [`peer`](CascadeOrigin::peer) and
114//! [`workflow`](CascadeOrigin::workflow): in a rank in which the value written
115//! last wins, every origin is of one source. Such a feature has no entry among
116//! the settings in effect ([`Cascade::in_effect`]).
117//!
118//! # Entries that another feature declares
119//!
120//! A feature may declare the schema of one entry of a map that a key of
121//! another feature holds, at a place that the owner of the key opens
122//! ([`EntryDecl`], [`SettingsDecl::open_entries`], [`SettingsDecl::entry_data`]).
123//! The declaration of an entry is in force when its feature and the owner are
124//! among the features of the packages in use and neither is switched off; the
125//! cascade then combines and reads the owner's settings by the owner's
126//! declaration combined with those of its entries in force
127//! ([`declaration_in_force`]):
128//!
129//! - the marks of an entry's schema apply to the values written under the
130//!   entry;
131//! - a key written under an entry that the entry's schema does not declare is
132//!   left out of the combined settings, with a warning at the origin of each
133//!   write of it ([`WarningKind::UndeclaredKey`]);
134//! - an entry that nothing declares is accepted as written and read by
135//!   whatever reads the owner's key;
136//! - two features that declare one entry, and a declaration of an entry at a
137//!   place that the owner does not open, are problems of [`Cascade::read`]
138//!   without an origin, which name the features' packages.
139//!
140//! # Reading the combined settings
141//!
142//! [`Cascade::read`] reads the combined data through each feature's settings
143//! declaration, as the package factories list them, into the settings each
144//! package is built from and the option values set on the document and on the
145//! render request, with the warnings ([`ReadSettings`]), or, when it finds problems, those
146//! problems with the warnings ([`ReadFailure`]); [`Cascade::parsing`] reads the parsing
147//! settings ([`FlmParsing`]), combined key by key by the same rule. Each path
148//! in a value that the feature marks as a path to a file ([`Mark::Path`]) is
149//! first given by its origin the form its reader receives
150//! ([`CascadeOrigin::resolve_path`]).
151//!
152//! Every feature of the packages in use that declares settings is read at each
153//! reading, whether or not anything is written under it. A feature nothing is
154//! written for is read from the empty map, so that its package receives the
155//! configuration its declaration reads from it ([`SettingsDecl::read`]): the
156//! type's default for a configuration declared with a Rust type, and the
157//! reader's answer for one declared with a reader
158//! ([`SettingsDecl::config_data_read`]). A problem found then has no origin.
159//!
160//! [`Cascade::in_effect`] returns the combined data that [`Cascade::read`]
161//! reads, before any declaration reads it: for each feature written, whether
162//! it is switched off and where, and the value in effect of each key written,
163//! with where it was written ([`FeatureInEffect`]). A host uses it to show each
164//! setting's value and its origin.
165
166use std::borrow::Cow;
167use std::collections::{BTreeMap, BTreeSet};
168use std::fmt;
169
170use serde_json::{Map, Value};
171
172use crate::core::registry::{PackageFactory, WorkflowDef};
173use crate::core::settings::{EntryDecl, Mark, PackageSettings, SettingsDecl, texts_at};
174use crate::lang::FlmParsing;
175use crate::model::names::Name;
176use crate::model::options::{Bind, OptionValues};
177
178/// Where a value was written, as the host knows it: the host's own type, which
179/// the cascade compares, clones and shows (its `Display` text is how a message
180/// refers to it, "`a.yaml:2:1`", "the program's defaults").
181///
182/// Every origin of one rank answers [`peer`](CascadeOrigin::peer) alike: all
183/// with a package's identity (a rank of packages, decided by the reach), or all
184/// with `None` (a rank in which the value written last wins).
185pub trait CascadeOrigin: Clone + fmt::Display + fmt::Debug + PartialEq {
186    /// The rank of the source: a higher rank replaces what a lower one writes.
187    fn rank(&self) -> u32;
188    /// For a source that is a package: the package's identity (its factory
189    /// name), by which the reach decides between two packages of one rank.
190    /// `None` for a rank in which the value written last wins. Every origin of
191    /// one rank answers alike.
192    fn peer(&self) -> Option<&str>;
193    /// For the settings a package gives a workflow: the workflow's name. Such a
194    /// source may set only keys bound to the render request.
195    fn workflow(&self) -> Option<&str>;
196    /// The source of a higher rank in which a person can write a setting, as a
197    /// message names it ("the document's front matter"); `None` when there is
198    /// none. The message about packages that disagree suggests it.
199    fn higher_source(&self) -> Option<&str>;
200    /// A path in a value marked [`Mark::Path`], as its reader receives it,
201    /// given the place where the origin was written; `Ok(None)` leaves the
202    /// path as written.
203    ///
204    /// # Errors
205    ///
206    /// The text of a path that has no meaning where the origin was written,
207    /// which the cascade reports as a problem at the origin.
208    fn resolve_path(&self, path: &str) -> Result<Option<String>, String>;
209}
210
211/// Which packages each package *reaches*: for each package, by its factory's
212/// name, the names of the factories of the packages it uses, directly or
213/// through others ([`PackageCatalog::reach`](crate::core::registry::PackageCatalog::reach)).
214/// A package wins over the packages it reaches; see the [module
215/// documentation](self#the-rule-between-packages).
216pub type Reach = BTreeMap<Name, BTreeSet<Name>>;
217
218/// One setting's value, as JSON data, with where it was written.
219#[derive(Debug, Clone, PartialEq)]
220pub struct SettingValue<O> {
221    /// The value, as data.
222    pub value: Value,
223    /// Where it was written.
224    pub origin: O,
225}
226
227/// A problem with the settings: the message, and where the value at fault was
228/// written when that is known. Its `Display` text is
229/// [`detail`](Problem::detail). [`Cascade::read`] returns the problems that are
230/// errors in [`ReadFailure::errors`], and those that are warnings, each with its
231/// kind ([`Warning`]), in [`ReadSettings::warnings`] or, beside errors, in
232/// [`ReadFailure::warnings`].
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct Problem<O> {
235    /// Where the value at fault was written; `None` when that is not known,
236    /// as for a feature nothing is written for, read from the empty map.
237    pub origin: Option<O>,
238    /// The problem, as a text for a reader.
239    pub detail: String,
240}
241
242/// A value that the settings accept and that may be a mistake, as
243/// [`Cascade::read`] finds it: what kind of value it is, where it was written
244/// and the message ([`ReadSettings::warnings`]).
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct Warning<O> {
247    /// What the value is.
248    pub kind: WarningKind,
249    /// Where the value was written, and the message.
250    pub problem: Problem<O>,
251}
252
253/// The kinds of [`Warning`].
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
255pub enum WarningKind {
256    /// A source writes a feature that no package in use has (see the [module
257    /// documentation](self#a-feature-that-no-package-in-use-has)): accepted and
258    /// read by nothing. One warning per source, at its first origin.
259    UnknownFeature,
260    /// A source writes, under an entry in force that another feature declares
261    /// ([`EntryDecl`]), a key that the entry does not declare: left out of the
262    /// combined settings. One warning per write of the key, at its origin.
263    UndeclaredKey,
264}
265
266impl<O> fmt::Display for Problem<O> {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        f.write_str(&self.detail)
269    }
270}
271
272impl<O: fmt::Debug> std::error::Error for Problem<O> {}
273
274/// Whether the source `winner` wins over `other`, a source of the same rank, by
275/// the packages they are written in: `winner`'s package reaches `other`'s, and
276/// `other`'s does not reach `winner`'s (two packages that reach each other are
277/// peers).
278fn wins_over<O: CascadeOrigin>(reach: &Reach, winner: &O, other: &O) -> bool {
279    let (Some(winner), Some(other)) = (winner.peer(), other.peer()) else { return false };
280    let reaches = |from: &str, to: &str| reach.get(from).is_some_and(|reached| reached.contains(to));
281    winner != other && reaches(winner, other) && !reaches(other, winner)
282}
283
284/// The resulting value for one key or one switch, and the values that its peers
285/// wrote that differ from it.
286#[derive(Debug, Clone)]
287struct Written<T, O> {
288    value: T,
289    origin: O,
290    disagreeing: Vec<(T, O)>,
291}
292
293/// Returns the position in `writes` (every value each source wrote for one
294/// setting, in the order written) of the resulting value by the rule of the
295/// ranks, with the positions of the values its peers wrote that differ from
296/// it. The sources of the highest rank that writes the setting decide. Within
297/// a rank without peers, the value written last results. Within a rank of
298/// peers, the sources that count are those over which no other wins
299/// ([`wins_over`], by `reach`); the first of them written results, and the
300/// others that differ from it are disagreeing. Which sources count does not
301/// depend on the order written.
302// Peers must agree, and a package changes another's value only by naming it
303// in its `use` list: a package added beside the others never silently
304// changes a value, and each value in force comes from one source.
305fn decide_at<T: PartialEq, O: CascadeOrigin>(writes: &[(&T, &O)], reach: &Reach) -> Option<(usize, Vec<usize>)> {
306    let top = writes.iter().map(|(_, origin)| origin.rank()).max()?;
307    let at_top: Vec<usize> = (0..writes.len()).filter(|at| writes[*at].1.rank() == top).collect();
308    if !at_top.iter().any(|at| writes[*at].1.peer().is_some()) {
309        return Some((*at_top.last()?, Vec::new()));
310    }
311    let mut counting =
312        at_top.iter().copied().filter(|at| !at_top.iter().any(|other| wins_over(reach, writes[*other].1, writes[*at].1)));
313    let first = counting.next()?;
314    let disagreeing = counting.filter(|at| writes[*at].0 != writes[first].0).collect();
315    Some((first, disagreeing))
316}
317
318impl<T: PartialEq + Clone, O: CascadeOrigin> Written<T, O> {
319    /// Returns the resulting value among `writes`, every value each source wrote
320    /// for one setting, in the order written, by the rule of the ranks
321    /// ([`decide_at`]), with the values of its peers that differ from it.
322    fn decide<'w>(writes: impl IntoIterator<Item = (&'w T, &'w O)>, reach: &Reach) -> Option<Written<T, O>>
323    where
324        T: 'w,
325        O: 'w,
326    {
327        let writes: Vec<(&T, &O)> = writes.into_iter().collect();
328        let (first, disagreeing) = decide_at(&writes, reach)?;
329        let (value, origin) = writes[first];
330        let disagreeing = disagreeing.into_iter().map(|at| (writes[at].0.clone(), writes[at].1.clone())).collect();
331        Some(Written { value: value.clone(), origin: origin.clone(), disagreeing })
332    }
333
334    /// Returns the problem of peers that disagree, if they do: `what` identifies
335    /// the setting, `show` writes one of its values, and `higher_writes` says
336    /// whether the higher source the resulting origin names
337    /// ([`CascadeOrigin::higher_source`]) can write the setting, and so decide
338    /// it.
339    fn disagreement(&self, what: &str, show: impl Fn(&T) -> String, higher_writes: bool) -> Option<Problem<O>> {
340        if self.disagreeing.is_empty() {
341            return None;
342        }
343        let others: Vec<String> =
344            self.disagreeing.iter().map(|(value, origin)| format!("{} at {origin}", show(value))).collect();
345        let settle = match self.origin.higher_source() {
346            Some(higher) if higher_writes => format!(
347                "; make the values agree, make one of these packages use the other, or set the value in {higher}"
348            ),
349            _ => String::from("; make the values agree, or make one of these packages use the other"),
350        };
351        Some(Problem {
352            origin: Some(self.origin.clone()),
353            detail: format!(
354                "the packages that set {what} must agree on its value when none of them uses another, directly \
355                 or through other packages (the value of a package replaces those of the packages it uses), but {} \
356                 is set at {} and {}{settle}",
357                show(&self.value),
358                self.origin,
359                others.join(" and ")
360            ),
361        })
362    }
363}
364
365/// The settings of one feature: every value each source wrote for each key, in
366/// the order written, combined when they are read (a value combined key by key
367/// is so by the marks of the feature's declaration alone).
368#[derive(Debug, Clone)]
369struct FeatureValues<O> {
370    keys: BTreeMap<String, Vec<SettingValue<O>>>,
371    /// Whether the feature is off, as each source that switches it off (`true`
372    /// here) or on (`false`) says, in the order recorded.
373    off: Vec<(bool, O)>,
374    /// The origin of every key and every switch recorded for the feature, in the
375    /// order recorded.
376    written: Vec<O>,
377}
378
379impl<O> Default for FeatureValues<O> {
380    fn default() -> FeatureValues<O> {
381        FeatureValues { keys: BTreeMap::new(), off: Vec::new(), written: Vec::new() }
382    }
383}
384
385/// Whether the origins `a` and `b` are of one source: of one rank, one peer and
386/// one workflow (see the [module
387/// documentation](self#a-feature-that-no-package-in-use-has)).
388fn same_source<O: CascadeOrigin>(a: &O, b: &O) -> bool {
389    a.rank() == b.rank() && a.peer() == b.peer() && a.workflow() == b.workflow()
390}
391
392/// The settings written in every source, each value with its origin, combined
393/// by the rule of the ranks when they are read. See the [module
394/// documentation](self).
395///
396/// The host records every value written ([`set`](Cascade::set),
397/// [`switch_off`](Cascade::switch_off), [`switch_on`](Cascade::switch_on),
398/// [`set_parsing`](Cascade::set_parsing),
399/// [`add_workflow_fields`](Cascade::add_workflow_fields)), in any order, then
400/// reads the result with [`read`](Cascade::read),
401/// [`parsing`](Cascade::parsing) and [`workflows`](Cascade::workflows).
402#[derive(Debug, Clone)]
403pub struct Cascade<O: CascadeOrigin> {
404    features: BTreeMap<String, FeatureValues<O>>,
405    parsing: BTreeMap<String, Vec<(Value, O)>>,
406    /// The fields of workflows, by the workflow's name and then the field's; a
407    /// workflow a package writes with settings alone is here with no field.
408    workflow_fields: BTreeMap<String, BTreeMap<String, Vec<(Value, O)>>>,
409    /// Which package reaches which, deciding between sources of one rank.
410    reach: Reach,
411}
412
413impl<O: CascadeOrigin> Default for Cascade<O> {
414    fn default() -> Cascade<O> {
415        Cascade {
416            features: BTreeMap::new(),
417            parsing: BTreeMap::new(),
418            workflow_fields: BTreeMap::new(),
419            reach: Reach::new(),
420        }
421    }
422}
423
424/// The settings once read through the features' declarations, as
425/// [`Cascade::read`] returns them, with the warnings found while reading them.
426#[derive(Debug, Clone)]
427pub struct ReadSettings<O> {
428    /// The settings each package is built from, by the package's name.
429    pub packages: BTreeMap<Name, PackageSettings>,
430    /// The option values to set on the document.
431    pub document: OptionValues,
432    /// The option values to set on the render request (the plan request's
433    /// render options).
434    pub render: OptionValues,
435    /// The values accepted that may be mistakes, each with its kind and its
436    /// origin, in the order found: one for each source that writes a feature
437    /// that no package in use has (see the [module
438    /// documentation](self#a-feature-that-no-package-in-use-has)), and one for
439    /// each write of a key that an entry in force does not declare (see the
440    /// [module documentation](self#entries-that-another-feature-declares)).
441    /// The host reports each of them as a warning.
442    pub warnings: Vec<Warning<O>>,
443}
444
445/// The error of [`Cascade::read`] when the settings have problems: the problems,
446/// and the warnings found while reading them, which the host reports with the
447/// problems.
448#[derive(Debug, Clone, PartialEq, Eq)]
449pub struct ReadFailure<O> {
450    /// The problems, each at the origin of the value at fault; a problem
451    /// found in reading a feature that nothing is written for has no origin.
452    pub errors: Vec<Problem<O>>,
453    /// The values accepted that may be mistakes, as in [`ReadSettings::warnings`].
454    pub warnings: Vec<Warning<O>>,
455}
456
457impl<O> Default for ReadSettings<O> {
458    fn default() -> ReadSettings<O> {
459        ReadSettings {
460            packages: BTreeMap::new(),
461            document: OptionValues::default(),
462            render: OptionValues::default(),
463            warnings: Vec::new(),
464        }
465    }
466}
467
468/// The settings of one feature in effect, as [`Cascade::in_effect`] returns
469/// them: whether a source switched the feature off, and the value in effect of
470/// each key that a source wrote, each with where it was written.
471#[derive(Debug, Clone, PartialEq)]
472pub struct FeatureInEffect<O> {
473    /// Where the feature was switched off, when the source that decides
474    /// whether it is off switches it off (see the [module
475    /// documentation](self#switching-a-feature-off)). None of the keys of a
476    /// feature switched off is in effect, so [`keys`](FeatureInEffect::keys) is
477    /// then empty.
478    pub switched_off: Option<O>,
479    /// The value in effect of each key that a source wrote, by the key's name.
480    /// A key that no source wrote is absent.
481    pub keys: BTreeMap<String, KeyInEffect<O>>,
482}
483
484/// The value in effect of one key of a feature: the value combined from every
485/// source that wrote the key, by the rule of the ranks, with where it was
486/// written.
487#[derive(Debug, Clone, PartialEq)]
488pub struct KeyInEffect<O> {
489    /// The value, as data, with every path that the feature marks as a path to
490    /// a file in the form its origin gives it ([`CascadeOrigin::resolve_path`]). For a key whose value is
491    /// combined key by key, the feature's own default combined with every
492    /// source's value, one key at a time, at every depth that the marks name
493    /// (see the [module documentation](self#values-combined-key-by-key)).
494    pub value: Value,
495    /// Where the value was written. For a key whose value is combined key by
496    /// key, the origin of the highest rank among those that wrote the key (of
497    /// several of that rank, the one recorded last); each key of the value has
498    /// its own origin in [`entry_origins`](KeyInEffect::entry_origins).
499    pub origin: O,
500    /// For a key whose value is combined key by key: where each key of the
501    /// value that a source wrote was written, by its name (the origin of the
502    /// write that gives its value). A key of the feature's own default that no
503    /// source wrote has no origin here; a key that is left out of
504    /// [`value`](KeyInEffect::value) (its combined value is `false` in an
505    /// object marked [`Mark::RemoveKeyWhenValueIsFalse`], or `null` where
506    /// [`Mark::SetToDefaultWithNull`] stands) has one. Empty for any other
507    /// key.
508    pub entry_origins: BTreeMap<String, O>,
509    /// For each key of the value that is itself combined key by key, the
510    /// origins of the values below it, in the same form, at every depth: the
511    /// levels below [`entry_origins`](KeyInEffect::entry_origins). A key
512    /// whose value no source writes below it is absent.
513    pub below: BTreeMap<String, EntryOrigins<O>>,
514}
515
516/// Where the keys of a value combined key by key were written, one level of
517/// the origins that [`KeyInEffect`] gives below a key.
518#[derive(Debug, Clone, PartialEq)]
519pub struct EntryOrigins<O> {
520    /// Where each key of the value that a source wrote was written, by its
521    /// name, as [`KeyInEffect::entry_origins`] gives them for a key.
522    pub entry_origins: BTreeMap<String, O>,
523    /// For each key of the value that is itself combined key by key, the
524    /// origins of the values below it.
525    pub below: BTreeMap<String, EntryOrigins<O>>,
526}
527
528impl<O> Default for EntryOrigins<O> {
529    fn default() -> EntryOrigins<O> {
530        EntryOrigins { entry_origins: BTreeMap::new(), below: BTreeMap::new() }
531    }
532}
533
534impl<O> EntryOrigins<O> {
535    /// Whether no origin is recorded at any depth.
536    fn is_empty(&self) -> bool {
537        self.entry_origins.is_empty() && self.below.is_empty()
538    }
539}
540
541impl<O> KeyInEffect<O> {
542    /// Returns where the value at `path` below the key was written (`path`
543    /// holds the names of the keys, outermost first): the origin of the write
544    /// that gives that value, or, for a value that no source wrote at that
545    /// place (a value of the feature's own default) or a place inside a value
546    /// decided whole, the origin of the closest value above it.
547    pub fn origin_at(&self, path: &[&str]) -> &O {
548        let mut origin = &self.origin;
549        let (mut origins, mut below) = (&self.entry_origins, &self.below);
550        for name in path {
551            match origins.get(*name) {
552                Some(at) => origin = at,
553                None => break,
554            }
555            match below.get(*name) {
556                Some(level) => (origins, below) = (&level.entry_origins, &level.below),
557                None => break,
558            }
559        }
560        origin
561    }
562}
563
564/// One value that a source wrote at a place of the settings, as
565/// [`Cascade::writes_at`] lists them: the value at that place, as written, where
566/// it was written, and whether it is the value in effect there.
567#[derive(Debug, Clone, PartialEq)]
568pub struct WriteAt<O> {
569    /// The value the write holds at the place, as written (a path marked
570    /// [`Mark::Path`] as written too).
571    pub value: Value,
572    /// Where the value was written.
573    pub origin: O,
574    /// Whether this write gives the value in effect at the place, by the rule
575    /// of the ranks.
576    pub in_effect: bool,
577}
578
579/// The place decided whole that holds a place of the settings, as
580/// [`Cascade::decided_at`] finds it: how deep it lies, and what gives its
581/// value.
582#[derive(Debug, Clone, PartialEq)]
583pub struct DecidedAt<O> {
584    /// The number of names below the key that lead to the place (`0` for the
585    /// key itself).
586    pub depth: usize,
587    /// The origin of the write that gives the value there, by the rule of the
588    /// ranks; `None` when no source writes there, and the feature's own
589    /// default gives it.
590    pub origin: Option<O>,
591}
592
593/// Returns the values `writes` of one key, in the order written, combined whole
594/// by the rule of the ranks, `reach` deciding between packages: the resulting
595/// value, and those its peers wrote that differ from it.
596fn whole<O: CascadeOrigin>(writes: &[SettingValue<O>], reach: &Reach) -> Option<Written<Value, O>> {
597    Written::decide(writes.iter().map(|write| (&write.value, &write.origin)), reach)
598}
599
600/// Whether the path `pattern` of a mark ([`KeyMark`](crate::core::settings::KeyMark),
601/// `*` naming every key and every item) names the place `path`.
602pub(super) fn names(pattern: &str, path: &[String]) -> bool {
603    let segments: Vec<&str> = pattern.split('.').collect();
604    segments.len() == path.len() && segments.iter().zip(path).all(|(segment, name)| *segment == "*" || segment == name)
605}
606
607/// The values the sources wrote at one place, each with its origin, in the
608/// order written.
609type Writes<'w, O> = Vec<(&'w Value, &'w O)>;
610
611/// A value combined from the sources' values at one place: the value, where it
612/// was written (for a value combined key by key, the origin of the highest
613/// rank among those written there) and the origins below it.
614struct Combined<O> {
615    value: Value,
616    origin: O,
617    below: EntryOrigins<O>,
618}
619
620/// Combines the sources' values of the settings of one feature by the marks
621/// of its declaration, and by the entries in force in it
622/// ([`SettingsDecl::entry_in_force`]).
623struct Combiner<'c> {
624    feature: &'c str,
625    decl: &'c SettingsDecl,
626    reach: &'c Reach,
627}
628
629/// What combining finds beside the combined values: the problems, and the
630/// warnings (a key written under an entry in force that the entry does not
631/// declare).
632struct Found<O> {
633    problems: Vec<Problem<O>>,
634    warnings: Vec<Warning<O>>,
635}
636
637impl<O> Default for Found<O> {
638    fn default() -> Found<O> {
639        Found { problems: Vec::new(), warnings: Vec::new() }
640    }
641}
642
643impl Combiner<'_> {
644    /// Returns the place `path` as messages name it: the feature, then the
645    /// names joined by `.`.
646    fn dotted(&self, path: &[String]) -> String {
647        format!("{}.{}", self.feature, path.join("."))
648    }
649
650    /// Returns the values `writes` at the place `path` combined by the rule of
651    /// the ranks, `default` being the feature's own value there, or `None` when
652    /// no source writes the place. Where `path` carries
653    /// [`Mark::MergeObjectKeyValues`], the values are combined key by key, each
654    /// key by this rule one level down, over `default` (or the default entries
655    /// of the place's node) as the lowest source; elsewhere the value is
656    /// decided whole. Under an entry in force, a key that the entry does not
657    /// declare is left out, with a warning at the origin of each write of it.
658    /// The problems found (a value that is not an object where it is combined
659    /// key by key, peers that disagree) and the warnings are added to `found`.
660    // A value decided whole is never merged below, so that it comes from one
661    // source, which a problem can name.
662    fn combine<O: CascadeOrigin>(
663        &self,
664        path: &mut Vec<String>,
665        writes: Writes<'_, O>,
666        default: Option<&Value>,
667        found: &mut Found<O>,
668    ) -> Option<Combined<O>> {
669        let entry = self.decl.entry_in_force(&path.join("."));
670        if !self.decl.is_marked(path, Mark::MergeObjectKeyValues) {
671            let written = Written::decide(writes, self.reach)?;
672            let what = match path.split_last() {
673                Some((name, parent)) if !parent.is_empty() => {
674                    format!("the entry `{name}` of `{}`", self.dotted(parent))
675                }
676                _ => format!("`{}`", self.dotted(path)),
677            };
678            found.problems.extend(written.disagreement(&what, shown, true));
679            let mut value = written.value;
680            if let (Some(entry), Value::Object(map)) = (entry, &mut value) {
681                map.retain(|name, _| {
682                    let declared = entry.keys().contains(name);
683                    if !declared {
684                        found.warnings.push(self.undeclared(path, name, &written.origin));
685                    }
686                    declared
687                });
688            }
689            self.leave_out(path, &mut value);
690            return Some(Combined { value, origin: written.origin, below: EntryOrigins::default() });
691        }
692        let mut sorted = writes;
693        sorted.sort_by_key(|(_, origin)| origin.rank());
694        let origin = sorted.last()?.1.clone();
695        let defaults = match default {
696            Some(Value::Object(entries)) => Some(entries),
697            _ => self
698                .decl
699                .marks()
700                .iter()
701                .filter(|marks| marks.has(Mark::MergeObjectKeyValues) && names(&marks.path, path))
702                .find_map(|marks| self.decl.default_entries(&marks.path)),
703        };
704        // Each key: its name, the feature's default, and what the sources wrote.
705        let mut entries: Vec<(String, Option<&Value>, Writes<'_, O>)> = defaults
706            .into_iter()
707            .flatten()
708            .map(|(name, value)| (name.clone(), Some(value), Vec::new()))
709            .collect();
710        for (value, origin) in &sorted {
711            let Value::Object(map) = value else {
712                found.problems.push(Problem {
713                    origin: Some((*origin).clone()),
714                    detail: format!(
715                        "the value of `{}` must be a map from each entry's name to the entry",
716                        self.dotted(path)
717                    ),
718                });
719                continue;
720            };
721            for (name, value) in map {
722                if entry.is_some_and(|entry| !entry.keys().contains(name)) {
723                    found.warnings.push(self.undeclared(path, name, origin));
724                    continue;
725                }
726                let at = match entries.iter().position(|(entry, _, _)| entry == name) {
727                    Some(at) => at,
728                    None => {
729                        entries.push((name.clone(), None, Vec::new()));
730                        entries.len() - 1
731                    }
732                };
733                entries[at].2.push((value, *origin));
734            }
735        }
736        let remove_false = self.decl.is_marked(path, Mark::RemoveKeyWhenValueIsFalse);
737        let mut value = Map::new();
738        let mut below = EntryOrigins::default();
739        for (name, default, writes) in entries {
740            path.push(name.clone());
741            let in_force = match self.combine(path, writes, default, found) {
742                Some(combined) => {
743                    below.entry_origins.insert(name.clone(), combined.origin);
744                    if !combined.below.is_empty() {
745                        below.below.insert(name.clone(), combined.below);
746                    }
747                    combined.value
748                }
749                None => {
750                    let mut value = default.cloned().unwrap_or(Value::Null);
751                    self.leave_out(path, &mut value);
752                    value
753                }
754            };
755            let to_default = in_force.is_null() && self.decl.is_marked(path, Mark::SetToDefaultWithNull);
756            path.pop();
757            if !to_default && !(remove_false && in_force == Value::Bool(false)) {
758                value.insert(name, in_force);
759            }
760        }
761        Some(Combined { value: Value::Object(value), origin, below })
762    }
763
764    /// The warning for the key `name`, written at `origin` under the entry in
765    /// force at `path`, which does not declare it.
766    fn undeclared<O: CascadeOrigin>(&self, path: &[String], name: &str, origin: &O) -> Warning<O> {
767        let detail = format!("Unknown setting ‘{name}’ in ‘{}’", self.dotted(path));
768        Warning { kind: WarningKind::UndeclaredKey, problem: Problem { origin: Some(origin.clone()), detail } }
769    }
770
771    /// Leaves out, inside `value` (the value at the place `path`, decided
772    /// whole), each key whose value is `false` in an object marked
773    /// [`Mark::RemoveKeyWhenValueIsFalse`], and each value `null` marked
774    /// [`Mark::SetToDefaultWithNull`].
775    fn leave_out(&self, path: &mut Vec<String>, value: &mut Value) {
776        match value {
777            Value::Object(map) => {
778                let remove_false = self.decl.is_marked(path, Mark::RemoveKeyWhenValueIsFalse);
779                map.retain(|name, item| {
780                    path.push(name.clone());
781                    self.leave_out(path, item);
782                    let to_default = item.is_null() && self.decl.is_marked(path, Mark::SetToDefaultWithNull);
783                    path.pop();
784                    !to_default && !(remove_false && *item == Value::Bool(false))
785                });
786            }
787            Value::Array(items) => {
788                for (at, item) in items.iter_mut().enumerate() {
789                    path.push(at.to_string());
790                    self.leave_out(path, item);
791                    path.pop();
792                }
793            }
794            _ => {}
795        }
796    }
797}
798
799/// Rewrites, in `combined` (the value of the key `key` of the feature that
800/// `decl` declares), every path at a place that `decl` marks as a path to a
801/// file ([`Mark::Path`]), as the origin of the value resolves it
802/// ([`CascadeOrigin::resolve_path`]), and adds to `problems` each path that
803/// the origin refuses, at the origin. A value combined key by key is resolved
804/// by the origin of each of its keys; the values of the feature's own default,
805/// written in no source, are left unchanged.
806// Paths are resolved here, where the origin of each value is known, so that one
807// rule serves every feature and a path written in a file is relative to the
808// file's folder.
809fn resolve_paths<O: CascadeOrigin>(
810    decl: &SettingsDecl,
811    key: &str,
812    combined: &mut KeyInEffect<O>,
813    problems: &mut Vec<Problem<O>>,
814) {
815    for mark in decl.marks().iter().filter(|mark| mark.has(Mark::Path)) {
816        let mut segments = mark.path.split('.');
817        if segments.next() != Some(key) {
818            continue;
819        }
820        let below: Vec<&str> = segments.collect();
821        let mut path = vec![key.to_string()];
822        let origins = (&combined.entry_origins, &combined.below);
823        resolve_in(decl, &mut path, &mut combined.value, &below, &combined.origin, origins, problems);
824    }
825}
826
827/// Resolves, in `value` (the value at the place `path`, written at `origin`),
828/// every text at the place that `segments` designates below it, as
829/// [`resolve_at`] does; where `path` is combined key by key, each key by its
830/// own origin among `origins` (and the origins below it), a key that no source
831/// wrote left unchanged; adds to `problems` each path refused.
832fn resolve_in<O: CascadeOrigin>(
833    decl: &SettingsDecl,
834    path: &mut Vec<String>,
835    value: &mut Value,
836    segments: &[&str],
837    origin: &O,
838    origins: (&BTreeMap<String, O>, &BTreeMap<String, EntryOrigins<O>>),
839    problems: &mut Vec<Problem<O>>,
840) {
841    if !decl.is_marked(path, Mark::MergeObjectKeyValues) {
842        resolve_at(value, segments, origin, problems);
843        return;
844    }
845    let Value::Object(map) = value else { return };
846    let none = EntryOrigins::default();
847    for (name, entry) in map.iter_mut() {
848        let Some(entry_origin) = origins.0.get(name) else { continue };
849        let rest = match segments.split_first() {
850            None => segments,
851            Some((first, rest)) if *first == "*" || first == name => rest,
852            Some(_) => continue,
853        };
854        let below = origins.1.get(name).unwrap_or(&none);
855        path.push(name.clone());
856        resolve_in(decl, path, entry, rest, entry_origin, (&below.entry_origins, &below.below), problems);
857        path.pop();
858    }
859}
860
861/// Resolves, in `value`, every text at the place that `segments` designates
862/// below it ([`texts_at`]), as written at `origin`. A text that the origin
863/// refuses is left as written, and its problem added to `problems`.
864fn resolve_at<O: CascadeOrigin>(value: &mut Value, segments: &[&str], origin: &O, problems: &mut Vec<Problem<O>>) {
865    texts_at(value, segments, &mut |text| match origin.resolve_path(text) {
866        Ok(Some(resolved)) => *text = resolved,
867        Ok(None) => {}
868        Err(detail) => problems.push(Problem { origin: Some(origin.clone()), detail }),
869    });
870}
871
872/// Returns the value at `path` inside `value` (`path` holds the names of the
873/// keys, outermost first, and the positions of the items of a list), if
874/// `value` holds one there.
875fn value_at<'v>(value: &'v Value, path: &[&str]) -> Option<&'v Value> {
876    path.iter().try_fold(value, |value, name| match value {
877        Value::Object(map) => map.get(*name),
878        Value::Array(items) => items.get(name.parse::<usize>().ok()?),
879        _ => None,
880    })
881}
882
883/// Returns the factory among `factories` that holds the feature `feature`, if
884/// one does.
885fn holder<'f>(factories: &[&'f PackageFactory], feature: &str) -> Option<&'f PackageFactory> {
886    factories.iter().copied().find(|factory| factory.features().iter().any(|entry| entry.name == feature))
887}
888
889/// Returns the settings declaration of the feature `feature` among
890/// `factories` (`None` when no factory holds it or it takes no settings),
891/// combined with the declarations of its entries in force
892/// ([`SettingsDecl::with_entries`]): those that the features of `factories`
893/// declare, each feature for which `off` answers `false`.
894///
895/// This is the declaration by which the cascade combines and reads the
896/// feature's settings, `off` answering whether the settings switch a feature
897/// off; a host that describes the settings of the packages in use (a JSON
898/// Schema of a front matter) gives `off` that answers `false` for every
899/// feature.
900pub fn declaration_in_force<'f>(
901    factories: &[&'f PackageFactory],
902    feature: &str,
903    off: impl Fn(&str) -> bool,
904) -> Option<Cow<'f, SettingsDecl>> {
905    entries_in_force(factories, feature, off, &mut Vec::new())
906}
907
908/// The declaration of [`declaration_in_force`], adding to `problems` the
909/// faults of the declarations of entries: an entry that two features declare
910/// (the problem names the entry by its label, [`EntryDecl::label`], and both
911/// features by their packages), and an entry at a place that the owner does
912/// not open ([`SettingsDecl::open_entries`]).
913fn entries_in_force<'f>(
914    factories: &[&'f PackageFactory],
915    feature: &str,
916    off: impl Fn(&str) -> bool,
917    problems: &mut Vec<String>,
918) -> Option<Cow<'f, SettingsDecl>> {
919    let owner = holder(factories, feature)?.settings(feature)?;
920    let mut declared: Vec<(&Name, &str, &EntryDecl)> = Vec::new();
921    for factory in factories {
922        for entry in factory.features() {
923            let Some(decl) = &entry.settings else { continue };
924            if off(&entry.name) {
925                continue;
926            }
927            for declaration in decl.entries().iter().filter(|declaration| declaration.owner().as_str() == feature) {
928                let path = declaration.path();
929                if !owner.opens(path) {
930                    problems.push(format!(
931                        "Misconfigured feature ‘{}’: the feature ‘{feature}’ does not allow other features to \
932                         declare an entry at ‘{feature}.{path}’",
933                        entry.name
934                    ));
935                    continue;
936                }
937                let label = declaration.label();
938                match declared.iter().find(|(_, _, other)| other.path() == path) {
939                    Some((package, other, _)) if *package == factory.name() => problems.push(format!(
940                        "Duplicate {label} (features ‘{other}’ and ‘{}’ of the package ‘{package}’)",
941                        entry.name
942                    )),
943                    Some((package, _, _)) => problems.push(format!(
944                        "Duplicate {label} (packages ‘{package}’ and ‘{}’)",
945                        factory.name()
946                    )),
947                    None => declared.push((factory.name(), entry.name.as_str(), declaration)),
948                }
949            }
950        }
951    }
952    if declared.is_empty() {
953        return Some(Cow::Borrowed(owner));
954    }
955    Some(Cow::Owned(owner.with_entries(declared.into_iter().map(|(_, _, declaration)| declaration))))
956}
957
958/// Returns a value as a message shows it: its one-line JSON form, between
959/// backticks.
960fn shown(value: &Value) -> String {
961    format!("`{value}`")
962}
963
964impl<O: CascadeOrigin> Cascade<O> {
965    /// Returns an empty cascade in which no package reaches another, so that
966    /// every two packages are peers.
967    pub fn new() -> Cascade<O> {
968        Cascade::default()
969    }
970
971    /// Returns an empty cascade in which the packages reach one another as
972    /// `reach` says: a package wins over the packages it reaches, for every
973    /// setting both write. See the [module
974    /// documentation](self#the-rule-between-packages).
975    pub fn with_reach(reach: Reach) -> Cascade<O> {
976        Cascade { reach, ..Cascade::default() }
977    }
978
979    /// Records `value` for the key `key` of the feature `feature`, written at
980    /// `origin`. Every value recorded is kept; the rule of the ranks decides
981    /// which one results when the settings are read, and
982    /// [`read`](Cascade::read) reports peers that disagree. It does not switch
983    /// the feature on.
984    pub fn set(&mut self, feature: &str, key: &str, value: Value, origin: O) {
985        let values = self.features.entry(feature.to_string()).or_default();
986        values.written.push(origin.clone());
987        values.keys.entry(key.to_string()).or_default().push(SettingValue { value, origin });
988    }
989
990    /// Records that `origin` switches the feature `feature` off; the keys its
991    /// source sets for the feature are recorded apart, with [`Cascade::set`],
992    /// and are not read while the feature is off. The rule of the ranks decides
993    /// between the sources that switch the feature on or off.
994    pub fn switch_off(&mut self, feature: &str, origin: O) {
995        self.switch(feature, true, origin);
996    }
997
998    /// Records that `origin` switches the feature `feature` on; the keys its
999    /// source sets for the feature are recorded apart, with [`Cascade::set`].
1000    /// The rule of the ranks decides between the sources that switch the
1001    /// feature on or off.
1002    pub fn switch_on(&mut self, feature: &str, origin: O) {
1003        self.switch(feature, false, origin);
1004    }
1005
1006    /// Records that `origin` switches the feature `feature` off (`off`) or on.
1007    fn switch(&mut self, feature: &str, off: bool, origin: O) {
1008        let values = self.features.entry(feature.to_string()).or_default();
1009        values.written.push(origin.clone());
1010        values.off.push((off, origin));
1011    }
1012
1013    /// Records `value` for the parsing setting `key` ([`FlmParsing`]), written
1014    /// at `origin`; the parsing settings are combined key by key by the rule of
1015    /// the ranks ([`parsing`](Cascade::parsing)).
1016    pub fn set_parsing(&mut self, key: &str, value: Value, origin: O) {
1017        self.parsing.entry(key.to_string()).or_default().push((value, origin));
1018    }
1019
1020    /// Records `fields`, the fields that a package writes for the workflow
1021    /// `workflow`: each a field's name, its value and its origin. With no
1022    /// field, it records the workflow alone (a package that gives the workflow
1023    /// settings only). The rule of the ranks decides between the packages that
1024    /// write one field, and [`read`](Cascade::read) reports peers that
1025    /// disagree.
1026    pub fn add_workflow_fields(&mut self, workflow: &str, fields: impl IntoIterator<Item = (String, Value, O)>) {
1027        let written = self.workflow_fields.entry(workflow.to_string()).or_default();
1028        for (field, value, origin) in fields {
1029            written.entry(field).or_default().push((value, origin));
1030        }
1031    }
1032
1033    /// Returns the resulting value of the key `key` of the feature `feature`,
1034    /// combined whole, with its origin, if a source wrote one. When peers
1035    /// disagree, it is the first written. A value marked as combined key by key
1036    /// is combined so only when the settings are [read](Cascade::read), which
1037    /// has the feature's declaration.
1038    pub fn value(&self, feature: &str, key: &str) -> Option<SettingValue<O>> {
1039        let written = whole(self.features.get(feature)?.keys.get(key)?, &self.reach)?;
1040        Some(SettingValue { value: written.value, origin: written.origin })
1041    }
1042
1043    /// Returns where the feature `feature` was switched off, if the source that
1044    /// decides its switch switches it off.
1045    pub fn switched_off(&self, feature: &str) -> Option<O> {
1046        let off = self.decide(&self.features.get(feature)?.off)?;
1047        if off.value { Some(off.origin) } else { None }
1048    }
1049
1050    /// Returns the resulting value of the field `field` of the workflow
1051    /// `workflow`, with its origin, if a package wrote one. When peers
1052    /// disagree, it is the first written.
1053    pub fn workflow_field(&self, workflow: &str, field: &str) -> Option<SettingValue<O>> {
1054        let writes = self.workflow_fields.get(workflow)?.get(field)?;
1055        let written = self.decide(writes)?;
1056        Some(SettingValue { value: written.value, origin: written.origin })
1057    }
1058
1059    /// Returns every workflow that a package writes, with fields or with
1060    /// settings only, by its name: its resulting fields, each with its name,
1061    /// value and origin (none for a workflow written with settings only). The
1062    /// host gives these to the library, once per workflow ([`workflow_def`],
1063    /// then
1064    /// [`RegistryBuilder::workflow_fields`](crate::core::registry::RegistryBuilder::workflow_fields)),
1065    /// so they are the fields the workflow runs with.
1066    pub fn workflows(&self) -> BTreeMap<String, Vec<(String, SettingValue<O>)>> {
1067        self.workflow_fields
1068            .keys()
1069            .map(|workflow| {
1070                let fields = self.workflow_fields[workflow]
1071                    .keys()
1072                    .filter_map(|field| Some((field.clone(), self.workflow_field(workflow, field)?)))
1073                    .collect();
1074                (workflow.clone(), fields)
1075            })
1076            .collect()
1077    }
1078
1079    /// The declaration of the feature `feature` among `factories` by which its
1080    /// settings are combined and read: with its entries in force, those that
1081    /// the features of `factories` that are not switched off declare
1082    /// ([`declaration_in_force`]). The faults of the declarations of entries
1083    /// are added to `problems`.
1084    fn declaration<'f>(
1085        &self,
1086        factories: &[&'f PackageFactory],
1087        feature: &str,
1088        problems: &mut Vec<String>,
1089    ) -> Option<Cow<'f, SettingsDecl>> {
1090        entries_in_force(factories, feature, |name| self.switched_off(name).is_some(), problems)
1091    }
1092
1093    /// Returns the resulting value among `writes`, by the rule of the ranks and
1094    /// the packages' reach.
1095    fn decide<T: PartialEq + Clone>(&self, writes: &[(T, O)]) -> Option<Written<T, O>> {
1096        Written::decide(writes.iter().map(|(value, origin)| (value, origin)), &self.reach)
1097    }
1098
1099    /// Returns the resulting parsing settings: each key as written by the
1100    /// source of the highest rank that writes it, the others at their
1101    /// defaults.
1102    ///
1103    /// # Errors
1104    ///
1105    /// A [`Problem`] for each key to which peers give different values, and one
1106    /// when the values cannot be read as the parsing settings' types.
1107    pub fn parsing(&self) -> Result<FlmParsing, Vec<Problem<O>>> {
1108        let mut problems = Vec::new();
1109        let mut data = Map::new();
1110        for (key, writes) in &self.parsing {
1111            let Some(written) = self.decide(writes) else { continue };
1112            problems.extend(written.disagreement(&format!("`parsing.{key}`"), shown, true));
1113            data.insert(key.clone(), written.value.clone());
1114        }
1115        if !problems.is_empty() {
1116            return Err(problems);
1117        }
1118        serde_json::from_value(Value::Object(data)).map_err(|error| {
1119            vec![Problem { origin: None, detail: format!("each parsing setting must hold a value of its type: {error}") }]
1120        })
1121    }
1122
1123    /// Returns the resulting value of each parsing setting that a source wrote,
1124    /// by its key, with its origin: the value that
1125    /// [`parsing`](Cascade::parsing) reads for the key. When peers disagree, it
1126    /// is the first written. A key that no source wrote is absent.
1127    pub fn parsing_in_effect(&self) -> BTreeMap<String, SettingValue<O>> {
1128        self.parsing
1129            .iter()
1130            .filter_map(|(key, writes)| {
1131                let written = self.decide(writes)?;
1132                Some((key.clone(), SettingValue { value: written.value, origin: written.origin }))
1133            })
1134            .collect()
1135    }
1136
1137    /// Returns the settings in effect for the package factories `factories`,
1138    /// by the feature's name: for each feature that a source wrote and that one
1139    /// of the factories holds, whether it is switched off and where, and the
1140    /// value in effect of each key written, combined from every source by the
1141    /// rule of the ranks, with where it was written ([`FeatureInEffect`]). A
1142    /// value marked as combined key by key is combined so, each key with its
1143    /// origin, at every depth (see the [module
1144    /// documentation](self#values-combined-key-by-key)), and relative paths are resolved (see the [module
1145    /// documentation](self#reading-the-combined-settings)). This is the data
1146    /// that [`read`](Cascade::read) reads through the features' settings
1147    /// declarations, combined by the same code.
1148    ///
1149    /// A host uses it to show each setting's value and where it was written.
1150    /// Nothing is checked: a key that the feature does not declare is listed
1151    /// like the others, and when peers disagree the value is the first written,
1152    /// as for [`value`](Cascade::value); [`read`](Cascade::read) reports these
1153    /// problems. A feature that no factory holds, and the keys of a feature
1154    /// that takes no settings, are left out.
1155    pub fn in_effect(&self, factories: &[&PackageFactory]) -> BTreeMap<String, FeatureInEffect<O>> {
1156        // The problems and the warnings are those `read` reports; they are not returned here.
1157        let mut found = Found::default();
1158        self.features
1159            .iter()
1160            .filter_map(|(feature, values)| {
1161                holder(factories, feature)?;
1162                let decl = self.declaration(factories, feature, &mut Vec::new());
1163                Some((feature.clone(), self.combine(feature, values, decl.as_deref(), &mut found)))
1164            })
1165            .collect()
1166    }
1167
1168    /// Returns every value that a source wrote at the place `path` below the
1169    /// key `key` of the feature `feature` (`path` holds the names of the keys,
1170    /// outermost first; empty for the key itself), lowest rank first and, within
1171    /// a rank, in the order written: each write of the key that holds a value
1172    /// at that place, with that value as written, its origin, and whether it
1173    /// gives the value in effect there.
1174    ///
1175    /// The value in effect is decided as [`in_effect`](Cascade::in_effect)
1176    /// decides it, by the marks of `decl`, the declaration in force of the
1177    /// feature ([`declaration_in_force`], whose `off` answers whether this
1178    /// cascade switches a feature off; `None` for a feature that takes no
1179    /// settings or that no factory holds): down the path, through each place
1180    /// combined key by key, to the first place decided whole, where the write
1181    /// that the rule of the ranks chooses gives the value in effect when it
1182    /// holds a value at `path`. No write is in effect at a place combined key
1183    /// by key (its value is made of several writes), at a place that no source
1184    /// writes (where the feature's own default is in effect), nor in a feature
1185    /// switched off, without settings, or that no factory holds. When peers
1186    /// disagree, the first written is in effect, as for
1187    /// [`value`](Cascade::value). A host that lists the writes at several
1188    /// places of one feature computes the declaration once.
1189    pub fn writes_at(
1190        &self,
1191        decl: Option<&SettingsDecl>,
1192        feature: &str,
1193        key: &str,
1194        path: &[&str],
1195    ) -> Vec<WriteAt<O>> {
1196        let Some(writes) = self.features.get(feature).and_then(|values| values.keys.get(key)) else {
1197            return Vec::new();
1198        };
1199        let in_effect = match decl {
1200            Some(decl) if self.switched_off(feature).is_none() => self.write_in_effect(decl, key, path, writes),
1201            _ => None,
1202        };
1203        let mut found: Vec<(usize, Value)> = writes
1204            .iter()
1205            .enumerate()
1206            .filter_map(|(at, write)| Some((at, value_at(&write.value, path)?.clone())))
1207            .collect();
1208        found.sort_by_key(|(at, _)| writes[*at].origin.rank());
1209        found
1210            .into_iter()
1211            .map(|(at, value)| WriteAt { value, origin: writes[at].origin.clone(), in_effect: in_effect == Some(at) })
1212            .collect()
1213    }
1214
1215    /// Returns the place decided whole that holds the place `path` below the
1216    /// key `key` of the feature `feature` (as for
1217    /// [`writes_at`](Cascade::writes_at), whose `decl` it takes too): the
1218    /// first place, down the path through each place combined key by key, that
1219    /// is not combined so, with the origin of the write that gives its value
1220    /// by the rule of the ranks, or no origin when no source writes there (the
1221    /// feature's own default then gives it, an entry of its default of the
1222    /// value combined key by key above it when the place lies below the key).
1223    /// The value at `path` lies at the place returned or inside it. There is
1224    /// none when `path` is itself combined key by key or lies in such a place
1225    /// along its names, and in a feature switched off, without settings, or
1226    /// that no factory holds. [`writes_at`](Cascade::writes_at) lists the
1227    /// writes there.
1228    pub fn decided_at(
1229        &self,
1230        decl: Option<&SettingsDecl>,
1231        feature: &str,
1232        key: &str,
1233        path: &[&str],
1234    ) -> Option<DecidedAt<O>> {
1235        let decl = decl.filter(|_| self.switched_off(feature).is_none())?;
1236        let writes = self.features.get(feature).and_then(|values| values.keys.get(key));
1237        let writes = writes.map(Vec::as_slice).unwrap_or_default();
1238        let (depth, decided) = self.decide_whole(decl, key, path, writes)?;
1239        Some(DecidedAt { depth, origin: decided.map(|(at, _)| writes[at].origin.clone()) })
1240    }
1241
1242    /// Returns the position among `writes` (the writes of the key `key` of the
1243    /// feature that `decl` declares) of the write that gives the value in
1244    /// effect at `path` below the key, if one does (see
1245    /// [`writes_at`](Cascade::writes_at)).
1246    fn write_in_effect(
1247        &self,
1248        decl: &SettingsDecl,
1249        key: &str,
1250        path: &[&str],
1251        writes: &[SettingValue<O>],
1252    ) -> Option<usize> {
1253        let (depth, (at, value)) = match self.decide_whole(decl, key, path, writes)? {
1254            (depth, Some(decided)) => (depth, decided),
1255            (_, None) => return None,
1256        };
1257        value_at(value, &path[depth..]).map(|_| at)
1258    }
1259
1260    /// Returns the place decided whole that holds `path` below the key `key`
1261    /// ([`decided_at`](Cascade::decided_at)), `writes` being the key's writes
1262    /// and `decl` the declaration in force: the number of names of `path` that
1263    /// lead to it, and the position among `writes` of the write that the rule
1264    /// of the ranks chooses there with its value at that place, if a write
1265    /// holds a value there.
1266    fn decide_whole<'w>(
1267        &self,
1268        decl: &SettingsDecl,
1269        key: &str,
1270        path: &[&str],
1271        writes: &'w [SettingValue<O>],
1272    ) -> Option<(usize, Option<(usize, &'w Value)>)> {
1273        let mut place = vec![key.to_string()];
1274        let mut level: Vec<(usize, &Value)> = writes.iter().enumerate().map(|(at, write)| (at, &write.value)).collect();
1275        while decl.is_marked(&place, Mark::MergeObjectKeyValues) {
1276            let name = path.get(place.len() - 1)?;
1277            level = level.into_iter().filter_map(|(at, value)| Some((at, value.as_object()?.get(*name)?))).collect();
1278            place.push(name.to_string());
1279        }
1280        let candidates: Vec<(&Value, &O)> = level.iter().map(|(at, value)| (*value, &writes[*at].origin)).collect();
1281        let decided = decide_at(&candidates, &self.reach).map(|(first, _)| level[first]);
1282        Some((place.len() - 1, decided))
1283    }
1284
1285    /// Returns the settings in effect of the feature `feature`, from `values`,
1286    /// what the sources wrote for it, read by `decl`, its settings declaration
1287    /// (`None` for a feature that takes no settings, whose keys are then left
1288    /// out): whether it is switched off and where, and, when it is not, each
1289    /// key's value combined by the rule of the ranks, its paths resolved.
1290    /// Adds to `found` the problems found on the way (peers that disagree on
1291    /// whether the feature is off, on a key or on a value below one; a value
1292    /// that is not an object where it is combined key by key; a key that a
1293    /// workflow's settings set and that is not set per render request), and
1294    /// the warnings (a key written under an entry in force that the entry does
1295    /// not declare, left out).
1296    fn combine(
1297        &self,
1298        feature: &str,
1299        values: &FeatureValues<O>,
1300        decl: Option<&SettingsDecl>,
1301        found: &mut Found<O>,
1302    ) -> FeatureInEffect<O> {
1303        let mut in_effect = FeatureInEffect { switched_off: None, keys: BTreeMap::new() };
1304        if let Some(off) = self.decide(&values.off) {
1305            let state = |off: &bool| String::from(if *off { "`false`" } else { "settings" });
1306            found.problems.extend(off.disagreement(&format!("the feature `{feature}`"), state, true));
1307            // A feature switched off is absent: none of its keys is in effect, whatever
1308            // source wrote them.
1309            if off.value {
1310                in_effect.switched_off = Some(off.origin);
1311                return in_effect;
1312            }
1313        }
1314        let Some(decl) = decl else { return in_effect };
1315        for (key, writes) in &values.keys {
1316            for write in writes {
1317                if let (Some(workflow), Some(declared)) = (write.origin.workflow(), decl.key(key)) {
1318                    if declared.bind != Bind::Render {
1319                        found.problems.push(Problem {
1320                            origin: Some(write.origin.clone()),
1321                            detail: format!("the settings of the workflow `{workflow}` must not set `{feature}.{key}`: a workflow's settings may set only keys that are set per render request, and `{feature}.{key}` is not one"),
1322                        });
1323                    }
1324                }
1325            }
1326            let combiner = Combiner { feature, decl, reach: &self.reach };
1327            let mut path = vec![key.clone()];
1328            let written = writes.iter().map(|write| (&write.value, &write.origin)).collect();
1329            let Some(combined) = combiner.combine(&mut path, written, None, found) else { continue };
1330            // A setting whose value `null` gives it its default is left out, so that its
1331            // reader applies the default.
1332            if combined.value.is_null() && decl.is_marked(&path, Mark::SetToDefaultWithNull) {
1333                continue;
1334            }
1335            let mut combined = KeyInEffect {
1336                value: combined.value,
1337                origin: combined.origin,
1338                entry_origins: combined.below.entry_origins,
1339                below: combined.below.below,
1340            };
1341            resolve_paths(decl, key, &mut combined, &mut found.problems);
1342            in_effect.keys.insert(key.clone(), combined);
1343        }
1344        in_effect
1345    }
1346
1347    /// Reads the combined settings through the settings declarations of the
1348    /// package factories `factories`: every feature of a factory that declares
1349    /// settings and is not switched off is read by its declaration, from the
1350    /// data written for it, or from the empty map when nothing is written under
1351    /// it (see [`SettingsDecl::read`] for the configuration read from the empty
1352    /// map). Path values are resolved first (see the [module
1353    /// documentation](self#reading-the-combined-settings)). The data read for
1354    /// a feature that a source wrote is what [`in_effect`](Cascade::in_effect)
1355    /// returns for it.
1356    ///
1357    /// Every factory gets an entry in [`ReadSettings::packages`], which holds
1358    /// the settings read of each of its features that declares settings,
1359    /// written or not; a feature switched off is recorded as such in its
1360    /// package's settings. What a source writes for a feature that no factory
1361    /// holds is read by nothing: each source that writes such a feature gives
1362    /// one warning ([`WarningKind::UnknownFeature`]), at the first origin
1363    /// recorded for it, and nothing else (see the [module
1364    /// documentation](self#a-feature-that-no-package-in-use-has)). A key
1365    /// written under an entry in force that the entry does not declare is left
1366    /// out of the combined settings, with one warning
1367    /// ([`WarningKind::UndeclaredKey`]) at the origin of each write of it (see
1368    /// the [module documentation](self#entries-that-another-feature-declares)).
1369    /// The warnings are in [`ReadSettings::warnings`], or in
1370    /// [`ReadFailure::warnings`] when the reading finds problems.
1371    ///
1372    /// # Errors
1373    ///
1374    /// A [`ReadFailure`] with every problem found, each at the origin of the
1375    /// value at fault, and the warnings found beside them. The problems: settings
1376    /// written for a feature that takes no settings; peers that disagree on
1377    /// a key, on a value below one, or on whether a feature is off; a value
1378    /// that is not an object where the feature's declaration combines it key
1379    /// by key ([`Mark::MergeObjectKeyValues`]); a key the feature does not
1380    /// declare, or a value its declaration cannot read; a key that a workflow's
1381    /// settings set and that is not set per render request; peers that disagree
1382    /// on a field of a workflow; an entry that two features in use declare, and
1383    /// a declaration of an entry at a place that the owner does not open
1384    /// ([`SettingsDecl::open_entries`]); a path in a value marked
1385    /// [`Mark::Path`] that its origin refuses
1386    /// ([`CascadeOrigin::resolve_path`]). A problem found in reading a
1387    /// feature nothing is written for (a configuration reader that refuses the
1388    /// empty map), and a fault of the declarations of entries, have no origin.
1389    pub fn read(&self, factories: &[&PackageFactory]) -> Result<ReadSettings<O>, ReadFailure<O>> {
1390        let mut read = ReadSettings::default();
1391        for factory in factories {
1392            read.packages.insert(factory.name().clone(), PackageSettings::new());
1393        }
1394        let mut problems = Vec::new();
1395        for (workflow, field, writes) in self
1396            .workflow_fields
1397            .iter()
1398            .flat_map(|(workflow, fields)| fields.iter().map(move |(field, writes)| (workflow, field, writes)))
1399        {
1400            let Some(written) = self.decide(writes) else { continue };
1401            let what = format!("the field `{field}` of the workflow `{workflow}`");
1402            problems.extend(written.disagreement(&what, shown, false));
1403        }
1404        // The features written, combined: each one not switched off whose declaration
1405        // reads it, with its settings in effect and the first origin written for it.
1406        let mut written_features: BTreeMap<&str, (FeatureInEffect<O>, Option<O>)> = BTreeMap::new();
1407        for (feature, values) in &self.features {
1408            let first_origin = values
1409                .keys
1410                .values()
1411                .find_map(|writes| writes.first())
1412                .map(|write| write.origin.clone())
1413                .or(values.off.first().map(|(_, origin)| origin.clone()));
1414            let Some(factory) = holder(factories, feature) else {
1415                // Accepted and read by nothing, with one warning for each source that writes
1416                // it, at the first origin of that source, since the name may be misspelled.
1417                let mut firsts: Vec<&O> = Vec::new();
1418                for origin in &values.written {
1419                    if !firsts.iter().any(|first| same_source(*first, origin)) {
1420                        firsts.push(origin);
1421                    }
1422                }
1423                read.warnings.extend(firsts.into_iter().map(|origin| Warning {
1424                    kind: WarningKind::UnknownFeature,
1425                    problem: Problem {
1426                        origin: Some(origin.clone()),
1427                        detail: format!("Unknown feature ‘{feature}’: no package in use has this feature"),
1428                    },
1429                }));
1430                continue;
1431            };
1432            let decl = self.declaration(factories, feature, &mut Vec::new()).filter(|decl| decl.takes_settings());
1433            let mut found = Found::default();
1434            let in_effect = self.combine(feature, values, decl.as_deref(), &mut found);
1435            problems.extend(found.problems);
1436            read.warnings.extend(found.warnings);
1437            if in_effect.switched_off.is_some() {
1438                read.packages.entry(factory.name().clone()).or_default().switch_off(feature.as_str());
1439            } else if decl.is_some() {
1440                written_features.insert(feature.as_str(), (in_effect, first_origin));
1441            } else if !values.keys.is_empty() {
1442                problems.push(Problem {
1443                    origin: first_origin,
1444                    detail: format!("the feature `{feature}` takes no settings, so nothing may be written under it"),
1445                });
1446            }
1447        }
1448        // Every feature in use that declares settings and is not switched off is read: from
1449        // its settings in effect, or from the empty map when nothing is written under it.
1450        for factory in factories {
1451            let package = read.packages.entry(factory.name().clone()).or_default();
1452            for entry in factory.features() {
1453                if entry.settings.is_none() || package.is_off(&entry.name) {
1454                    continue;
1455                }
1456                let mut declared = Vec::new();
1457                let Some(decl) = self.declaration(factories, &entry.name, &mut declared) else { continue };
1458                problems.extend(declared.into_iter().map(|detail| Problem { origin: None, detail }));
1459                let (in_effect, first_origin) = match written_features.get(entry.name.as_str()) {
1460                    Some((in_effect, first_origin)) => (Some(in_effect), first_origin.as_ref()),
1461                    None => (None, None),
1462                };
1463                let data: Map<String, Value> = in_effect
1464                    .iter()
1465                    .flat_map(|in_effect| &in_effect.keys)
1466                    .map(|(key, combined)| (key.clone(), combined.value.clone()))
1467                    .collect();
1468                match decl.read(&data) {
1469                    Ok(settings) => {
1470                        read.document.merge_from(settings.document_options());
1471                        read.render.merge_from(settings.render_options());
1472                        package.insert(settings);
1473                    }
1474                    Err(errors) => problems.extend(errors.into_iter().map(|error| {
1475                        // At the key or the entry at fault when it is written, else at the
1476                        // first value written for the feature; nowhere when nothing is.
1477                        let mut path = error.path.split('.').skip(1);
1478                        let at = path.next().and_then(|key| in_effect?.keys.get(key)).map(|combined| {
1479                            let below: Vec<&str> = path.collect();
1480                            combined.origin_at(&below).clone()
1481                        });
1482                        Problem { origin: at.or_else(|| first_origin.cloned()), detail: error.detail }
1483                    })),
1484                }
1485            }
1486        }
1487        if problems.is_empty() { Ok(read) } else { Err(ReadFailure { errors: problems, warnings: read.warnings }) }
1488    }
1489}
1490
1491/// Returns the fields `fields` of the workflow `name` (each a field's name and
1492/// its value as a package writes it) as the library holds them: a
1493/// [`WorkflowDef`] with the fields given and the others unset. A field that the
1494/// library does not declare is ignored.
1495///
1496/// The host calls it with the resulting fields among every package that writes
1497/// the workflow ([`Cascade::workflows`]), and registers the result through
1498/// [`RegistryBuilder::workflow_fields`](crate::core::registry::RegistryBuilder::workflow_fields).
1499pub fn workflow_def<'v>(name: &str, fields: impl IntoIterator<Item = (&'v str, &'v Value)>) -> WorkflowDef {
1500    let mut def = WorkflowDef::new(name);
1501    let names = |value: &Value| -> Vec<String> {
1502        value.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()
1503    };
1504    for (field, value) in fields {
1505        match field {
1506            "extends" => def.extends = value.as_str().map(Into::into),
1507            "outputs" => def.outputs = names(value).into_iter().map(Into::into).collect(),
1508            "demands" => def.demands = names(value).into_iter().map(Into::into).collect(),
1509            "prefer" => def.prefer = names(value).into_iter().map(Into::into).collect(),
1510            // Through the builder, so that the cargo feature `docs` decides for
1511            // a text read from data as for one given in Rust.
1512            "docs" => def = def.docs(value.as_str().unwrap_or_default()),
1513            _ => {}
1514        }
1515    }
1516    def
1517}