Skip to main content

flm_core/stdlib/features/quote/
config.rs

1//! The configuration of the `quote` feature: which quote environments exist,
2//! which quotation-section commands each one accepts, and which kind of
3//! quotation section its bare content (content written outside those
4//! commands) is read as. The configuration is the value the feature is
5//! constructed from, fixed when the registry is built
6//! ([configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::hash::{Hash, Hasher};
10
11use crate::stdlib::backends::pres::LIST_RESERVED_KINDS;
12
13/// The kind of one quotation section of a quote environment, and the
14/// quotation-section command that writes it.
15///
16/// - [`Text`](QuoteSection::Text) — a quoted passage, one paragraph:
17///   `\text{…}`.
18/// - [`Lines`](QuoteSection::Lines) — content set line by line, each `\\`
19///   ending a line and each `\indent` at the start of a line indenting it by
20///   one tab: `\lines{…}`.
21/// - [`Attributed`](QuoteSection::Attributed) — the attribution, an author or
22///   a source: `\attributed{…}`.
23/// - [`Block`](QuoteSection::Block) — ordinary paragraphs and blocks set as a
24///   quotation: `\block{…}`.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Deserialize, serde::Serialize)]
26#[derive(schemars::JsonSchema)]
27#[serde(rename_all = "kebab-case")]
28pub enum QuoteSection {
29    /// A quoted passage, one paragraph, written `\text{…}`.
30    Text,
31    /// Lines set as written, written `\lines{…}`.
32    Lines,
33    /// The attribution, written `\attributed{…}`.
34    Attributed,
35    /// Paragraphs and blocks, written `\block{…}`.
36    Block,
37}
38
39impl QuoteSection {
40    /// Every section kind, in declaration order.
41    pub const ALL: [QuoteSection; 4] =
42        [QuoteSection::Text, QuoteSection::Lines, QuoteSection::Attributed, QuoteSection::Block];
43
44    /// Returns the kind's stable name, which is also the name of the
45    /// quotation-section command that writes it: `text`, `lines`,
46    /// `attributed` or `block`. Settings write a kind by this name.
47    pub fn as_str(self) -> &'static str {
48        match self {
49            QuoteSection::Text => "text",
50            QuoteSection::Lines => "lines",
51            QuoteSection::Attributed => "attributed",
52            QuoteSection::Block => "block",
53        }
54    }
55
56    /// Returns the kind whose stable name ([`as_str`](QuoteSection::as_str))
57    /// is `name`, or `None` when no kind has that name.
58    pub fn parse(name: &str) -> Option<QuoteSection> {
59        QuoteSection::ALL.into_iter().find(|section| section.as_str() == name)
60    }
61
62    /// Returns the role of the block a quotation section of this kind is
63    /// staged as:
64    /// [`TEXT_ROLE`](super::TEXT_ROLE), [`LINES_ROLE`](super::LINES_ROLE),
65    /// [`ATTRIBUTED_ROLE`](super::ATTRIBUTED_ROLE) or
66    /// [`BLOCK_ROLE`](super::BLOCK_ROLE).
67    pub fn role(self) -> &'static str {
68        match self {
69            QuoteSection::Text => super::TEXT_ROLE,
70            QuoteSection::Lines => super::LINES_ROLE,
71            QuoteSection::Attributed => super::ATTRIBUTED_ROLE,
72            QuoteSection::Block => super::BLOCK_ROLE,
73        }
74    }
75
76    /// Returns whether a quotation section of this kind holds inline content
77    /// (a passage, lines or an attribution) rather than paragraphs and blocks.
78    pub fn is_inline(self) -> bool {
79        !matches!(self, QuoteSection::Block)
80    }
81}
82
83/// One quote environment: the quotation-section commands its body accepts,
84/// and the kind of quotation section its **bare content** (content written in
85/// the body outside any quotation-section command) is read as.
86///
87/// An environment accepts exactly the quotation-section commands of
88/// [`sections`](QuoteEnvironment::sections), a set: the other commands are
89/// not declared in its body, and the order of the set has no meaning (an
90/// author writes the quotation sections in any order). Where
91/// [`bare`](QuoteEnvironment::bare) holds a kind, each run of bare content is
92/// read as one quotation section of that kind; where it holds none, bare
93/// content is an error (the condition
94/// [`BareContent`](super::BareContent)). An environment must accept a
95/// quotation-section command or read bare content, or
96/// [`QuoteConfig::validate`] refuses the configuration when the registry is
97/// built.
98///
99/// The bare-content kind also decides how the body is laid out
100/// ([`holds_blocks`](QuoteEnvironment::holds_blocks)): as paragraphs and
101/// blocks when it is [`Block`](QuoteSection::Block) or when there is none, so
102/// that each quotation-section command is a block of its own; as inline
103/// content when it is [`Text`](QuoteSection::Text),
104/// [`Lines`](QuoteSection::Lines) or [`Attributed`](QuoteSection::Attributed),
105/// so that the quotation sections and the bare content form one run.
106///
107/// # Examples
108///
109/// ```
110/// use flm_core::stdlib::features::quote::{QuoteEnvironment, QuoteSection};
111///
112/// // A quotation of one passage and its attribution, nothing else.
113/// let epigraph = QuoteEnvironment::new([QuoteSection::Text, QuoteSection::Attributed]);
114/// assert!(epigraph.enables(QuoteSection::Attributed));
115/// assert_eq!(epigraph.bare, None);
116///
117/// // An environment whose whole content is lines, as `address` is.
118/// let verse = QuoteEnvironment::new([]).bare(QuoteSection::Lines);
119/// assert!(!verse.holds_blocks());
120/// ```
121#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
122#[derive(schemars::JsonSchema)]
123#[serde(deny_unknown_fields)]
124pub struct QuoteEnvironment {
125    /// The quotation-section commands the body accepts.
126    pub sections: BTreeSet<QuoteSection>,
127    /// The kind of quotation section bare content is read as; `None` makes
128    /// bare content an error.
129    pub bare: Option<QuoteSection>,
130}
131
132impl QuoteEnvironment {
133    /// Returns an environment that accepts the quotation-section commands of
134    /// `sections` (a kind given twice is accepted once) and whose bare content
135    /// is an error. [`bare`](QuoteEnvironment::bare()) sets the kind bare
136    /// content is read as.
137    pub fn new(sections: impl IntoIterator<Item = QuoteSection>) -> QuoteEnvironment {
138        QuoteEnvironment { sections: sections.into_iter().collect(), bare: None }
139    }
140
141    /// Builder: sets the kind of quotation section bare content is read as to
142    /// `kind`, and returns the environment.
143    pub fn bare(mut self, kind: QuoteSection) -> QuoteEnvironment {
144        self.bare = Some(kind);
145        self
146    }
147
148    /// Returns whether the body accepts the quotation-section command of the
149    /// kind `section`.
150    pub fn enables(&self, section: QuoteSection) -> bool {
151        self.sections.contains(&section)
152    }
153
154    /// Returns whether the body is laid out as paragraphs and blocks: true
155    /// when its bare content is read as a [`Block`](QuoteSection::Block)
156    /// section or is an error. A body whose bare content is read as a passage,
157    /// lines or an attribution is laid out as inline content.
158    pub fn holds_blocks(&self) -> bool {
159        self.bare.is_none_or(|kind| !kind.is_inline())
160    }
161}
162
163/// The configuration of the [`Quote`](super::Quote) feature: the quote
164/// environments, each environment's name mapped to its [`QuoteEnvironment`].
165///
166/// The default ([`QuoteConfig::new`]) declares three environments:
167///
168/// | environment | quotation-section commands | bare content read as |
169/// |---|---|---|
170/// | `quote` | `\text`, `\lines`, `\attributed`, `\block` | an error |
171/// | `blockquote` | none | one block section |
172/// | `address` | none | one lines section |
173///
174/// A host declares others, or changes these, through the same type:
175///
176/// ```
177/// use flm_core::stdlib::features::quote::{QuoteConfig, QuoteEnvironment, QuoteSection};
178///
179/// let config = QuoteConfig::new()
180///     .environment("epigraph", QuoteEnvironment::new([QuoteSection::Text, QuoteSection::Attributed]))
181///     .environment("aside", QuoteEnvironment::new([]).bare(QuoteSection::Block));
182/// assert_eq!(config.environments.len(), 5);
183/// assert!(config.validate().is_ok());
184/// ```
185///
186/// The value is what [`Quote::new`](super::Quote::new) takes; a host using
187/// the standard features passes it with
188/// [`StdlibConfig::quote`](crate::stdlib::StdlibConfig::quote). The
189/// configuration is fixed when the registry is built, before any document is
190/// parsed
191/// ([configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
192/// because the environments and their quotation-section commands are part of
193/// the language. The feature therefore feeds
194/// [`digest_bytes`](QuoteConfig::digest_bytes) into the [registry
195/// digest](crate::model::digest), the number that changes whenever something
196/// about the registry that can change what processing produces changes
197/// ([`FeatureBuilder::digest_input`](crate::core::registry::FeatureBuilder::digest_input)).
198///
199/// The feature checks the configuration when the registry is built
200/// ([`validate`](QuoteConfig::validate)), and the registry build fails, with
201/// a message that identifies the environment, on any of these: a name that
202/// is empty or holds whitespace, a brace, a backslash or `%`; a name equal to
203/// one of the kind tokens a presentation list reserves ([`LIST_RESERVED_KINDS`]), since an
204/// environment's name becomes the kind token of the block it is staged as;
205/// and an environment that accepts no quotation-section command and reads no
206/// bare content. A name that another feature also declares, such as `itemize`
207/// or `theorem`, makes the registry build fail as any two declarations of one
208/// name do.
209///
210/// The configuration refers to no backend, HTML tag or stylesheet: the
211/// lowering rules and stylesheets of each backend decide how a quotation is
212/// presented.
213#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
214#[derive(schemars::JsonSchema)]
215#[serde(default, deny_unknown_fields)]
216pub struct QuoteConfig {
217    /// The quote environments, by name.
218    pub environments: BTreeMap<String, QuoteEnvironment>,
219}
220
221impl Default for QuoteConfig {
222    fn default() -> QuoteConfig {
223        QuoteConfig::new()
224    }
225}
226
227impl QuoteConfig {
228    /// Returns the default configuration: the environments `quote`,
229    /// `blockquote` and `address` (see the table above).
230    // The three environments are the Python product's defaults.
231    pub fn new() -> QuoteConfig {
232        QuoteConfig::empty()
233            .environment("quote", QuoteEnvironment::new(QuoteSection::ALL))
234            .environment("blockquote", QuoteEnvironment::new([]).bare(QuoteSection::Block))
235            .environment("address", QuoteEnvironment::new([]).bare(QuoteSection::Lines))
236    }
237
238    /// Returns a configuration that declares no quote environment. The
239    /// feature then registers no quote environment, no quotation-section
240    /// command and no lowering rule.
241    pub fn empty() -> QuoteConfig {
242        QuoteConfig { environments: BTreeMap::new() }
243    }
244
245    /// Builder: declares the environment `name` as `environment`, replacing
246    /// any environment of that name, and returns the configuration.
247    pub fn environment(mut self, name: impl Into<String>, environment: QuoteEnvironment) -> QuoteConfig {
248        self.environments.insert(name.into(), environment);
249        self
250    }
251
252    /// Builder: removes the environment `name`, if there is one, and returns
253    /// the configuration.
254    pub fn without_environment(mut self, name: &str) -> QuoteConfig {
255        self.environments.remove(name);
256        self
257    }
258
259    /// Returns the environment `name`, or `None` when none is declared.
260    pub fn get(&self, name: &str) -> Option<&QuoteEnvironment> {
261        self.environments.get(name)
262    }
263
264    /// Checks the configuration, as the feature does when it registers.
265    ///
266    /// # Errors
267    ///
268    /// Returns a sentence that states the first problem found: an environment
269    /// name that is empty or holds whitespace, a brace, a backslash or the
270    /// comment character `%`; a name equal to one of the kind tokens a
271    /// presentation list reserves ([`LIST_RESERVED_KINDS`]); an environment
272    /// that accepts no quotation-section command and reads no bare content.
273    pub fn validate(&self) -> Result<(), String> {
274        for (name, environment) in &self.environments {
275            if name.is_empty()
276                || name.chars().any(|ch| ch.is_whitespace() || matches!(ch, '{' | '}' | '\\' | '%'))
277            {
278                return Err(format!(
279                    "the quote environment name `{name}` must not be empty or contain \
280                     whitespace, a brace, a backslash or `%`"
281                ));
282            }
283            if LIST_RESERVED_KINDS.contains(&name.as_str()) {
284                let reserved = LIST_RESERVED_KINDS.iter().map(|kind| format!("`{kind}`"));
285                return Err(format!(
286                    "the quote environment name `{name}` is reserved: a quote environment must \
287                     not be named {}",
288                    english_list(reserved, "or")
289                ));
290            }
291            if environment.sections.is_empty() && environment.bare.is_none() {
292                let sections: Vec<String> = QuoteSection::ALL
293                    .iter()
294                    .map(|section| format!("`\\{}`", section.as_str()))
295                    .collect();
296                return Err(format!(
297                    "the quote environment `{name}` must accept at least one of {}, or content \
298                     outside them",
299                    sections.join(", ")
300                ));
301            }
302        }
303        Ok(())
304    }
305
306    /// Returns the canonical byte form of the configuration: what the feature
307    /// feeds into the registry digest, and what `Hash` hashes.
308    ///
309    /// The bytes are: the number of environments, then each environment in
310    /// the order of the names: its name preceded by its length, the number of
311    /// its quotation-section commands and the commands in the order of
312    /// [`QuoteSection`], and its bare-content kind (0 for none, otherwise one
313    /// more than the kind's position in that order, counted from zero). Two
314    /// configurations therefore have the same byte form exactly when they are equal.
315    pub fn digest_bytes(&self) -> Vec<u8> {
316        // The fields are taken apart by name, so that a field added to a type
317        // and not written here fails to compile.
318        let QuoteConfig { environments } = self;
319        let mut out = Vec::new();
320        push_len(&mut out, environments.len());
321        for (name, environment) in environments {
322            let QuoteEnvironment { sections, bare } = environment;
323            push_len(&mut out, name.len());
324            out.extend_from_slice(name.as_bytes());
325            push_len(&mut out, sections.len());
326            out.extend(sections.iter().map(|section| section_byte(*section)));
327            out.push(bare.map_or(0, |kind| section_byte(kind) + 1));
328        }
329        out
330    }
331}
332
333/// Joins `items` as an English list, with no serial comma: `a`, `a or b`,
334/// `a, b or c` (with `conjunction` `"or"`).
335pub(super) fn english_list(items: impl IntoIterator<Item = String>, conjunction: &str) -> String {
336    let mut items: Vec<String> = items.into_iter().collect();
337    let last = items.pop().unwrap_or_default();
338    if items.is_empty() { last } else { format!("{} {conjunction} {last}", items.join(", ")) }
339}
340
341/// A section kind as one byte: its position in [`QuoteSection::ALL`].
342fn section_byte(section: QuoteSection) -> u8 {
343    match section {
344        QuoteSection::Text => 0,
345        QuoteSection::Lines => 1,
346        QuoteSection::Attributed => 2,
347        QuoteSection::Block => 3,
348    }
349}
350
351/// Writes a count as eight little-endian bytes.
352fn push_len(out: &mut Vec<u8>, len: usize) {
353    out.extend_from_slice(&(len as u64).to_le_bytes());
354}
355
356impl Hash for QuoteConfig {
357    fn hash<H: Hasher>(&self, state: &mut H) {
358        state.write(&self.digest_bytes());
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn the_shipped_environments_are_the_three_of_the_python_product() {
368        let config = QuoteConfig::new();
369        let names: Vec<&str> = config.environments.keys().map(String::as_str).collect();
370        assert_eq!(names, ["address", "blockquote", "quote"]);
371        let quote = config.get("quote").expect("shipped");
372        assert_eq!(quote.sections, BTreeSet::from(QuoteSection::ALL));
373        assert_eq!(quote.bare, None);
374        assert!(quote.holds_blocks());
375        let blockquote = config.get("blockquote").expect("shipped");
376        assert!(blockquote.sections.is_empty());
377        assert_eq!(blockquote.bare, Some(QuoteSection::Block));
378        assert!(blockquote.holds_blocks());
379        let address = config.get("address").expect("shipped");
380        assert!(address.sections.is_empty());
381        assert_eq!(address.bare, Some(QuoteSection::Lines));
382        assert!(!address.holds_blocks());
383        assert_eq!(config.validate(), Ok(()));
384    }
385
386    #[test]
387    fn a_section_kind_is_named_and_parsed_as_its_command() {
388        for section in QuoteSection::ALL {
389            assert_eq!(QuoteSection::parse(section.as_str()), Some(section));
390            assert!(section.role().ends_with(section.as_str()));
391        }
392        assert_eq!(QuoteSection::parse("quote"), None);
393    }
394
395    #[test]
396    fn an_environment_admitting_nothing_or_misnamed_is_refused() {
397        let nothing = QuoteConfig::empty().environment("empty", QuoteEnvironment::new([]));
398        assert!(nothing.validate().is_err());
399        for reserved in LIST_RESERVED_KINDS {
400            let config = QuoteConfig::empty().environment(reserved, QuoteEnvironment::new(QuoteSection::ALL));
401            assert!(config.validate().is_err(), "{reserved}");
402        }
403        let spaced = QuoteConfig::empty().environment("my quote", QuoteEnvironment::new(QuoteSection::ALL));
404        assert!(spaced.validate().is_err());
405    }
406
407    #[test]
408    fn the_digest_bytes_change_with_every_field() {
409        let base = QuoteConfig::new();
410        let changed = [
411            base.clone().environment("aside", QuoteEnvironment::new([]).bare(QuoteSection::Block)),
412            base.clone().without_environment("address"),
413            base.clone().environment("quote", QuoteEnvironment::new([QuoteSection::Text])),
414            base.clone().environment("quote", QuoteEnvironment::new(QuoteSection::ALL).bare(QuoteSection::Text)),
415            base.clone().environment("address", QuoteEnvironment::new([]).bare(QuoteSection::Text)),
416        ];
417        for other in &changed {
418            assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
419        }
420        assert_eq!(QuoteConfig::new().digest_bytes(), base.digest_bytes());
421    }
422
423    #[test]
424    fn the_accepted_sections_are_a_set() {
425        // Named in another order, or twice, the sections are the same set:
426        // the configurations are equal and digest alike.
427        let listed = QuoteConfig::empty().environment(
428            "quote",
429            QuoteEnvironment::new([QuoteSection::Lines, QuoteSection::Text, QuoteSection::Text]),
430        );
431        let canonical = QuoteConfig::empty()
432            .environment("quote", QuoteEnvironment::new([QuoteSection::Text, QuoteSection::Lines]));
433        assert_eq!(listed, canonical);
434        assert_eq!(listed.digest_bytes(), canonical.digest_bytes());
435        assert_eq!(listed.validate(), Ok(()));
436    }
437}