Skip to main content

flm_core/core/
settings.rs

1//! Settings are a feature's configuration and option values written as data, one
2//! map per feature from key to value, which this module reads into the feature's
3//! own Rust types; a settings key is one field of those types.
4//!
5//! A feature's configuration is the plain Rust value the feature is constructed
6//! from; it is fixed when the registry is built and cannot vary per document or
7//! per render ([settings, options and
8//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
9//! An option type is a plain Rust struct a feature declares once, whose values
10//! are set on a document or on a render request ([`crate::model::options`]).
11//!
12//! A program that does not construct these Rust values itself, such as a
13//! command line or a program that reads a document's front matter, gives them as
14//! data instead. This module reads that data. It adds no second definition of
15//! any setting: the keys, their defaults and their documentation are those of
16//! the Rust types, and the data is read into those types.
17//!
18//! # The declaration
19//!
20//! A feature that takes settings gives one [`SettingsDecl`]: the feature's name,
21//! the Rust types its settings are read into, each with its
22//! [binding](crate::model::options::Bind) (where a value may be set: fixed with
23//! the registry, on the document, on the render request, or on either), and marks
24//! on some keys or on values below them ([`Mark`], [`KeyMark`]). Every field of
25//! those types is one settings key of the feature: the keys of the `html`
26//! feature, for example, are the fields of its render options, `title`, `lang`,
27//! `heading_tags` and so on. The declaration
28//! lists the keys ([`SettingsDecl::keys`]), reads a map of them
29//! ([`SettingsDecl::read`]) and describes them as a JSON Schema
30//! ([`SettingsDecl::json_schema`]), with the descriptions taken from the Rust
31//! documentation of the fields.
32//!
33//! A feature gives its declaration through
34//! [`FlmFeature::settings`](crate::core::registry::FlmFeature::settings), and
35//! nothing else states it again: the registry build declares the feature's
36//! option types from it, each with its binding and its documentation, and a
37//! package factory lists it beside the feature's name
38//! ([`PackageFactory`](crate::core::registry::PackageFactory)).
39//!
40//! # Reading
41//!
42//! Data is a [`serde_json::Value`], the only data model this module reads; the
43//! host is responsible for reading another notation (for example YAML) into it.
44//! The types the data is read into implement [`serde::Deserialize`] and are
45//! public, so that another program reads the same keys. Reading gives a
46//! [`FeatureSettings`]: the feature's configuration (its default when no key of
47//! it is written), and the option values of every option type at least one of
48//! whose keys is written.
49//!
50//! A key the feature does not declare, and a value that does not have the shape
51//! its key requires, are each reported as a [`SettingsError`] that identifies the
52//! key by its path from the feature's name (`html.heading_tags.section`).
53//! [`SettingsDecl::read`] receives only the data, not the file or the line in
54//! which a value was written: a host, which records where each value was
55//! written, adds that place when it reports the error.
56//!
57//! The key [`ENABLED_KEY`] (`enabled`) is reserved: a source of settings
58//! writes it beside a feature's settings to switch the feature on or off, and
59//! a declaration refuses a key of that name, as it refuses a key declared
60//! twice.
61//!
62//! # Collections of named things
63//!
64//! A collection of named things, such as the xnote kinds or the float types, is
65//! written in data as a map from a name to an entry, in the order written;
66//! [`named`] provides the function that reads such a field
67//! ([`named::deserialize`]). Its feature marks
68//! the key as combined key by key ([`SettingsDecl::merge_entries`]), giving
69//! its default entries as data ([`SettingsDecl::default_entries`]), and as one
70//! in which an entry written `false` is removed
71//! ([`SettingsDecl::remove_false`]). A host that combines several sources of
72//! settings combines such a key one entry at a time, with the default entries
73//! as the lowest source, instead of letting one source's value replace
74//! another's whole. This module reads one map per feature, already combined.
75//!
76//! # Marks
77//!
78//! A mark ([`Mark`]) says how sources of settings combine a value, or what the
79//! value means. It is written on the node of the JSON Schema that it concerns,
80//! as the list of the mark names under [`MARKS_KEYWORD`] (`x-flm-marks`):
81//! `{"type": "object", "x-flm-marks": ["merge-object-key-values",
82//! "remove-key-when-value-is-false"]}`. The declaration keeps each mark with
83//! the path of its node ([`KeyMark`]). A declaration written in Rust sets marks
84//! by path, with one method per mark; a part declared from data writes them on
85//! the nodes of its schema. Either way, the schema that
86//! [`SettingsDecl::json_schema`] prints carries every mark on its node.
87//!
88//! # Settings declared from data
89//!
90//! A feature whose settings have no Rust types, such as a feature written in a
91//! script, declares them from data instead: its configuration with
92//! [`SettingsDecl::config_data`] and each option type with
93//! [`SettingsDecl::options_data`], each from a JSON Schema of an object, with
94//! the marks written on the nodes of that schema. Such a
95//! part of the declaration is a *data part*; it lives in one declaration beside
96//! the parts declared with Rust types, and everything above holds for it alike:
97//! its keys are the `properties` of its schema, it is read, declared to the
98//! registry and described as the others are.
99//!
100//! - **Its key.** The configuration is the option type named by the feature's
101//!   name, and an option type the one named by the name the feature gives
102//!   ([`OptionKey::Data`]). A stage reads
103//!   it by that name
104//!   ([`StageCx::option_named`](crate::core::run::StageCx::option_named), after
105//!   [`Needs::option_named`](crate::core::stage::Needs::option_named)), and a
106//!   package reads a configuration declared from data as a
107//!   [`DataValue`] ([`PackageSettings::config`]).
108//! - **Reading.** A key outside the schema's `properties` is an unknown key, as
109//!   for a Rust type that refuses unknown fields. The values are kept as written,
110//!   as a [`DataValue`]: they are not checked against the types the schema
111//!   states, which is the feature's own task. The configuration read when none
112//!   of its keys is written is the empty map.
113//! - **A reader.** A feature that reads its configuration when the settings are
114//!   read declares it with [`SettingsDecl::config_data_read`], giving the
115//!   function that reads it: the configuration written goes in, and the value
116//!   kept as the [`DataValue`] comes out, or a [`ReadError`] naming the value at
117//!   fault, which is reported as the conversion errors of
118//!   [`SettingsDecl::config_from`] are, at that value's path. This is the twin of
119//!   reading a Rust type `D` and converting it with `C::try_from`.
120//! - **The marks.** The declaration reads the marks from the nodes of the
121//!   schema, each at its node's path ([`KeyMark`]): a property `K` of an
122//!   object adds the segment `K`, `additionalProperties` and `items` add the
123//!   segment `*`, and a `$ref` into the schema's own `$defs` is followed. The
124//!   default entries of an object combined key by key are the `default` of its
125//!   node, the empty map when it has none.
126//! - **The schema.** [`SettingsDecl::json_schema`] takes the keys' schemas from
127//!   the schema given, with the binding added as for a Rust type and the marks
128//!   written on their nodes; the schema's own `$defs` join those of the result.
129//! - **Mistakes.** The data constructors return a [`SettingsError`] of the kind
130//!   [`SettingsErrorKind::InvalidDeclaration`] where the constructors taking a
131//!   Rust type panic: their input comes from outside the program, and nothing it
132//!   holds may stop the program.
133//!
134//! # Combining settings from several sources
135//!
136//! A host that reads settings from several sources, ranked (a program's
137//! defaults, the packages a document uses, its front matter, a command line),
138//! combines them with [`cascade`]: every value is recorded with where it was
139//! written, the source of the highest rank decides each key, a package wins
140//! over the packages it uses and its peers must agree, a key marked as combined
141//! key by key is combined one entry at a time over its default entries, and the
142//! result is read through the declarations above, each problem placed where the
143//! value at fault was written. The host keeps its sources and the texts that
144//! name them; the cascade reads no file.
145//!
146//! # The settings of a package
147//!
148//! A package (a bundle of features ready to register) is built from the settings
149//! of all its features at once, gathered in a [`PackageSettings`]; see
150//! [`PackageFactory`](crate::core::registry::PackageFactory).
151
152use std::any::Any;
153use std::collections::{BTreeMap, BTreeSet};
154use std::fmt;
155use std::sync::{Arc, OnceLock};
156
157use serde::de::DeserializeOwned;
158use serde_json::{Map, Value};
159
160use crate::core::registry::{BuildError, FeatureBuilder};
161use crate::model::names::{FeatureName, Name};
162use crate::model::options::{Bind, DataValue, OptionKey, Options, OptionValues};
163
164pub mod cascade;
165mod marks;
166pub mod named;
167
168/// The key that switches a feature on or off in a source of settings
169/// (`citations: {enabled: false}`), reserved in every feature's settings: a
170/// [`SettingsDecl`] refuses a key of this name (the constructors that take a
171/// Rust type panic, those that take data return a [`SettingsError`] of the
172/// kind [`SettingsErrorKind::InvalidDeclaration`]). The host that reads the
173/// sources of settings reads the key itself; the feature never receives it.
174pub const ENABLED_KEY: &str = "enabled";
175
176/// The bounds a Rust type must meet for settings to be read into it from data.
177///
178/// The trait is implemented for every type that implements both
179/// [`serde::de::DeserializeOwned`], which reads the data, and
180/// [`schemars::JsonSchema`], from which the schema of the settings is derived
181/// (and is `Send + Sync + 'static`). A crate outside this library that declares
182/// settings of its own lists `serde` and `schemars` as dependencies in its
183/// manifest and derives both traits on its settings types.
184pub trait SettingsData: DeserializeOwned + schemars::JsonSchema + Any + Send + Sync {}
185impl<T: DeserializeOwned + schemars::JsonSchema + Any + Send + Sync> SettingsData for T {}
186
187/// The keyword under which a node of a JSON Schema lists its marks
188/// ([`Mark`]), as the names of the marks: `{"type": "object", "x-flm-marks":
189/// ["merge-object-key-values", "remove-key-when-value-is-false"]}`.
190pub const MARKS_KEYWORD: &str = "x-flm-marks";
191
192/// A mark that a declaration sets on one of its settings, or on a value at any
193/// depth below one: how sources of settings combine the value, or what the
194/// value means.
195///
196/// A mark is written on the node of the JSON Schema that it concerns, under
197/// [`MARKS_KEYWORD`] (`x-flm-marks`), as its name ([`Mark::name`]); see
198/// [`KeyMark`] for the path of the node.
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
200pub enum Mark {
201    /// `merge-object-key-values`, on an object: sources of settings are
202    /// combined key by key. The `default` of the object's node is its default
203    /// entries ([`SettingsDecl::default_entries`]).
204    MergeObjectKeyValues,
205    /// `remove-key-when-value-is-false`, on an object: a key whose value is
206    /// `false` is removed.
207    RemoveKeyWhenValueIsFalse,
208    /// `set-to-default-with-null`, on one setting: a value of `null` gives the
209    /// setting its default.
210    SetToDefaultWithNull,
211    /// `path`, on a text or on a value that holds texts: each text is the path
212    /// of a file. The origin of the value gives each such text the form its
213    /// reader receives ([`CascadeOrigin::resolve_path`](cascade::CascadeOrigin::resolve_path)).
214    Path,
215    /// `markup`, on a text or on a value that holds texts: each text is
216    /// written in FLM markup, which the feature parses.
217    Markup,
218}
219
220impl Mark {
221    /// Every mark, in the order in which a node lists them.
222    pub const ALL: [Mark; 5] =
223        [Mark::MergeObjectKeyValues, Mark::RemoveKeyWhenValueIsFalse, Mark::SetToDefaultWithNull, Mark::Path, Mark::Markup];
224
225    /// The mark's name, as a schema writes it under [`MARKS_KEYWORD`].
226    pub fn name(self) -> &'static str {
227        match self {
228            Mark::MergeObjectKeyValues => "merge-object-key-values",
229            Mark::RemoveKeyWhenValueIsFalse => "remove-key-when-value-is-false",
230            Mark::SetToDefaultWithNull => "set-to-default-with-null",
231            Mark::Path => "path",
232            Mark::Markup => "markup",
233        }
234    }
235
236    /// The mark named `name`, or `None` when no mark has that name.
237    pub fn from_name(name: &str) -> Option<Mark> {
238        Mark::ALL.into_iter().find(|mark| mark.name() == name)
239    }
240}
241
242impl fmt::Display for Mark {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.write_str(self.name())
245    }
246}
247
248/// The marks ([`Mark`]) that a declaration sets on one of its settings, or on
249/// a value at any depth below one.
250///
251/// A declaration written in Rust sets marks with
252/// [`SettingsDecl::merge_entries`], [`SettingsDecl::remove_false`],
253/// [`SettingsDecl::default_on_null`], [`SettingsDecl::markup`] and
254/// [`SettingsDecl::path`]; a part declared from data writes them on the nodes
255/// of its schema. A host reads them with [`SettingsDecl::marks`] and
256/// [`SettingsDecl::mark_at`], and the JSON Schema writes each on its node
257/// ([`SettingsDecl::json_schema`]).
258///
259/// The marked value is identified by its path below the feature's name, its
260/// segments joined by `.`. The segment `*` means every entry of a map and every
261/// item of a list (`kinds.*.words`, a key of the theorems feature, marks the
262/// `words` of every theorem kind, `labels.*`
263/// every item of the list `labels`); a variant of an enumeration written as a
264/// map of one key is a segment of its own (`nesting.template`). In the schema,
265/// a property `K` of an object is the segment `K`, `additionalProperties` and
266/// `items` are the segment `*`, and the alternatives of a node (`anyOf`,
267/// `oneOf`, `allOf`) and the definition its `$ref` names in the schema's own
268/// `$defs` are at the node's path. A path that reaches no node of the
269/// declaration's schema is a mistake of the declaration.
270///
271/// A mark on a value that holds several texts (a list, a map, a structure) says
272/// what every text inside it is: `environments.*.labels` (the lists feature)
273/// marks every label template of every list environment, and `styles.*.join`
274/// (the numbering feature) every text of each counter style's join. A
275/// value that holds texts of different kinds is not marked as a whole; the
276/// values below it are marked one by one.
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct KeyMark {
279    /// The path of the marked value below the feature's name, its segments
280    /// separated by `.`, with `*` meaning every entry of a map and every item of
281    /// a list.
282    pub path: String,
283    /// The marks of the value, each once, in the order of [`Mark::ALL`].
284    pub marks: Vec<Mark>,
285}
286
287impl KeyMark {
288    /// Whether the value carries `mark`.
289    pub fn has(&self, mark: Mark) -> bool {
290        self.marks.contains(&mark)
291    }
292}
293
294/// Rewrites, in `data` (settings that `schema`, the object schema of a part
295/// declared from data, describes), every text at a node that the schema marks
296/// with `mark`, by `rewrite`; where the value at the node is a list or a map,
297/// every text inside it. The paths of the marked nodes are read as
298/// [`KeyMark`] says. A schema whose marks cannot be read marks nothing here:
299/// its declaration reports the fault ([`SettingsDecl::entry_data`]).
300///
301/// # Errors
302///
303/// The text of the first `Err` of `rewrite`, which leaves the text unchanged.
304pub(crate) fn rewrite_marked(
305    schema: &Value,
306    mark: Mark,
307    data: &mut Map<String, Value>,
308    rewrite: &mut dyn FnMut(&str) -> Result<String, String>,
309) -> Result<(), String> {
310    let Ok(read) = marks::read(schema) else { return Ok(()) };
311    let mut failed = None;
312    for node in read.iter().filter(|node| node.marks.contains(&mark)) {
313        let mut segments = node.path.split('.');
314        let Some(value) = segments.next().and_then(|key| data.get_mut(key)) else { continue };
315        let below: Vec<&str> = segments.collect();
316        texts_at(value, &below, &mut |text| {
317            if failed.is_some() {
318                return;
319            }
320            match rewrite(text) {
321                Ok(rewritten) => *text = rewritten,
322                Err(error) => failed = Some(error),
323            }
324        });
325    }
326    failed.map_or(Ok(()), Err)
327}
328
329/// Calls `visit` on every text in `value` at the place that `segments`
330/// designates below it (`*` matching every entry of a map and every item of a
331/// list); where the value at that place is a list or a map, on every text
332/// inside it.
333pub(crate) fn texts_at(value: &mut Value, segments: &[&str], visit: &mut dyn FnMut(&mut String)) {
334    match (segments.split_first(), value) {
335        (None, Value::String(text)) => visit(text),
336        (None, Value::Array(items)) => items.iter_mut().for_each(|item| texts_at(item, &[], visit)),
337        (None, Value::Object(map)) => map.values_mut().for_each(|item| texts_at(item, &[], visit)),
338        (Some((&"*", rest)), Value::Array(items)) => items.iter_mut().for_each(|item| texts_at(item, rest, visit)),
339        (Some((&"*", rest)), Value::Object(map)) => map.values_mut().for_each(|item| texts_at(item, rest, visit)),
340        (Some((name, rest)), Value::Object(map)) => {
341            if let Some(item) = map.get_mut(*name) {
342                texts_at(item, rest, visit);
343            }
344        }
345        _ => {}
346    }
347}
348
349/// One settings key of a feature, as [`SettingsDecl::keys`] and
350/// [`SettingsDecl::key`] return it.
351#[derive(Debug, Clone, PartialEq, Eq)]
352pub struct KeyDecl {
353    /// The key's name, which is the name of the Rust field its value is read
354    /// into, or a property of the schema of a part declared from data.
355    pub name: String,
356    /// The binding of the Rust type the field belongs to: where a value for the
357    /// key may be set.
358    pub bind: Bind,
359}
360
361/// The function of a [`Part`] that reads the part's keys, given as a map.
362type ReadFn = Arc<dyn Fn(Value) -> Result<ReadValue, ReadError> + Send + Sync>;
363
364/// The function of a [`Part`] that declares it as an option type.
365type DeclareFn = Arc<dyn Fn(&mut FeatureBuilder<'_>, Bind, String) -> Result<(), BuildError> + Send + Sync>;
366
367/// The function of a [`Part`] that returns its JSON Schema.
368type SchemaFn = Arc<dyn Fn(&mut schemars::SchemaGenerator) -> schemars::Schema + Send + Sync>;
369
370/// One Rust type of a feature's settings, or one part declared from data, with
371/// the functions that read it from data, declare it as an option type and give
372/// its JSON Schema.
373#[derive(Clone)]
374struct Part {
375    bind: Bind,
376    option: OptionKey,
377    docs: String,
378    keys: Vec<String>,
379    read: ReadFn,
380    declare: DeclareFn,
381    schema: SchemaFn,
382}
383
384/// The value read for one [`Part`]: a configuration, or the function that sets
385/// the option value read in an [`OptionValues`].
386enum ReadValue {
387    Config(Arc<dyn Any + Send + Sync>),
388    Option(Box<dyn FnOnce(&mut OptionValues)>),
389}
390
391/// A failure to read a feature's settings, or one part of them: the value at
392/// fault, by its path below the feature's name, and the condition it violates.
393///
394/// The reader of a configuration declared from data answers one
395/// ([`SettingsDecl::config_data_read`]), and so does each part of a
396/// declaration whose keys cannot be read; [`SettingsDecl::read`] reports it
397/// as a [`SettingsError`] of the kind [`SettingsErrorKind::InvalidValue`],
398/// whose path is the feature's name followed by `path`. As data, it is the
399/// map `{ path, detail }`, `path` being optional.
400#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
401#[serde(deny_unknown_fields)]
402pub struct ReadError {
403    /// The path of the value at fault below the feature's name, its segments
404    /// separated by `.` (`macros.abs.args`); empty when the fault concerns
405    /// the settings as a whole.
406    #[serde(default)]
407    pub path: String,
408    /// The condition the value violates, as a message for a person (``must be
409    /// a text, not `3` ``).
410    pub detail: String,
411}
412
413/// A feature's declaration of its settings: the Rust types they are read into,
414/// each with its binding, and marks on some of their keys.
415///
416/// A feature returns its declaration from
417/// [`FlmFeature::settings`](crate::core::registry::FlmFeature::settings). The
418/// registry build declares the feature's option types from it, and a package
419/// factory lists it beside the feature's name
420/// ([`PackageFactory`](crate::core::registry::PackageFactory)). A host uses it to
421/// read the feature's settings from data ([`SettingsDecl::read`]), to know the
422/// keys and their marks, and to describe them ([`SettingsDecl::json_schema`]).
423///
424/// Create one with [`SettingsDecl::new`], then add at most one configuration
425/// ([`config`](SettingsDecl::config) or [`config_from`](SettingsDecl::config_from)),
426/// any number of option types ([`options`](SettingsDecl::options)) and marks on
427/// the values they declare ([`merge_entries`](SettingsDecl::merge_entries),
428/// [`remove_false`](SettingsDecl::remove_false),
429/// [`default_on_null`](SettingsDecl::default_on_null),
430/// [`markup`](SettingsDecl::markup), [`path`](SettingsDecl::path)), each method
431/// taking and returning the declaration. Two types that declare the same key,
432/// and a mark whose path reaches no node of the schema, make these methods
433/// panic: a declaration that contradicts itself is a mistake in the feature's
434/// code. The parts declared from data
435/// ([`config_data`](SettingsDecl::config_data),
436/// [`config_data_read`](SettingsDecl::config_data_read),
437/// [`options_data`](SettingsDecl::options_data)) read their marks from the
438/// nodes of their schema, and return a fault of the declaration as an error.
439/// See the [module documentation](self).
440///
441/// # Examples
442///
443/// ```
444/// use flm_core::core::settings::SettingsDecl;
445/// use flm_core::model::options::Bind;
446///
447/// #[derive(Debug, Clone, Default, Hash, serde::Deserialize, schemars::JsonSchema)]
448/// #[serde(default, deny_unknown_fields)]
449/// struct PageOptions {
450///     /// The page's width, in characters.
451///     width: u32,
452/// }
453///
454/// let decl = SettingsDecl::new("page").options::<PageOptions>(Bind::Render, "The page.");
455/// assert_eq!(decl.keys().map(|key| key.name).collect::<Vec<_>>(), ["width"]);
456///
457/// let data = serde_json::json!({ "width": 72 });
458/// let settings = decl.read(data.as_object().unwrap()).unwrap();
459/// assert_eq!(settings.render_options().get::<PageOptions>().unwrap().width, 72);
460///
461/// let wrong = serde_json::json!({ "height": 72 });
462/// let errors = decl.read(wrong.as_object().unwrap()).unwrap_err();
463/// assert_eq!(errors[0].path, "page.height");
464/// ```
465#[derive(Clone)]
466pub struct SettingsDecl {
467    feature: FeatureName,
468    parts: Vec<Part>,
469    marks: Vec<KeyMark>,
470    defaults: Vec<(String, Map<String, Value>)>,
471    /// The places where other features declare entries
472    /// ([`open_entries`](SettingsDecl::open_entries)).
473    open: Vec<String>,
474    /// The entries of other features' keys that this feature declares
475    /// ([`entry_data`](SettingsDecl::entry_data)).
476    entries: Vec<EntryDecl>,
477    /// The entries in force of this feature's own keys, which other features
478    /// declare ([`with_entries`](SettingsDecl::with_entries)).
479    in_force: Vec<EntryDecl>,
480    /// The schema of the parts, against which the paths of the marks set by
481    /// method are checked: made on the first mark set after a part is added.
482    /// It holds no mark set by method; a data part keeps the `x-flm-marks` of
483    /// its own schema there.
484    bare: OnceLock<Arc<Value>>,
485}
486
487/// The declaration of one entry of a map that a key of another feature holds:
488/// the schema of that entry, which a feature gives in its own settings
489/// declaration ([`SettingsDecl::entry_data`]).
490///
491/// The feature that holds the key, the *owner*, states in its declaration the
492/// places where other features declare entries
493/// ([`SettingsDecl::open_entries`]); an entry is declared at one place that
494/// such a path names, by its concrete path below the owner's name (each `*`
495/// replaced by the entry's name). A declaration of an entry is in force when
496/// its feature and the owner are among the features of the packages in use and
497/// neither is switched off; the [`cascade`] then combines the owner's
498/// declaration with it ([`SettingsDecl::with_entries`]):
499///
500/// - the marks of the entry's schema apply to the values written under the
501///   entry, as the owner's own marks do;
502/// - a key written under the entry that the schema's `properties` lack is left
503///   out of the combined settings, with a warning at its origin;
504/// - the owner's JSON Schema ([`SettingsDecl::json_schema`]) holds the entry's
505///   schema at its place.
506///
507/// The values written under the entry are not checked against the types of
508/// the schema, as for any part declared from data.
509#[derive(Debug, Clone, PartialEq)]
510pub struct EntryDecl {
511    owner: FeatureName,
512    path: String,
513    /// What the entry is, in the words of the person who writes its schema
514    /// ([`SettingsDecl::entry_data`]).
515    label: String,
516    schema: Value,
517    keys: Vec<String>,
518    /// The marks of the schema, each path relative to the entry.
519    marks: Vec<KeyMark>,
520    /// The default entries of the objects of the schema combined key by key,
521    /// each path relative to the entry.
522    defaults: Vec<(String, Map<String, Value>)>,
523}
524
525impl EntryDecl {
526    /// The name of the feature that holds the key the entry belongs to.
527    pub fn owner(&self) -> &FeatureName {
528        &self.owner
529    }
530
531    /// The entry's path below the owner's name, its segments joined by `.`
532    /// (`template_config.html.base`).
533    pub fn path(&self) -> &str {
534        &self.path
535    }
536
537    /// What the entry is, in the words of the person who writes its schema,
538    /// without an article (`compose template ‘base’ for the output ‘html’`).
539    pub fn label(&self) -> &str {
540        &self.label
541    }
542
543    /// The keys the entry declares: the names of the `properties` of its
544    /// schema, in their order.
545    pub fn keys(&self) -> &[String] {
546        &self.keys
547    }
548}
549
550/// A function that returns the default entries of an object combined key by
551/// key: the entries the object holds when no source of settings writes it.
552///
553/// The function returns the entries as data, a map from each entry's name to the
554/// rest of the entry, or a text saying why they cannot be written as data.
555/// [`SettingsDecl::merge_entries`] calls it once, when the mark is set.
556pub type DefaultEntries = fn() -> Result<Value, String>;
557
558impl SettingsDecl {
559    /// Creates the declaration of the settings of the feature named `feature`,
560    /// with no key yet.
561    pub fn new(feature: impl Into<FeatureName>) -> SettingsDecl {
562        SettingsDecl {
563            feature: feature.into(),
564            parts: Vec::new(),
565            marks: Vec::new(),
566            defaults: Vec::new(),
567            open: Vec::new(),
568            entries: Vec::new(),
569            in_force: Vec::new(),
570            bare: OnceLock::new(),
571        }
572    }
573
574    /// Adds the feature's configuration, the type `C` its constructor takes,
575    /// with the description `docs`, and returns the declaration. Every field of
576    /// `C` is a settings key, bound when the registry is built
577    /// ([`Bind::Registry`]).
578    ///
579    /// `C` is read with its `Deserialize` implementation. An empty map must read
580    /// as `C`'s default, which `#[serde(default)]` on the type provides, because
581    /// [`read`](SettingsDecl::read) reads the configuration even when none of
582    /// its keys is written.
583    ///
584    /// # Panics
585    ///
586    /// When a field of `C` has the name of a key already declared or is named
587    /// [`ENABLED_KEY`] (`enabled`), when the declaration already has a
588    /// configuration, or when `C` is not read from a map of named fields.
589    pub fn config<C: SettingsData + Options>(self, docs: impl Into<String>) -> SettingsDecl {
590        self.config_from::<C, C>(docs)
591    }
592
593    /// Adds the feature's configuration, the type `C` its constructor takes,
594    /// read from data as the type `D` and converted with `C::try_from`, and
595    /// returns the declaration. Use it for a configuration that holds values
596    /// data cannot state, or whose form as data differs from its Rust type.
597    /// Every field of `D` is a settings key; a conversion error is reported as
598    /// a [`SettingsError`] for the feature as a whole. Otherwise as
599    /// [`config`](SettingsDecl::config).
600    ///
601    /// # Panics
602    ///
603    /// When a field of `D` has the name of a key already declared or is named
604    /// [`ENABLED_KEY`] (`enabled`), when the declaration already has a
605    /// configuration, or when `D` is not read from a map of named fields.
606    pub fn config_from<D, C>(self, docs: impl Into<String>) -> SettingsDecl
607    where
608        D: SettingsData,
609        C: Options + TryFrom<D>,
610        <C as TryFrom<D>>::Error: fmt::Display,
611    {
612        fn read<D, C>(data: Value) -> Result<ReadValue, ReadError>
613        where
614            D: SettingsData,
615            C: Options + TryFrom<D>,
616            <C as TryFrom<D>>::Error: fmt::Display,
617        {
618            let value = deserialize::<D>(data)?;
619            let config = C::try_from(value)
620                .map_err(|error| ReadError { path: String::new(), detail: error.to_string() })?;
621            Ok(ReadValue::Config(Arc::new(config)))
622        }
623        fn declare<C: Options>(
624            b: &mut FeatureBuilder<'_>,
625            bind: Bind,
626            docs: String,
627        ) -> Result<(), BuildError> {
628            b.options_with_docs::<C>(bind, docs)
629        }
630        self.part(Part {
631            bind: Bind::Registry,
632            option: OptionKey::of::<C>(),
633            docs: crate::kept_docs(docs),
634            keys: field_names::<D>(),
635            read: Arc::new(read::<D, C>),
636            declare: Arc::new(declare::<C>),
637            schema: Arc::new(|generator: &mut schemars::SchemaGenerator| generator.subschema_for::<D>()),
638        })
639    }
640
641    /// Adds the feature's configuration declared from data, and returns the
642    /// declaration: `schema` is a JSON Schema of an object, whose `properties`
643    /// are the configuration's settings keys, bound when the registry is built
644    /// ([`Bind::Registry`]); `docs` describes it.
645    ///
646    /// The configuration is the option type named by the feature's name
647    /// ([`OptionKey::Data`]). [`read`](SettingsDecl::read) keeps the values
648    /// written as a [`DataValue`], the empty map when none of the keys is
649    /// written, and checks nothing of them but their keys (see the [module
650    /// documentation](self#settings-declared-from-data)); a package reads it with
651    /// [`PackageSettings::config`]`::<DataValue>`. A feature that reads its
652    /// configuration when the settings are read declares it with
653    /// [`config_data_read`](SettingsDecl::config_data_read).
654    ///
655    /// The schema's own `$defs` join those of the declaration's schema
656    /// ([`json_schema`](SettingsDecl::json_schema)): a `$defs` name shared with
657    /// another part of the declaration refers to one definition.
658    ///
659    /// # Errors
660    ///
661    /// A [`SettingsError`] of the kind [`SettingsErrorKind::InvalidDeclaration`]
662    /// when `schema` has no `properties` map, when one of its properties is a
663    /// key declared already or is named [`ENABLED_KEY`] (`enabled`), when
664    /// the declaration has a configuration already, or when the marks of its
665    /// nodes are not a list of mark names, lie outside every setting (on the
666    /// schema's root, or under a keyword that no path follows), mark an
667    /// object as combined key by key with a `default` that is not a map, or
668    /// are read while a definition of `$defs` that refers to itself is read
669    /// (a mark is kept with its path, and a path names one depth of the
670    /// definition).
671    pub fn config_data(self, schema: Value, docs: impl Into<String>) -> Result<SettingsDecl, SettingsError> {
672        self.data_config(schema, docs.into(), Arc::new(|data: Value| Ok(ReadValue::Config(Arc::new(DataValue(data))))))
673    }
674
675    /// Adds the feature's configuration declared from data, read by `read`,
676    /// and returns the declaration: as [`config_data`](SettingsDecl::config_data),
677    /// except that [`read`](SettingsDecl::read) gives the configuration
678    /// written (the empty map when none of its keys is written) to `read`, and
679    /// keeps the value `read` answers as the [`DataValue`] that
680    /// [`PackageSettings::config`]`::<DataValue>` gives.
681    ///
682    /// `read` is the twin of [`config_from`](SettingsDecl::config_from)'s
683    /// reading as `D` and conversion with `C::try_from`: it answers the value
684    /// the feature receives, or the value at fault as a [`ReadError`], which
685    /// is reported as `config_from`'s conversion errors are, a
686    /// [`SettingsError`] of the kind [`SettingsErrorKind::InvalidValue`] whose
687    /// path is the feature's name followed by the error's path. A reader that
688    /// only checks the configuration answers it unchanged.
689    ///
690    /// # Errors
691    ///
692    /// As [`config_data`](SettingsDecl::config_data).
693    pub fn config_data_read(
694        self,
695        schema: Value,
696        docs: impl Into<String>,
697        read: Arc<dyn Fn(Value) -> Result<Value, ReadError> + Send + Sync>,
698    ) -> Result<SettingsDecl, SettingsError> {
699        let read: ReadFn = Arc::new(move |data: Value| Ok(ReadValue::Config(Arc::new(DataValue(read(data)?)))));
700        self.data_config(schema, docs.into(), read)
701    }
702
703    /// The configuration declared from data with the schema `schema`, the
704    /// description `docs` and the reading `read`: what
705    /// [`config_data`](SettingsDecl::config_data) and
706    /// [`config_data_read`](SettingsDecl::config_data_read) add.
707    fn data_config(self, schema: Value, docs: String, read: ReadFn) -> Result<SettingsDecl, SettingsError> {
708        let feature = self.feature.clone();
709        let keys = schema_keys(&schema).ok_or_else(|| {
710            self.invalid(
711                String::new(),
712                format!(
713                    "the schema of the configuration of the feature `{feature}` must be an object \
714                     schema with `properties`, a map from each setting to its schema"
715                ),
716            )
717        })?;
718        let name = Name::clone(&feature);
719        self.try_part(Part {
720            bind: Bind::Registry,
721            option: OptionKey::Data(name.clone()),
722            docs: crate::kept_docs(docs),
723            keys,
724            read,
725            declare: declare_named(name),
726            schema: data_schema(schema.clone()),
727        })?
728        .with_read_marks(&schema)
729    }
730
731    /// Adds the option type named `name`, declared from data, with the binding
732    /// `bind`, and returns the declaration: `schema` is a JSON Schema of an
733    /// object, whose `properties` are the option type's settings keys; `docs`
734    /// describes it.
735    ///
736    /// The option type is identified by `name` ([`OptionKey::Data`]); a stage
737    /// reads it by that name
738    /// ([`StageCx::option_named`](crate::core::run::StageCx::option_named)).
739    /// [`read`](SettingsDecl::read) keeps the values written as a [`DataValue`]
740    /// and checks nothing of them but their keys; when none of its keys is
741    /// written, the option type gets no value, and a read resolves to the empty
742    /// map.
743    ///
744    /// The schema's own `$defs` join those of the declaration's schema
745    /// ([`json_schema`](SettingsDecl::json_schema)): a `$defs` name shared with
746    /// another part of the declaration refers to one definition.
747    ///
748    /// # Errors
749    ///
750    /// As [`config_data`](SettingsDecl::config_data), and when `bind` is
751    /// [`Bind::Registry`] (a value fixed with the registry is the feature's
752    /// configuration).
753    pub fn options_data(
754        self,
755        name: impl Into<Name>,
756        bind: Bind,
757        schema: Value,
758        docs: impl Into<String>,
759    ) -> Result<SettingsDecl, SettingsError> {
760        let name = name.into();
761        let feature = self.feature.clone();
762        if bind == Bind::Registry {
763            return Err(self.invalid(
764                String::new(),
765                format!(
766                    "the feature `{feature}` declares the option `{name}` bound to the registry, \
767                     and a value fixed when the registry is built belongs in the feature's \
768                     configuration"
769                ),
770            ));
771        }
772        let keys = schema_keys(&schema).ok_or_else(|| {
773            self.invalid(
774                String::new(),
775                format!(
776                    "the schema of the option `{name}` of the feature `{feature}` must be an object \
777                     schema with `properties`, a map from each setting to its schema"
778                ),
779            )
780        })?;
781        let read_name = name.clone();
782        self.try_part(Part {
783            bind,
784            option: OptionKey::Data(name.clone()),
785            docs: crate::kept_docs(docs),
786            keys,
787            read: Arc::new(move |data: Value| {
788                let name = read_name.clone();
789                Ok(ReadValue::Option(Box::new(move |values: &mut OptionValues| values.set_named(name, data))))
790            }),
791            declare: declare_named(name),
792            schema: data_schema(schema.clone()),
793        })?
794        .with_read_marks(&schema)
795    }
796
797    /// Adds the option type `O` of the feature, with the binding `bind` and the
798    /// description `docs`, and returns the declaration. Every field of `O` is a
799    /// settings key.
800    ///
801    /// # Panics
802    ///
803    /// When `bind` is [`Bind::Registry`] (a value fixed with the registry is
804    /// the feature's configuration: see [`config`](SettingsDecl::config)), when
805    /// a field of `O` has the name of a key already declared or is named
806    /// [`ENABLED_KEY`] (`enabled`), or when `O` is not read from a map of named
807    /// fields.
808    pub fn options<O: SettingsData + Options>(
809        self,
810        bind: Bind,
811        docs: impl Into<String>,
812    ) -> SettingsDecl {
813        assert!(
814            bind != Bind::Registry,
815            "the feature `{}` declares the option type `{}` with `Bind::Registry`, but the values \
816             of an option type must be set on the document or on the render request; a value \
817             fixed when the registry is built belongs in the feature's configuration, declared \
818             with `SettingsDecl::config`",
819            self.feature,
820            crate::model::options::short_type_name(std::any::type_name::<O>())
821        );
822        fn read<O: SettingsData + Options>(data: Value) -> Result<ReadValue, ReadError> {
823            let value = deserialize::<O>(data)?;
824            Ok(ReadValue::Option(Box::new(move |values: &mut OptionValues| values.set::<O>(value))))
825        }
826        fn declare<O: Options>(
827            b: &mut FeatureBuilder<'_>,
828            bind: Bind,
829            docs: String,
830        ) -> Result<(), BuildError> {
831            b.options_with_docs::<O>(bind, docs)
832        }
833        self.part(Part {
834            bind,
835            option: OptionKey::of::<O>(),
836            docs: crate::kept_docs(docs),
837            keys: field_names::<O>(),
838            read: Arc::new(read::<O>),
839            declare: Arc::new(declare::<O>),
840            schema: Arc::new(|generator: &mut schemars::SchemaGenerator| generator.subschema_for::<O>()),
841        })
842    }
843
844    /// Adds `part`; panics on a contradiction (a declaration in Rust code).
845    fn part(self, part: Part) -> SettingsDecl {
846        match self.try_part(part) {
847            Ok(decl) => decl,
848            Err(error) => panic!("{}", error.detail),
849        }
850    }
851
852    /// Adds `part`, or returns the fault it makes: a key named
853    /// [`ENABLED_KEY`], or a contradiction with the parts already declared (a
854    /// key declared twice, or a second configuration).
855    fn try_part(mut self, part: Part) -> Result<SettingsDecl, SettingsError> {
856        if part.keys.iter().any(|key| key == ENABLED_KEY) {
857            let detail = format!(
858                "the feature ‘{}’ declares the setting ‘{ENABLED_KEY}’, a name reserved for \
859                 switching a feature on or off",
860                self.feature
861            );
862            return Err(self.invalid(ENABLED_KEY.to_string(), detail));
863        }
864        for key in &part.keys {
865            if self.part_of(key).is_some() {
866                let detail = format!("the feature `{}` declares the setting `{key}` twice", self.feature);
867                return Err(self.invalid(key.clone(), detail));
868            }
869        }
870        if part.bind == Bind::Registry && self.parts.iter().any(|p| p.bind == Bind::Registry) {
871            let detail = format!("the feature `{}` declares two configurations", self.feature);
872            return Err(self.invalid(String::new(), detail));
873        }
874        self.parts.push(part);
875        self.bare = OnceLock::new();
876        Ok(self)
877    }
878
879    /// An [`InvalidDeclaration`](SettingsErrorKind::InvalidDeclaration) error
880    /// at `path` below the feature's name (the feature's name alone when `path`
881    /// is empty).
882    fn invalid(&self, path: String, detail: String) -> SettingsError {
883        let path = if path.is_empty() { self.feature.to_string() } else { format!("{}.{path}", self.feature) };
884        SettingsError { path, kind: SettingsErrorKind::InvalidDeclaration, detail }
885    }
886
887    /// Marks the object at `path` as combined key by key
888    /// ([`Mark::MergeObjectKeyValues`]), and returns the declaration: a host that
889    /// combines two sources of settings combines that object one key at a time.
890    /// See [`KeyMark`] for the form of the path, which reaches a value at any
891    /// depth.
892    ///
893    /// `default_entries` returns, as data, the entries the object holds when no
894    /// source writes it: the feature's own default. A host treats them as the
895    /// lowest-ranked source, so an entry a source writes replaces the default
896    /// entry of that name, and the default entries no source writes stay. The
897    /// function usually writes the default of the key's Rust field as data
898    /// ([`named::to_data`] for a list of named entries). Read them back with
899    /// [`default_entries`](SettingsDecl::default_entries); the JSON Schema
900    /// gives them as the `default` of the object's node.
901    ///
902    /// A collection of named things is also marked with
903    /// [`remove_false`](SettingsDecl::remove_false).
904    ///
905    /// # Panics
906    ///
907    /// When `path` reaches no node of the declaration's schema, and when
908    /// `default_entries` fails or returns something other than a map: both are
909    /// mistakes in the feature's code, not in any data.
910    pub fn merge_entries(self, path: impl Into<String>, default_entries: DefaultEntries) -> SettingsDecl {
911        let path = path.into();
912        let decl = self.mark(path.clone(), Mark::MergeObjectKeyValues);
913        let entries = match default_entries() {
914            Ok(Value::Object(entries)) => entries,
915            Ok(other) => panic!(
916                "the default entries of ‘{}.{path}’ must be written as a map, not ‘{other}’",
917                decl.feature
918            ),
919            Err(detail) => panic!(
920                "the default entries of ‘{}.{path}’ cannot be written as data: {detail}",
921                decl.feature
922            ),
923        };
924        decl.with_default(path, entries)
925    }
926
927    /// Records `entries` as the default entries of the object at `path`.
928    fn with_default(mut self, path: String, entries: Map<String, Value>) -> SettingsDecl {
929        self.defaults.retain(|(marked, _)| *marked != path);
930        self.defaults.push((path, entries));
931        self
932    }
933
934    /// The default entries of the object at `path`, marked as combined key by
935    /// key ([`Mark::MergeObjectKeyValues`]): the entries it holds when no source
936    /// of settings writes it, as a map from each entry's name to the rest of the
937    /// entry, in the feature's order. Returns `None` when the object is not
938    /// marked so.
939    pub fn default_entries(&self, path: &str) -> Option<&Map<String, Value>> {
940        self.defaults.iter().find(|(marked, _)| marked == path).map(|(_, entries)| entries)
941    }
942
943    /// Marks the object at `path` as one in which a key whose value is `false`
944    /// is removed ([`Mark::RemoveKeyWhenValueIsFalse`]) and returns the
945    /// declaration. See [`KeyMark`] for the form of the path.
946    ///
947    /// # Panics
948    ///
949    /// When `path` reaches no node of the declaration's schema.
950    pub fn remove_false(self, path: impl Into<String>) -> SettingsDecl {
951        self.mark(path.into(), Mark::RemoveKeyWhenValueIsFalse)
952    }
953
954    /// Marks the setting at `path` as one that a value of `null` gives its
955    /// default ([`Mark::SetToDefaultWithNull`]) and returns the declaration. See
956    /// [`KeyMark`] for the form of the path.
957    ///
958    /// # Panics
959    ///
960    /// When `path` reaches no node of the declaration's schema.
961    pub fn default_on_null(self, path: impl Into<String>) -> SettingsDecl {
962        self.mark(path.into(), Mark::SetToDefaultWithNull)
963    }
964
965    /// Marks the value at `path` as text in FLM markup ([`Mark::Markup`]) and
966    /// returns the declaration. See [`KeyMark`] for the form of the path.
967    ///
968    /// # Panics
969    ///
970    /// When `path` reaches no node of the declaration's schema.
971    pub fn markup(self, path: impl Into<String>) -> SettingsDecl {
972        self.mark(path.into(), Mark::Markup)
973    }
974
975    /// Marks the value at `path` as a path to a file ([`Mark::Path`]) and
976    /// returns the declaration. See [`KeyMark`] for the form of the path.
977    ///
978    /// # Panics
979    ///
980    /// When `path` reaches no node of the declaration's schema.
981    pub fn path(self, path: impl Into<String>) -> SettingsDecl {
982        self.mark(path.into(), Mark::Path)
983    }
984
985    /// Sets `mark` on the value at `path` and returns the declaration: the
986    /// methods above. A mark set on a value that carries it already changes
987    /// nothing.
988    ///
989    /// # Panics
990    ///
991    /// When `path` reaches no node of the declaration's schema.
992    fn mark(self, path: String, mark: Mark) -> SettingsDecl {
993        let bare = Arc::clone(self.bare.get_or_init(|| Arc::new(self.bare_schema())));
994        if !marks::reaches(&bare, &path) {
995            panic!("missing setting ‘{path}’ for the mark ‘{mark}’ of the feature ‘{}’", self.feature);
996        }
997        self.with_mark(path, mark)
998    }
999
1000    /// Adds `mark` to the marks of the value at `path`.
1001    fn with_mark(mut self, path: String, mark: Mark) -> SettingsDecl {
1002        match self.marks.iter_mut().find(|marked| marked.path == path) {
1003            Some(marked) => {
1004                if !marked.has(mark) {
1005                    marked.marks.push(mark);
1006                    marked.marks.sort();
1007                }
1008            }
1009            None => self.marks.push(KeyMark { path, marks: vec![mark] }),
1010        }
1011        self
1012    }
1013
1014    /// Adds the marks that the schema `schema` of a part declared from data
1015    /// writes on its nodes, each with its default entries.
1016    fn with_read_marks(mut self, schema: &Value) -> Result<SettingsDecl, SettingsError> {
1017        let read = read_marks(schema, &self.feature, "", &format!("the feature ‘{}’", self.feature))?;
1018        for written in read {
1019            for mark in written.marks {
1020                self = self.with_mark(written.path.clone(), mark);
1021            }
1022            if let Some(entries) = written.default {
1023                self = self.with_default(written.path, entries);
1024            }
1025        }
1026        Ok(self)
1027    }
1028
1029    /// Marks the places `path` (see [`KeyMark`] for its form) as those where
1030    /// other features declare entries ([`entry_data`](SettingsDecl::entry_data),
1031    /// [`EntryDecl`]), and returns the declaration: `template_config.*.*`
1032    /// lets another feature declare the schema of `template_config.html.base`.
1033    ///
1034    /// # Panics
1035    ///
1036    /// When `path` reaches no node of the declaration's schema.
1037    pub fn open_entries(self, path: impl Into<String>) -> SettingsDecl {
1038        let path = path.into();
1039        let bare = Arc::clone(self.bare.get_or_init(|| Arc::new(self.bare_schema())));
1040        if !marks::reaches(&bare, &path) {
1041            panic!("missing setting ‘{path}’ for the entries that the feature ‘{}’ opens", self.feature);
1042        }
1043        let mut decl = self;
1044        if !decl.open.contains(&path) {
1045            decl.open.push(path);
1046        }
1047        decl
1048    }
1049
1050    /// Whether another feature may declare the entry at `path` (its segments
1051    /// joined by `.`, with no `*`): one of the places
1052    /// [`open_entries`](SettingsDecl::open_entries) gives names it.
1053    pub fn opens(&self, path: &str) -> bool {
1054        let segments: Vec<String> = path.split('.').map(str::to_string).collect();
1055        self.open.iter().any(|open| cascade::names(open, &segments))
1056    }
1057
1058    /// Declares the schema of the entry at `path` of a key of the feature
1059    /// `owner`, and returns the declaration (see [`EntryDecl`]). `path` is the
1060    /// entry's path below the owner's name, its segments joined by `.`, each
1061    /// segment the name of an entry (`template_config.html.base`); `label` is
1062    /// what the entry is, in the words of the person who writes its schema and
1063    /// without an article (`compose template ‘base’ for the output ‘html’`),
1064    /// which the messages about the entry name it by; `schema` is
1065    /// a JSON Schema of an object, whose `properties` are the keys of the
1066    /// entry, with the marks written on its nodes, read as those of a part
1067    /// declared from data are (see the [module
1068    /// documentation](self#settings-declared-from-data)). An entry is not a
1069    /// key of the declaring feature: a declaration with entries and no key of
1070    /// its own describes a feature that takes no settings
1071    /// ([`takes_settings`](SettingsDecl::takes_settings)).
1072    ///
1073    /// # Errors
1074    ///
1075    /// A [`SettingsError`] of the kind [`SettingsErrorKind::InvalidDeclaration`]
1076    /// when `path` holds `*` or an empty segment, when the declaration already
1077    /// declares that entry, when `schema` has no `properties` map, or when the
1078    /// marks of its nodes are faulty as [`config_data`](SettingsDecl::config_data)
1079    /// states.
1080    pub fn entry_data(
1081        mut self,
1082        owner: impl Into<FeatureName>,
1083        path: impl Into<String>,
1084        label: impl Into<String>,
1085        schema: Value,
1086    ) -> Result<SettingsDecl, SettingsError> {
1087        let (owner, path, label) = (owner.into(), path.into(), label.into());
1088        let at = |detail: String| SettingsError {
1089            path: format!("{owner}.{path}"),
1090            kind: SettingsErrorKind::InvalidDeclaration,
1091            detail,
1092        };
1093        if path.split('.').any(|segment| segment.is_empty() || segment == "*") {
1094            return Err(at(format!(
1095                "Invalid entry ‘{owner}.{path}’ declared by the feature ‘{}’: each part of the path must name one entry",
1096                self.feature
1097            )));
1098        }
1099        if self.entries.iter().any(|entry| entry.owner == owner && entry.path == path) {
1100            return Err(at(format!("Duplicate {label} (feature ‘{}’)", self.feature)));
1101        }
1102        let Some(keys) = schema_keys(&schema) else {
1103            return Err(at(format!(
1104                "Invalid settings schema of the {label}: it must be an object schema with ‘properties’, a map \
1105                 from each setting to its schema"
1106            )));
1107        };
1108        let mut marks: Vec<KeyMark> = Vec::new();
1109        let mut defaults = Vec::new();
1110        for written in read_marks(&schema, &owner, &path, &format!("the {label}"))? {
1111            match marks.iter_mut().find(|marked| marked.path == written.path) {
1112                Some(marked) => {
1113                    marked.marks.extend(written.marks);
1114                    marked.marks.sort();
1115                    marked.marks.dedup();
1116                }
1117                None => marks.push(KeyMark { path: written.path.clone(), marks: written.marks }),
1118            }
1119            if let Some(entries) = written.default {
1120                defaults.push((written.path, entries));
1121            }
1122        }
1123        self.entries.push(EntryDecl { owner, path, label, schema, keys, marks, defaults });
1124        Ok(self)
1125    }
1126
1127    /// The entries of other features' keys that this feature declares
1128    /// ([`entry_data`](SettingsDecl::entry_data)), in the order declared.
1129    pub fn entries(&self) -> &[EntryDecl] {
1130        &self.entries
1131    }
1132
1133    /// Returns this declaration combined with the declarations of its entries
1134    /// `entries`, those in force (see [`EntryDecl`]): each entry of `entries`
1135    /// whose owner is this feature and whose path this declaration opens
1136    /// ([`opens`](SettingsDecl::opens)); the others are ignored.
1137    ///
1138    /// The result carries the marks of each entry's schema at their paths
1139    /// below the entry, with their default entries; the marks that this
1140    /// declaration sets on the places of the entry and of the maps above it,
1141    /// by a path with `*`, also at the entry's own path, so that its JSON
1142    /// Schema writes them on the entry's node; and the entry's schema at its
1143    /// place in its JSON Schema ([`json_schema`](SettingsDecl::json_schema)),
1144    /// its `$defs` joining those of the result under names of the entry's
1145    /// own (its path, a `.` and the definition's name). [`entry_in_force`](SettingsDecl::entry_in_force)
1146    /// gives each entry back. The cascade makes it from the entries declared by
1147    /// the features in use.
1148    pub fn with_entries<'e>(&self, entries: impl IntoIterator<Item = &'e EntryDecl>) -> SettingsDecl {
1149        let mut decl = self.clone();
1150        for entry in entries {
1151            if entry.owner != self.feature || !self.opens(&entry.path) || decl.entry_in_force(&entry.path).is_some() {
1152                continue;
1153            }
1154            let segments: Vec<String> = entry.path.split('.').map(str::to_string).collect();
1155            for depth in 2..=segments.len() {
1156                let place = &segments[..depth];
1157                let concrete = place.join(".");
1158                let owned: Vec<KeyMark> =
1159                    self.marks.iter().filter(|marked| cascade::names(&marked.path, place)).cloned().collect();
1160                for marked in owned {
1161                    for mark in &marked.marks {
1162                        decl = decl.with_mark(concrete.clone(), *mark);
1163                    }
1164                    if let Some(entries) = self.default_entries(&marked.path) {
1165                        decl = decl.with_default(concrete.clone(), entries.clone());
1166                    }
1167                }
1168            }
1169            for marked in &entry.marks {
1170                for mark in &marked.marks {
1171                    decl = decl.with_mark(format!("{}.{}", entry.path, marked.path), *mark);
1172                }
1173            }
1174            for (path, entries) in &entry.defaults {
1175                decl = decl.with_default(format!("{}.{path}", entry.path), entries.clone());
1176            }
1177            decl.in_force.push(entry.clone());
1178        }
1179        decl
1180    }
1181
1182    /// The entry in force at `path` (its segments joined by `.`), declared by
1183    /// another feature and combined with this declaration by
1184    /// [`with_entries`](SettingsDecl::with_entries), if there is one.
1185    pub fn entry_in_force(&self, path: &str) -> Option<&EntryDecl> {
1186        self.in_force.iter().find(|entry| entry.path == path)
1187    }
1188}
1189
1190/// The marks that `schema`, a schema given as data, writes on its nodes, each
1191/// at its path; `prefix` is the path of the schema below the feature `feature`
1192/// (empty for a part of the feature's own settings, the entry's path for a
1193/// declaration of an entry, [`SettingsDecl::entry_data`]), and the paths read
1194/// are relative to it. The messages name the schema's holder by `holder`
1195/// (`the feature ‘X’`, or the label of the entry with its article) and each
1196/// node by its path relative to `prefix`.
1197///
1198/// # Errors
1199///
1200/// A fault of the marks, as a [`SettingsError`] of the kind
1201/// [`SettingsErrorKind::InvalidDeclaration`] at the place it concerns.
1202fn read_marks(
1203    schema: &Value,
1204    feature: &FeatureName,
1205    prefix: &str,
1206    holder: &str,
1207) -> Result<Vec<marks::ReadMark>, SettingsError> {
1208    let full = |path: &str| match (prefix.is_empty(), path.is_empty()) {
1209        (true, _) => path.to_string(),
1210        (false, true) => prefix.to_string(),
1211        (false, false) => format!("{prefix}.{path}"),
1212    };
1213    marks::read(schema).map_err(|fault| {
1214        let (path, detail) = match fault {
1215            marks::Fault::NotAList(path) => {
1216                let detail = format!("‘{MARKS_KEYWORD}’ on ‘{path}’ of {holder} must be a list of mark names");
1217                (full(&path), detail)
1218            }
1219            marks::Fault::Unknown(path, name) => {
1220                let names: Vec<String> = Mark::ALL.iter().map(|mark| format!("‘{mark}’")).collect();
1221                let detail = format!("unknown mark ‘{name}’ on ‘{path}’ of {holder} (the marks are {})", names.join(", "));
1222                (full(&path), detail)
1223            }
1224            marks::Fault::DefaultNotAMap(path) => {
1225                let detail = format!(
1226                    "the default of ‘{path}’ of {holder} must be a map (mark ‘{}’)",
1227                    Mark::MergeObjectKeyValues
1228                );
1229                (full(&path), detail)
1230            }
1231            marks::Fault::Outside(pointer) => {
1232                let place = if pointer.is_empty() { "on the root".to_string() } else { format!("at ‘{pointer}’") };
1233                let detail = format!(
1234                    "misplaced ‘{MARKS_KEYWORD}’ {place} of the settings schema of {holder}: marks must be written on \
1235                     a setting or on a value below one"
1236                );
1237                (prefix.to_string(), detail)
1238            }
1239            marks::Fault::Recursive(path, definition) => {
1240                let detail = format!(
1241                    "invalid mark on ‘{path}’ of {holder}: \
1242                     marks may not be placed inside the recursive definition ‘{definition}’"
1243                );
1244                (full(&path), detail)
1245            }
1246        };
1247        let path = if path.is_empty() { feature.to_string() } else { format!("{feature}.{path}") };
1248        SettingsError { path, kind: SettingsErrorKind::InvalidDeclaration, detail }
1249    })
1250}
1251
1252impl SettingsDecl {
1253    /// The name of the feature whose settings this declaration describes.
1254    pub fn feature(&self) -> &FeatureName {
1255        &self.feature
1256    }
1257
1258    /// Every settings key the feature declares, with its binding: the fields of its
1259    /// configuration first, then those of each option type, in the order
1260    /// declared.
1261    pub fn keys(&self) -> impl Iterator<Item = KeyDecl> + '_ {
1262        self.parts
1263            .iter()
1264            .flat_map(|part| part.keys.iter().map(|name| KeyDecl { name: name.clone(), bind: part.bind }))
1265    }
1266
1267    /// Whether the feature takes settings: whether the declaration has a key
1268    /// of its own ([`keys`](SettingsDecl::keys)). A declaration that only
1269    /// declares entries of another feature's keys
1270    /// ([`entry_data`](SettingsDecl::entry_data)) describes a feature that
1271    /// takes no settings.
1272    pub fn takes_settings(&self) -> bool {
1273        self.keys().next().is_some()
1274    }
1275
1276    /// The Rust types the settings are read into, each identified by its option
1277    /// key and given with its binding, in the order they were added; the
1278    /// configuration's binding is [`Bind::Registry`]. The registry build
1279    /// declares each of them as an option type of the feature.
1280    pub fn option_types(&self) -> impl Iterator<Item = (OptionKey, Bind)> + '_ {
1281        self.parts.iter().map(|part| (part.option.clone(), part.bind))
1282    }
1283
1284    /// The settings key `name`, or `None` when the feature does not declare it.
1285    pub fn key(&self, name: &str) -> Option<KeyDecl> {
1286        self.keys().find(|key| key.name == name)
1287    }
1288
1289    /// The marks on the feature's settings and the values below them, one
1290    /// [`KeyMark`] per marked path, in the order each path was first marked.
1291    pub fn marks(&self) -> &[KeyMark] {
1292        &self.marks
1293    }
1294
1295    /// Whether a mark of the declaration sets `mark` on the place `place`, the
1296    /// key first, then the names below it: a mark's path names the place when
1297    /// each of its segments is the place's name there, or `*` (see [`KeyMark`]).
1298    pub fn is_marked(&self, place: &[String], mark: Mark) -> bool {
1299        self.marks.iter().any(|marks| marks.has(mark) && cascade::names(&marks.path, place))
1300    }
1301
1302    /// The marks on the value at `path` (see [`KeyMark`]), or `None` when no
1303    /// mark is set there.
1304    pub fn mark_at(&self, path: &str) -> Option<&KeyMark> {
1305        self.marks.iter().find(|mark| mark.path == path)
1306    }
1307
1308    /// Whether the value at `path` carries `mark`.
1309    pub fn has_mark(&self, path: &str, mark: Mark) -> bool {
1310        self.mark_at(path).is_some_and(|marked| marked.has(mark))
1311    }
1312
1313    fn part_of(&self, key: &str) -> Option<&Part> {
1314        self.parts.iter().find(|part| part.keys.iter().any(|name| name == key))
1315    }
1316
1317    /// Reads the feature's settings from `data`, a map from a settings key to its
1318    /// value.
1319    ///
1320    /// Returns the configuration (its default when none of its keys is
1321    /// written) and the option values of each option type at least one of whose
1322    /// keys is written; an option type none of whose keys is written gets no
1323    /// value. Values of an option type bound to the render request go to
1324    /// [`FeatureSettings::render_options`]; values of the other option types go
1325    /// to [`FeatureSettings::document_options`].
1326    ///
1327    /// # Errors
1328    ///
1329    /// Returns every problem found, each as a [`SettingsError`] that identifies
1330    /// the key by its path from the feature's name: every key in `data` that the
1331    /// feature does not declare, and every value that cannot be read as its key
1332    /// requires.
1333    pub fn read(&self, data: &Map<String, Value>) -> Result<FeatureSettings, Vec<SettingsError>> {
1334        let mut errors = Vec::new();
1335        for key in data.keys() {
1336            if self.part_of(key).is_none() {
1337                errors.push(SettingsError {
1338                    path: format!("{}.{key}", self.feature),
1339                    kind: SettingsErrorKind::UnknownKey,
1340                    detail: format!("the feature `{}` has no setting `{key}`", self.feature),
1341                });
1342            }
1343        }
1344        let mut settings = FeatureSettings {
1345            feature: self.feature.clone(),
1346            config: None,
1347            document: OptionValues::new(),
1348            render: OptionValues::new(),
1349        };
1350        for part in &self.parts {
1351            let written: Map<String, Value> = data
1352                .iter()
1353                .filter(|(key, _)| part.keys.iter().any(|name| name == *key))
1354                .map(|(key, value)| (key.clone(), value.clone()))
1355                .collect();
1356            if written.is_empty() && part.bind != Bind::Registry {
1357                continue;
1358            }
1359            match (part.read)(Value::Object(written)) {
1360                Ok(ReadValue::Config(config)) => settings.config = Some(config),
1361                Ok(ReadValue::Option(set)) => {
1362                    let values = match part.bind {
1363                        Bind::Render => &mut settings.render,
1364                        _ => &mut settings.document,
1365                    };
1366                    set(values);
1367                }
1368                Err(error) => {
1369                    let path = if error.path.is_empty() {
1370                        self.feature.to_string()
1371                    } else {
1372                        format!("{}.{}", self.feature, error.path)
1373                    };
1374                    errors.push(SettingsError {
1375                        detail: format!("the value of `{path}` is invalid: {}", error.detail),
1376                        path,
1377                        kind: SettingsErrorKind::InvalidValue,
1378                    });
1379                }
1380            }
1381        }
1382        if errors.is_empty() { Ok(settings) } else { Err(errors) }
1383    }
1384
1385    /// Declares the feature's option types on `b`, each with its binding and
1386    /// its documentation, the configuration among them as an option type bound
1387    /// when the registry is built. The registry build calls this for every
1388    /// feature that returns a declaration from
1389    /// [`FlmFeature::settings`](crate::core::registry::FlmFeature::settings),
1390    /// before it calls the feature's `register`.
1391    pub(crate) fn declare(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1392        for part in &self.parts {
1393            (part.declare)(b, part.bind, part.docs.clone())?;
1394        }
1395        Ok(())
1396    }
1397
1398    /// Returns the JSON Schema of the feature's settings.
1399    ///
1400    /// The schema is an object whose description joins the descriptions given
1401    /// with each Rust type of the declaration. Its properties are the feature's
1402    /// settings keys, each with the description from its field's Rust
1403    /// documentation and its binding under `x-flm-bind`; no other property is
1404    /// allowed. The schemas of the types the keys are read into are under
1405    /// `$defs`.
1406    ///
1407    /// Every mark ([`marks`](SettingsDecl::marks)) is written on the node at
1408    /// its path, under [`MARKS_KEYWORD`] (`x-flm-marks`), as the list of the
1409    /// mark names; the default of an object combined key by key is its default
1410    /// entries ([`default_entries`](SettingsDecl::default_entries)). A mark is
1411    /// written at no other place: where the path of a mark passes through a
1412    /// definition of `$defs` that another place refers to as well, and the
1413    /// marks below the two places differ, the definition is written out in
1414    /// place along that path; otherwise the marks are written in the
1415    /// definition.
1416    ///
1417    /// For a part declared from data, each key's schema is the one its
1418    /// `properties` give, with its binding added, and the part's own `$defs`
1419    /// join those of the result; its description is the `docs` given.
1420    ///
1421    /// The schema of each entry in force ([`with_entries`](SettingsDecl::with_entries))
1422    /// stands at its place: each map on the way to it gets the property of the
1423    /// entry's name beside its `additionalProperties`, and the entry's
1424    /// property is the entry's schema, with its marks and those that this
1425    /// declaration sets on the entry's place; the entry's own `$defs` join
1426    /// those of the result, each named by the entry's path, a `.` and its own
1427    /// name.
1428    ///
1429    /// Every description is the Rust documentation turned into plain text, for
1430    /// any reader of the schema: a link is written as its words alone, without
1431    /// its target; a code block is left out, and so is everything from the
1432    /// first heading on (`# Examples`, `# Panics`). The rest is kept as written,
1433    /// including code spans in backticks.
1434    pub fn json_schema(&self) -> Value {
1435        let mut root = self.bare_schema();
1436        for entry in &self.in_force {
1437            marks::graft(&mut root, &entry.path, &entry.schema);
1438        }
1439        marks::print(&mut root, &self.marks, |path| self.default_entries(path));
1440        plain_descriptions(&mut root);
1441        root
1442    }
1443
1444    /// The JSON Schema of the feature's settings, as
1445    /// [`json_schema`](SettingsDecl::json_schema) gives it before the marks
1446    /// are written and the descriptions made plain text.
1447    fn bare_schema(&self) -> Value {
1448        let mut generator = schemars::SchemaGenerator::default();
1449        let mut properties = Map::new();
1450        for part in &self.parts {
1451            let schema = (part.schema)(&mut generator);
1452            let resolved = resolve_ref(&generator, schema.as_value());
1453            let fields = resolved.get("properties").and_then(Value::as_object);
1454            for key in &part.keys {
1455                let mut property =
1456                    fields.and_then(|fields| fields.get(key)).cloned().unwrap_or(Value::Bool(true));
1457                if let Value::Object(object) = &mut property {
1458                    object.insert("x-flm-bind".into(), Value::from(part.bind.label()));
1459                } else {
1460                    let mut object = Map::new();
1461                    object.insert("x-flm-bind".into(), Value::from(part.bind.label()));
1462                    property = Value::Object(object);
1463                }
1464                properties.insert(key.clone(), property);
1465            }
1466        }
1467        let mut root = Map::new();
1468        let docs: Vec<&str> = self.parts.iter().map(|part| part.docs.as_str()).filter(|docs| !docs.is_empty()).collect();
1469        if !docs.is_empty() {
1470            root.insert("description".into(), Value::from(docs.join("\n\n")));
1471        }
1472        root.insert("type".into(), Value::from("object"));
1473        root.insert("properties".into(), Value::Object(properties));
1474        root.insert("additionalProperties".into(), Value::Bool(false));
1475        let definitions = generator.take_definitions(true);
1476        if !definitions.is_empty() {
1477            root.insert("$defs".into(), Value::Object(definitions));
1478        }
1479        Value::Object(root)
1480    }
1481}
1482
1483impl fmt::Debug for SettingsDecl {
1484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1485        f.debug_struct("SettingsDecl")
1486            .field("feature", &self.feature)
1487            .field("keys", &self.keys().map(|key| key.name).collect::<Vec<_>>())
1488            .field("marks", &self.marks)
1489            .finish()
1490    }
1491}
1492
1493/// Returns the JSON Schema of the type `T`, written as
1494/// [`SettingsDecl::json_schema`] writes the schemas of a feature's keys: every
1495/// description is the Rust documentation of the type and its fields as plain
1496/// text, and the schemas of the types `T` refers to are under `$defs`.
1497///
1498/// Use it to describe, beside the features' settings, another part of a file
1499/// that a program reads into a type of this library (for example the parsing
1500/// configuration, [`FlmParsing`](crate::lang::FlmParsing)).
1501pub fn schema_of<T: schemars::JsonSchema>() -> Value {
1502    let mut schema = schemars::SchemaGenerator::default().into_root_schema_for::<T>().to_value();
1503    if let Value::Object(object) = &mut schema {
1504        object.remove("$schema");
1505        object.remove("title");
1506    }
1507    plain_descriptions(&mut schema);
1508    schema
1509}
1510
1511/// Writes every description of `schema` as plain text ([`plain_text`]),
1512/// leaving alone the values that are data rather than schemas.
1513fn plain_descriptions(schema: &mut Value) {
1514    match schema {
1515        Value::Object(object) => {
1516            for (keyword, value) in object.iter_mut() {
1517                match (keyword.as_str(), value) {
1518                    ("description", Value::String(text)) => *text = plain_text(text),
1519                    ("default" | "const" | "enum" | "examples", _) => {}
1520                    (keyword, _) if keyword.starts_with("x-flm-") => {}
1521                    (_, value) => plain_descriptions(value),
1522                }
1523            }
1524        }
1525        Value::Array(items) => items.iter_mut().for_each(plain_descriptions),
1526        _ => {}
1527    }
1528}
1529
1530/// Returns a Rust documentation text, written in Markdown, as plain text: see
1531/// [`SettingsDecl::json_schema`].
1532fn plain_text(doc: &str) -> String {
1533    let mut lines = Vec::new();
1534    let mut in_code_block = false;
1535    for line in doc.lines() {
1536        let trimmed = line.trim_start();
1537        if trimmed.starts_with("```") {
1538            in_code_block = !in_code_block;
1539            continue;
1540        }
1541        if in_code_block {
1542            continue;
1543        }
1544        if trimmed.starts_with('#') && trimmed.trim_start_matches('#').starts_with(' ') {
1545            break;
1546        }
1547        lines.push(line);
1548    }
1549    let mut text = String::new();
1550    for line in unlinked(&lines.join("\n")).lines() {
1551        // One blank line between paragraphs, none at either end.
1552        if line.trim().is_empty() && (text.is_empty() || text.ends_with("\n\n")) {
1553            continue;
1554        }
1555        text.push_str(line);
1556        text.push('\n');
1557    }
1558    text.trim_end().to_string()
1559}
1560
1561/// Returns `text` with every Markdown link written as its words alone:
1562/// `[words](target)`, `[words][reference]`, and `` [`code`] `` (a link to the
1563/// item the code refers to). Code spans are copied unchanged; a bracket that
1564/// opens no link is kept.
1565fn unlinked(text: &str) -> String {
1566    let chars: Vec<char> = text.chars().collect();
1567    let mut out = String::new();
1568    let mut i = 0;
1569    while i < chars.len() {
1570        if chars[i] == '`' {
1571            let end = code_span_end(&chars, i);
1572            out.extend(&chars[i..end]);
1573            i = end;
1574        } else if chars[i] == '[' {
1575            let Some(close) = closing(&chars, i, '[', ']') else {
1576                out.push('[');
1577                i += 1;
1578                continue;
1579            };
1580            let words: String = chars[i + 1..close].iter().collect();
1581            let target = match chars.get(close + 1) {
1582                Some('(') => closing(&chars, close + 1, '(', ')'),
1583                Some('[') => closing(&chars, close + 1, '[', ']'),
1584                _ if words.starts_with('`') && words.ends_with('`') => Some(close),
1585                _ => None,
1586            };
1587            match target {
1588                Some(end) => {
1589                    out.push_str(&unlinked(&words));
1590                    i = end + 1;
1591                }
1592                None => {
1593                    out.push('[');
1594                    i += 1;
1595                }
1596            }
1597        } else {
1598            out.push(chars[i]);
1599            i += 1;
1600        }
1601    }
1602    out
1603}
1604
1605/// The position just after the code span that opens at `start` (a run of
1606/// backticks, closed by the next run of the same length), or just after the
1607/// run when nothing closes it.
1608fn code_span_end(chars: &[char], start: usize) -> usize {
1609    let run = |at: usize| chars[at..].iter().take_while(|c| **c == '`').count();
1610    let length = run(start);
1611    let mut at = start + length;
1612    while at < chars.len() {
1613        if chars[at] == '`' {
1614            let found = run(at);
1615            if found == length {
1616                return at + found;
1617            }
1618            at += found;
1619        } else {
1620            at += 1;
1621        }
1622    }
1623    start + length
1624}
1625
1626/// The position of the `close` matching the `open` at `start`, code spans
1627/// and nested pairs skipped, if there is one.
1628fn closing(chars: &[char], start: usize, open: char, close: char) -> Option<usize> {
1629    let mut depth = 0;
1630    let mut at = start;
1631    while at < chars.len() {
1632        let c = chars[at];
1633        if c == '`' {
1634            at = code_span_end(chars, at);
1635            continue;
1636        }
1637        if c == open {
1638            depth += 1;
1639        } else if c == close {
1640            depth -= 1;
1641            if depth == 0 {
1642                return Some(at);
1643            }
1644        }
1645        at += 1;
1646    }
1647    None
1648}
1649
1650/// The schema that a `$ref` refers to, or the schema itself when it is not a
1651/// reference.
1652fn resolve_ref(generator: &schemars::SchemaGenerator, schema: &Value) -> Value {
1653    if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
1654        let name = reference.rsplit('/').next().unwrap_or(reference);
1655        if let Some(found) = generator.definitions().get(name) {
1656            return found.clone();
1657        }
1658    }
1659    schema.clone()
1660}
1661
1662/// The keys of a part declared from data: the names of the `properties` of
1663/// `schema`, in their order, or `None` when `schema` has no `properties` map.
1664fn schema_keys(schema: &Value) -> Option<Vec<String>> {
1665    schema.get("properties").and_then(Value::as_object).map(|properties| properties.keys().cloned().collect())
1666}
1667
1668/// The function that declares a part declared from data as the option type
1669/// `name`.
1670fn declare_named(name: Name) -> DeclareFn {
1671    Arc::new(move |b: &mut FeatureBuilder<'_>, bind: Bind, docs: String| b.options_named(name.clone(), bind, docs))
1672}
1673
1674/// The schema function of a part declared from data: the schema as given, its
1675/// `$defs` moved into the generator's definitions, where those of every part
1676/// join.
1677fn data_schema(schema: Value) -> SchemaFn {
1678    Arc::new(move |generator: &mut schemars::SchemaGenerator| {
1679        let mut schema = schema.clone();
1680        if let Some(Value::Object(definitions)) = schema.as_object_mut().and_then(|object| object.remove("$defs")) {
1681            generator.definitions_mut().extend(definitions);
1682        }
1683        schemars::Schema::try_from(schema).unwrap_or_default()
1684    })
1685}
1686
1687/// Reads `T` from `data`; the error carries the path of the offending key.
1688fn deserialize<T: DeserializeOwned>(data: Value) -> Result<T, ReadError> {
1689    serde_path_to_error::deserialize::<_, T>(data).map_err(|error| {
1690        let path = error.path().to_string();
1691        let path = if path == "." { String::new() } else { path };
1692        ReadError { path, detail: error.into_inner().to_string() }
1693    })
1694}
1695
1696/// The names of the fields `T` is read from, as its `Deserialize`
1697/// implementation declares them.
1698///
1699/// # Panics
1700///
1701/// When `T` is not read from a map of named fields.
1702fn field_names<T: DeserializeOwned>() -> Vec<String> {
1703    // The key list comes from the derivation that reads the keys, so the two
1704    // cannot disagree.
1705    let mut probe = FieldProbe { fields: None };
1706    let _ = T::deserialize(&mut probe);
1707    probe
1708        .fields
1709        .unwrap_or_else(|| panic!("`{}` is not read from named fields", std::any::type_name::<T>()))
1710        .iter()
1711        .map(|name| (*name).to_string())
1712        .collect()
1713}
1714
1715/// A deserializer that reads nothing and records the field names that a struct's
1716/// `Deserialize` implementation passes to it.
1717struct FieldProbe {
1718    fields: Option<&'static [&'static str]>,
1719}
1720
1721/// The only error of [`FieldProbe`].
1722#[derive(Debug)]
1723struct ProbeError;
1724
1725impl fmt::Display for ProbeError {
1726    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1727        f.write_str("field probe")
1728    }
1729}
1730
1731impl std::error::Error for ProbeError {}
1732
1733impl serde::de::Error for ProbeError {
1734    fn custom<T: fmt::Display>(_msg: T) -> ProbeError {
1735        ProbeError
1736    }
1737}
1738
1739impl<'de> serde::Deserializer<'de> for &mut FieldProbe {
1740    type Error = ProbeError;
1741
1742    fn deserialize_any<V: serde::de::Visitor<'de>>(self, _visitor: V) -> Result<V::Value, ProbeError> {
1743        Err(ProbeError)
1744    }
1745
1746    fn deserialize_struct<V: serde::de::Visitor<'de>>(
1747        self,
1748        _name: &'static str,
1749        fields: &'static [&'static str],
1750        _visitor: V,
1751    ) -> Result<V::Value, ProbeError> {
1752        self.fields = Some(fields);
1753        Err(ProbeError)
1754    }
1755
1756    serde::forward_to_deserialize_any! {
1757        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1758        bytes byte_buf option unit unit_struct newtype_struct seq tuple
1759        tuple_struct map enum identifier ignored_any
1760    }
1761}
1762
1763/// A feature's settings as read from data by [`SettingsDecl::read`]: its
1764/// configuration, and the option values to set on a document and on a render
1765/// request.
1766///
1767/// A host passes the configuration to the feature's package through
1768/// [`PackageSettings`], sets the document option values on the document and the
1769/// render option values on the plan request.
1770#[derive(Clone)]
1771pub struct FeatureSettings {
1772    feature: FeatureName,
1773    config: Option<Arc<dyn Any + Send + Sync>>,
1774    document: OptionValues,
1775    render: OptionValues,
1776}
1777
1778impl FeatureSettings {
1779    /// The name of the feature whose settings these are.
1780    pub fn feature(&self) -> &FeatureName {
1781        &self.feature
1782    }
1783
1784    /// The feature's configuration, or `None` when the feature declares no
1785    /// configuration of type `C`. The configuration is the type's default when
1786    /// none of its keys was written.
1787    pub fn config<C: Any>(&self) -> Option<&C> {
1788        self.config.as_deref().and_then(|config| config.downcast_ref::<C>())
1789    }
1790
1791    /// The option values a host sets on the document
1792    /// ([`Doc::with_options`](crate::model::doc::Doc::with_options)): those of
1793    /// every option type bound to the document ([`Bind::Document`]) or to either
1794    /// site ([`Bind::Either`]) at least one of whose keys was written.
1795    pub fn document_options(&self) -> &OptionValues {
1796        &self.document
1797    }
1798
1799    /// The option values a host sets on the render request
1800    /// ([`PlanRequest::render_options`](crate::core::plan::PlanRequest#structfield.render_options)):
1801    /// those of every option type bound to the render request
1802    /// ([`Bind::Render`]) at least one of whose keys was written.
1803    pub fn render_options(&self) -> &OptionValues {
1804        &self.render
1805    }
1806}
1807
1808impl fmt::Debug for FeatureSettings {
1809    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1810        f.debug_struct("FeatureSettings")
1811            .field("feature", &self.feature)
1812            .field("config", &self.config.is_some())
1813            .field("document", &self.document)
1814            .field("render", &self.render)
1815            .finish()
1816    }
1817}
1818
1819/// The kind of problem a [`SettingsError`] reports.
1820#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1821pub enum SettingsErrorKind {
1822    /// The feature declares no settings key of that name.
1823    UnknownKey,
1824    /// The value does not have the shape its key requires, or the feature's
1825    /// conversion or reader of its configuration refuses it
1826    /// ([`SettingsDecl::config_from`], [`SettingsDecl::config_data_read`]).
1827    InvalidValue,
1828    /// A declaration of settings from data contradicts itself or is malformed
1829    /// ([`SettingsDecl::config_data`], [`SettingsDecl::config_data_read`], [`SettingsDecl::options_data`]):
1830    /// no data was read.
1831    InvalidDeclaration,
1832}
1833
1834/// A problem found while reading a feature's settings from data: the key, by its
1835/// path from the feature's name, and what is wrong with its value; or a problem
1836/// of a declaration of settings from data.
1837///
1838/// [`SettingsDecl::read`] returns these, and so do the constructors of the parts
1839/// declared from data ([`SettingsDecl::config_data`] and the others). The `Display` text is
1840/// [`detail`](SettingsError::detail); it does not say where the value was
1841/// written, which the host adds when it reports the error.
1842#[derive(Debug, Clone, PartialEq, Eq)]
1843pub struct SettingsError {
1844    /// The key's path from the feature's name, its segments separated by `.`
1845    /// (`html.heading_tags.section`); the feature's name alone when the
1846    /// problem concerns the settings as a whole.
1847    pub path: String,
1848    /// The kind of problem.
1849    pub kind: SettingsErrorKind,
1850    /// The problem, as a message for a person.
1851    pub detail: String,
1852}
1853
1854impl fmt::Display for SettingsError {
1855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1856        f.write_str(&self.detail)
1857    }
1858}
1859
1860impl std::error::Error for SettingsError {}
1861
1862/// The settings a package is built from: the settings of each of its features
1863/// that takes some, and the features switched off.
1864///
1865/// A package is a named bundle of features together with the packages it builds
1866/// on, ready to register ([`PackageEntry`](crate::core::registry::PackageEntry)); a
1867/// [`PackageFactory`](crate::core::registry::PackageFactory) builds it from these
1868/// settings with
1869/// [`PackageFactory::build`](crate::core::registry::PackageFactory::build). A
1870/// host reads each feature's data with the feature's [`SettingsDecl`] and
1871/// inserts the result here. The package's build function decides what a
1872/// feature with no settings here becomes, and leaves every switched-off feature
1873/// out ([`PackageFactory::new`](crate::core::registry::PackageFactory::new));
1874/// the standard features are built from their defaults where the settings give none.
1875#[derive(Debug, Clone, Default)]
1876pub struct PackageSettings {
1877    features: BTreeMap<FeatureName, FeatureSettings>,
1878    off: BTreeSet<FeatureName>,
1879}
1880
1881impl PackageSettings {
1882    /// Creates package settings with no feature settings and no feature switched
1883    /// off.
1884    pub fn new() -> PackageSettings {
1885        PackageSettings::default()
1886    }
1887
1888    /// Adds one feature's settings, replacing any settings of the same feature
1889    /// already added, and returns `&mut self` for chaining.
1890    pub fn insert(&mut self, settings: FeatureSettings) -> &mut PackageSettings {
1891        self.features.insert(settings.feature.clone(), settings);
1892        self
1893    }
1894
1895    /// Switches the feature named `feature` off, and returns `&mut self` for
1896    /// chaining. The package's build function leaves a switched-off feature out
1897    /// of the package
1898    /// ([`PackageFactory::new`](crate::core::registry::PackageFactory::new)).
1899    pub fn switch_off(&mut self, feature: impl Into<FeatureName>) -> &mut PackageSettings {
1900        self.off.insert(feature.into());
1901        self
1902    }
1903
1904    /// Whether the feature named `feature` is switched off.
1905    pub fn is_off(&self, feature: &str) -> bool {
1906        self.off.contains(feature)
1907    }
1908
1909    /// The settings of the feature named `feature`, or `None` when none were
1910    /// added. A reading through the cascade
1911    /// ([`Cascade::read`](cascade::Cascade::read)) adds the settings of every
1912    /// feature in use that declares some and is not switched off, whether or
1913    /// not anything is written under it.
1914    pub fn feature(&self, feature: &str) -> Option<&FeatureSettings> {
1915        self.features.get(feature)
1916    }
1917
1918    /// The configuration of type `C` of the feature named `feature`, or `None`
1919    /// when no settings were added for that feature or they hold no
1920    /// configuration of that type. After a reading through the cascade
1921    /// ([`Cascade::read`](cascade::Cascade::read)), it is `Some` for every
1922    /// feature in use, not switched off, that declares a configuration of type
1923    /// `C`: the configuration read from the settings written under the
1924    /// feature, or from the empty map when nothing is written under it.
1925    pub fn config<C: Any>(&self, feature: &str) -> Option<&C> {
1926        self.feature(feature).and_then(FeatureSettings::config::<C>)
1927    }
1928}