Skip to main content

flm_core/stdlib/features/quote/
elements.rs

1//! The element declarations of the `quote` feature: one environment per
2//! configured quote environment; the four quotation-section commands, in one
3//! scoped package per environment that accepts any; and the two field macros
4//! of a lines section, `\\` and `\indent` (macros that write nothing and that
5//! the lowering rules read in place;
6//! [fields](crate::guide::concepts_overview#fields-data-a-construct-reads)),
7//! in the scoped package [`LINES_PACKAGE`](super::LINES_PACKAGE). The module also holds the test of
8//! section position ([`section_position`]), which the block role of a
9//! quotation-section command and the lowering rules of a quotation share.
10
11use std::sync::Arc;
12
13use techy::core::node::NodeRef;
14
15use crate::lang::{Flm, FlmGroupType};
16use crate::lang::mint::{
17    ArgDef, ArgLayout, BodyDef, BodyLayout, ElementDef, ScopedPackageDef, SyntaxDef, field_element,
18};
19use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
20use crate::model::element::{ElementSpec, element_value};
21use crate::model::names::{FeatureName, Name};
22use crate::stdlib::backends::lowering::rules::owning_callable;
23
24use super::config::{QuoteEnvironment, QuoteSection};
25use super::{
26    CONTENT_ARG, INDENT_COMMAND, LINEBREAK_COMMAND, LINES_PACKAGE, QUOTE, SECTION,
27    sections_package,
28};
29
30/// The data that each element value of [`QUOTE`] carries: which quote
31/// environment the value is, and what the configuration declares about it.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct QuoteElement {
34    /// The environment's name, which is also the kind token of the block a
35    /// quotation of this environment is staged as.
36    pub name: String,
37    /// What the configuration declares about the environment.
38    pub environment: QuoteEnvironment,
39}
40
41/// The data that each element value of [`SECTION`] carries: which
42/// quotation-section command the value is.
43///
44/// It also gives the command's block role ([`BlockRoleAspect`]), decided per
45/// occurrence. A quotation-section command in *section position*, written
46/// directly in the body of a quote environment that accepts it, is a block
47/// where that body is laid out as paragraphs and blocks, so that it is a
48/// block of its own between the others. Anywhere else it is inline content:
49/// in a body laid out as inline content, whose quotation sections and bare
50/// content form one run, and wherever it opens no quotation section.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct SectionElement {
53    /// The kind of quotation section the command writes.
54    pub section: QuoteSection,
55}
56
57impl BlockRoleAspect for SectionElement {
58    fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
59        match section_position(node) {
60            Some(position) if position.quote.environment.holds_blocks() => BlockRole::Block,
61            _ => BlockRole::DEFAULT,
62        }
63    }
64}
65
66/// A quotation-section command in section position ([`section_position`]):
67/// the kind of quotation section it opens, and the quotation in whose body it
68/// is written.
69#[derive(Debug, Clone, Copy)]
70pub(super) struct SectionPosition<'t> {
71    /// The kind of quotation section the command opens.
72    pub(super) section: QuoteSection,
73    /// The quotation in whose body the command is written.
74    pub(super) quote: &'t QuoteElement,
75}
76
77/// Returns the section position of `node`, or `None` when `node` is not in
78/// **section position**: a quotation-section command written as a direct
79/// child of the body of a quote environment that accepts the command.
80///
81/// This predicate decides both the command's block role ([`SectionElement`])
82/// and which children of a body the lowering rules of a quotation stage as
83/// quotation sections, so that the two always agree. It reads the tree each
84/// time; nothing is stored.
85pub(super) fn section_position<'t>(node: &NodeRef<'t, Flm>) -> Option<SectionPosition<'t>> {
86    let section = element_value::<SectionElement>(node)?.section;
87    let quote = quote_of_body(node)?;
88    quote.environment.enables(section).then_some(SectionPosition { section, quote })
89}
90
91/// Returns the quotation in whose body `node` is written as a direct child,
92/// if any.
93fn quote_of_body<'t>(node: &NodeRef<'t, Flm>) -> Option<&'t QuoteElement> {
94    // A quote environment takes no argument: whatever it owns is its body.
95    owning_callable(node).and_then(|owner| element_value::<QuoteElement>(&owner))
96}
97
98/// Returns whether `node` is written directly in a quote environment's body:
99/// as a direct child of the body, or of a paragraph that the block-structure
100/// pass built directly in the body.
101pub(super) fn is_in_quote_body(node: &NodeRef<'_, Flm>) -> bool {
102    let place = match node.parent() {
103        Some(parent) if parent.group_type() == Some(FlmGroupType::Paragraph) => parent,
104        _ => *node,
105    };
106    quote_of_body(&place).is_some()
107}
108
109/// The element value of the quote environment `name`: a block, carrying the
110/// environment.
111fn quote_element(name: &str, environment: &QuoteEnvironment) -> Arc<ElementSpec> {
112    Arc::new(
113        ElementSpec::new(QUOTE)
114            .docs(format!("`{name}`: a quote environment, a quotation set apart from the running text."))
115            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
116            .with_value(Arc::new(QuoteElement {
117                name: name.to_string(),
118                environment: environment.clone(),
119            })),
120    )
121}
122
123/// Returns the declaration of the quote environment `name`, owned by
124/// `owner`: no argument, and a body laid out as paragraphs and blocks or as
125/// inline content according to the kind its bare content is read as
126/// ([`QuoteEnvironment::holds_blocks`]). The body refers to the scoped package
127/// of its quotation-section commands where it accepts at least one, and to
128/// the lines package where its bare content is read as lines. Text mode
129/// only.
130pub(super) fn environment_def(
131    owner: &FeatureName,
132    name: &str,
133    environment: &QuoteEnvironment,
134) -> ElementDef {
135    let layout = if environment.holds_blocks() { BodyLayout::Blocks } else { BodyLayout::Inline };
136    let mut body = BodyDef::new().layout(layout);
137    if !environment.sections.is_empty() {
138        body = body.scoped(sections_package(name));
139    }
140    if environment.bare == Some(QuoteSection::Lines) {
141        body = body.scoped(LINES_PACKAGE);
142    }
143    let commands: Vec<String> =
144        environment.sections.iter().map(|section| format!("`\\{}`", section.as_str())).collect();
145    let docs = match (commands.is_empty(), environment.bare) {
146        (false, _) => format!(
147            "Writes a quotation set apart from the running text, whose quotation sections are \
148             written with {}.",
149            commands.join(", ")
150        ),
151        (true, Some(kind)) => format!(
152            "Writes a quotation set apart from the running text, whose content is one {} section.",
153            kind.as_str()
154        ),
155        (true, None) => String::from("Writes a quotation set apart from the running text."),
156    };
157    ElementDef::new(
158        owner.clone(),
159        [name],
160        SyntaxDef::Environment { args: Vec::new(), body },
161        quote_element(name, environment),
162    )
163    .docs(docs)
164}
165
166/// Returns the element value of the quotation-section command of the kind
167/// `section`, whose block role is decided per occurrence
168/// ([`SectionElement`]).
169fn section_element(section: QuoteSection) -> Arc<ElementSpec> {
170    let value = Arc::new(SectionElement { section });
171    Arc::new(
172        ElementSpec::new(SECTION)
173            .docs(format!("`\\{}{{…}}`: a {} section of a quotation.", section.as_str(), section.as_str()))
174            .with::<dyn BlockRoleAspect>(Arc::clone(&value) as Arc<dyn BlockRoleAspect>)
175            .with_value(value),
176    )
177}
178
179/// Returns the declaration of the quotation-section command of the kind
180/// `section`, owned by `owner`: one mandatory argument, [`CONTENT_ARG`],
181/// laid out as inline content for a passage, lines and an attribution, and
182/// as inline content or as paragraphs and blocks, according to its content,
183/// for a block section; the argument of a lines section refers to the lines
184/// package. Text mode only, so that `\text{…}` inside mathematics is
185/// mathematics' own text command.
186fn section_def(owner: &FeatureName, section: QuoteSection, element: &Arc<ElementSpec>) -> ElementDef {
187    let mut content = ArgDef::mandatory(CONTENT_ARG);
188    let docs = match section {
189        QuoteSection::Text => "The quoted passage, one paragraph.",
190        QuoteSection::Lines => {
191            content = content.scoped(LINES_PACKAGE);
192            "The lines, each ended by `\\\\`; `\\indent` at the start of a line indents it by a \
193             tab."
194        }
195        QuoteSection::Attributed => "The attribution: an author, a source.",
196        QuoteSection::Block => {
197            content = content.layout(ArgLayout::InlineOrBlocks);
198            "Paragraphs and blocks; content written on one line is one paragraph."
199        }
200    };
201    let name = section.as_str();
202    ElementDef::new(
203        owner.clone(),
204        [name],
205        SyntaxDef::Macro { args: vec![content.docs(docs)] },
206        Arc::clone(element),
207    )
208    .docs(match section {
209        QuoteSection::Text => "Writes a quoted passage, a text section of the quotation around it.",
210        QuoteSection::Lines => "Writes a lines section of the quotation around it.",
211        QuoteSection::Attributed => "Writes the attribution of the quotation around it.",
212        QuoteSection::Block => "Writes a block section of the quotation around it.",
213    })
214}
215
216/// Returns the scoped packages of the quotation-section commands, declared by
217/// `owner`: one per environment of `environments` that accepts at least one
218/// command, whose name [`sections_package`] returns, holding exactly the commands
219/// that environment accepts.
220///
221/// A quotation-section command is one element value of [`SECTION`], however
222/// many packages hold it: two environments that accept `\text` declare the
223/// same element value under the same name in two packages. The two
224/// declarations never clash, because a scoped package is available only
225/// inside the bodies and arguments whose declarations refer to it.
226pub(super) fn sections_packages<'c>(
227    owner: &FeatureName,
228    environments: impl IntoIterator<Item = (&'c String, &'c QuoteEnvironment)>,
229) -> Vec<ScopedPackageDef> {
230    let elements: Vec<(QuoteSection, Arc<ElementSpec>)> =
231        QuoteSection::ALL.into_iter().map(|section| (section, section_element(section))).collect();
232    environments
233        .into_iter()
234        .filter(|(_, environment)| !environment.sections.is_empty())
235        .map(|(name, environment)| {
236            let defs = environment
237                .sections
238                .iter()
239                .filter_map(|section| elements.iter().find(|(kind, _)| kind == section))
240                .map(|(section, element)| section_def(owner, *section, element))
241                .collect();
242            ScopedPackageDef {
243                owner: owner.clone(),
244                name: Name::from(sections_package(name)),
245                elements: defs,
246                docs: format!(
247                    "The quotation-section commands available inside the body of the quote \
248                     environment `{name}`."
249                ),
250            }
251        })
252        .collect()
253}
254
255/// Returns the scoped package [`LINES_PACKAGE`], declared by `owner`: the
256/// field macros `\\`, which ends a line, and `\indent`, which indents the
257/// line it starts by one tab. Text mode only. The lowering rules of a lines
258/// section read both in place among the section's content; neither writes
259/// anything of its own.
260pub(super) fn lines_package(owner: &FeatureName) -> ScopedPackageDef {
261    let linebreak = ElementDef::new(
262        owner.clone(),
263        [LINEBREAK_COMMAND],
264        SyntaxDef::Macro { args: Vec::new() },
265        field_element(
266            "A `\\\\` inside a lines section of a quotation: the end of a line.",
267        ),
268    )
269    .docs("Ends a line of the lines section.");
270    let indent = ElementDef::new(
271        owner.clone(),
272        [INDENT_COMMAND],
273        SyntaxDef::Macro { args: Vec::new() },
274        field_element(
275            "An `\\indent` at the start of a line of a lines section of a quotation: one tab of \
276             indentation for the line.",
277        ),
278    )
279    .docs("Indents the line it starts by one tab; written several times, by as many tabs.");
280    ScopedPackageDef {
281        owner: owner.clone(),
282        name: Name::from(LINES_PACKAGE),
283        elements: vec![linebreak, indent],
284        docs: String::from(
285            "The commands available inside a lines section of a quotation: `\\\\`, which ends a \
286             line, and `\\indent`, which indents the line it starts.",
287        ),
288    }
289}