Skip to main content

flm_core/stdlib/features/literals/
mod.rs

1//! The `literals` feature: the commands that stand for one character of text,
2//! and `\@`.
3//!
4//! The guide to the language describes these commands for authors ([writing a
5//! character that means something
6//! else](crate::guide::language_syntax#writing-a-character-that-means-something-else)).
7//!
8//! # What an author writes
9//!
10//! A **literal** is a command, or a special character sequence, whose whole
11//! meaning is one character of ordinary text. A special character sequence is a
12//! sequence of characters recognized as a command without an escape character
13//! before it ([`CallableKind`](crate::lang::mint::CallableKind)); `~` is the only
14//! literal written that way. The feature declares nine literals:
15//!
16//! | written | character |
17//! |---|---|
18//! | `\%` | `%` |
19//! | `\#` | `#` |
20//! | `\&` | `&` |
21//! | `\$` | `$` |
22//! | `\ ` (a backslash and a space) | a space |
23//! | `\{` | `{` |
24//! | `\}` | `}` |
25//! | `\textbackslash` | `\` |
26//! | `~` | a non-breaking space, U+00A0 |
27//!
28//! All nine are declared so that one spelling of each character works in every
29//! place of a document, and an author need not know where the character itself has
30//! a meaning: `&` separates the cells of a table of cells, `#` marks a placeholder
31//! in a user definition's template, `$` opens mathematics when the parsing option
32//! [`FlmParsing::dollar_math`](crate::lang::FlmParsing::dollar_math) is on, and a
33//! lone `%` is refused as ambiguous unless it starts a comment
34//! ([`FlmParsing::percent_forbidden`](crate::lang::FlmParsing::percent_forbidden)).
35//!
36//! `\ ` produces a space, and `~` the non-breaking space U+00A0, which a backend
37//! that lays text out keeps from breaking. The two are whitespace to the
38//! layout of paragraphs (their element values carry the [`Whitespace`]
39//! aspect): to the block-structure pass
40//! ([`blocks`](crate::lang::rewrites::blocks)), and to the lowering helper
41//! that trims the paragraphs and lines a rule writes over content it cuts out
42//! itself
43//! ([`stage_trimmed`](crate::stdlib::backends::lowering::stage_trimmed)).
44//! They are removed where whitespace is removed: beside an element that
45//! absorbs the whitespace next to it (`\cite` removes the whitespace written
46//! before it), on both sides of a [displayed item](BlockRole::Displayed) such
47//! as `\[…\]` (`word~\[x\]` loses its `~`), and at the start and at the end
48//! of a paragraph and of a line of a quotation; and they start no paragraph.
49//! Everywhere else they are kept as written. The pass collapses every run of
50//! whitespace in the source to one space before any lowering rule runs, but it
51//! never merges a literal into the text beside it: `a~~b` keeps its two
52//! non-breaking spaces, and `a\ \ b` its two spaces. The lowering rule
53//! produces the character of each literal kept.
54//!
55//! `\@` adjusts the space after a period. Written after a period (`cf.\@ the
56//! appendix`), it says that the period ends an abbreviation, not a sentence;
57//! written before a period that follows a capital letter (`NASA\@.`), it says
58//! that the period ends a sentence. It produces no character.
59//!
60//! # What the feature registers
61//!
62//! The `literals` feature ([`Literals`], a
63//! [`FlmFeature`]) registers:
64//!
65//! - the element type [`LITERAL`] (`flm.literal`), with one element value per
66//!   literal. The nine literals form one family, declared as one element type with
67//!   one element value per command ([elements and
68//!   aspects](crate::guide::concepts_overview#elements-and-aspects)): each
69//!   element value carries a [`LiteralElement`], whose [`Literal`] says which
70//!   character the literal stands for, and the element values of `\ ` and `~`
71//!   carry the [`Whitespace`] aspect too;
72//! - the element [`SENTENCE_SPACING`] (`flm.sentence-spacing`) for `\@`, with no
73//!   data of its own;
74//! - the default lowering rules [`RULE`] and [`SENTENCE_SPACING_RULE`], and the
75//!   recomposition rules of [`latex`] for the `latex-recomposed` backend.
76//!
77//! # What a literal becomes on each backend
78//!
79//! - **Default rules** (used by the `text` and `html` backends): [`RULE`]
80//!   replaces a literal by a text node that holds its one character
81//!   ([`Literal::text`]); [`SENTENCE_SPACING_RULE`] replaces `\@` by nothing,
82//!   because plain text and HTML have no way to write the hint.
83//! - **`latex-recomposed` backend**: the rules of [`latex`] write every literal
84//!   and `\@` back as the author wrote it.
85//!
86//! # Map of the module
87//!
88//! - [`Literals`] — the feature; [`feature`] returns it for a package entry.
89//! - [`LITERAL`], [`Literal`], [`LiteralElement`] — the element type of the
90//!   literals and the data of each element value.
91//! - [`SENTENCE_SPACING`] — the element of `\@`.
92//! - [`RULE`], [`LiteralRule`], [`SENTENCE_SPACING_RULE`],
93//!   [`SentenceSpacingRule`] — the default lowering rules and their bodies.
94//! - [`latex`] — the recomposition rules for the `latex-recomposed` backend.
95//! - [`textstyles`](crate::stdlib::features::textstyles) — the sibling feature
96//!   that declares the inline formatting commands.
97
98// The nine literals are values of one element type, so that they share one
99// lowering rule on each backend; the spelling written for a value is what tells
100// them apart in a dump.
101
102pub mod latex;
103
104use std::sync::Arc;
105
106use techy::core::node::NodeRef;
107
108use crate::core::lowering::{
109    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
110};
111use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
112use crate::lang::mint::{ElementDef, SyntaxDef};
113use crate::lang::Flm;
114use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole, IsWhitespace, Whitespace};
115use crate::model::element::{ElementSpec, element_value};
116
117/// The feature's registered name, `literals`.
118pub const FEATURE: &str = "literals";
119
120/// The name of the element type of the nine literals, `flm.literal`. The data
121/// of each element value is a [`LiteralElement`].
122pub const LITERAL: &str = "flm.literal";
123
124/// The name of the default lowering rule of [`LITERAL`] on every backend,
125/// `flm.literal.lower.default`, whose body is [`LiteralRule`].
126pub const RULE: &str = "flm.literal.lower.default";
127
128/// The name of the element of `\@`, `flm.sentence-spacing`. The element
129/// carries no data of its own.
130pub const SENTENCE_SPACING: &str = "flm.sentence-spacing";
131
132/// The name of the default lowering rule of [`SENTENCE_SPACING`] on every
133/// backend, `flm.sentence-spacing.lower.default`, whose body is
134/// [`SentenceSpacingRule`].
135pub const SENTENCE_SPACING_RULE: &str = "flm.sentence-spacing.lower.default";
136
137/// One of the nine literals: the command or special character sequence, and
138/// the character it stands for.
139///
140/// [`Literal::text`] gives the character, [`Literal::source`] how the literal
141/// is written, and [`Literal::command`] or [`Literal::trigger`] the name it is
142/// declared under. The [module documentation](self) has the table of all
143/// nine.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
145pub enum Literal {
146    /// `\%` — a percent sign.
147    Percent,
148    /// `\#` — a number sign.
149    NumberSign,
150    /// `\&` — an ampersand.
151    Ampersand,
152    /// `\$` — a dollar sign.
153    Dollar,
154    /// `\ ` (a backslash and a space) — a space that is never collapsed with
155    /// the whitespace around it.
156    Space,
157    /// `\{` — an opening brace.
158    OpenBrace,
159    /// `\}` — a closing brace.
160    CloseBrace,
161    /// `\textbackslash` — a backslash.
162    Backslash,
163    /// `~` — a non-breaking space, U+00A0.
164    NonBreakingSpace,
165}
166
167impl Literal {
168    /// The nine literals, in the order the feature declares them.
169    pub const ALL: [Literal; 9] = [
170        Literal::Percent,
171        Literal::NumberSign,
172        Literal::Ampersand,
173        Literal::Dollar,
174        Literal::Space,
175        Literal::OpenBrace,
176        Literal::CloseBrace,
177        Literal::Backslash,
178        Literal::NonBreakingSpace,
179    ];
180
181    /// The character this literal stands for, as a string of one character:
182    /// what [`LiteralRule`] writes into the text node it stages.
183    pub fn text(self) -> &'static str {
184        match self {
185            Literal::Percent => "%",
186            Literal::NumberSign => "#",
187            Literal::Ampersand => "&",
188            Literal::Dollar => "$",
189            Literal::Space => " ",
190            Literal::OpenBrace => "{",
191            Literal::CloseBrace => "}",
192            Literal::Backslash => "\\",
193            Literal::NonBreakingSpace => "\u{a0}",
194        }
195    }
196
197    /// How this literal is written in a document, escape character included
198    /// (`"\\%"`, `"\\textbackslash"`, `"~"`): what the recomposition rule
199    /// of [`latex`] writes.
200    pub fn source(self) -> &'static str {
201        match self {
202            Literal::Percent => "\\%",
203            Literal::NumberSign => "\\#",
204            Literal::Ampersand => "\\&",
205            Literal::Dollar => "\\$",
206            Literal::Space => "\\ ",
207            Literal::OpenBrace => "\\{",
208            Literal::CloseBrace => "\\}",
209            Literal::Backslash => "\\textbackslash",
210            Literal::NonBreakingSpace => "~",
211        }
212    }
213
214    /// The name of the macro this literal is declared as, without the escape
215    /// character (`"%"`, `"textbackslash"`, `" "`), or `None` for
216    /// [`Literal::NonBreakingSpace`], which is a special character sequence
217    /// and has no macro name ([`Literal::trigger`] gives its characters).
218    pub fn command(self) -> Option<&'static str> {
219        match self {
220            Literal::Percent => Some("%"),
221            Literal::NumberSign => Some("#"),
222            Literal::Ampersand => Some("&"),
223            Literal::Dollar => Some("$"),
224            Literal::Space => Some(" "),
225            Literal::OpenBrace => Some("{"),
226            Literal::CloseBrace => Some("}"),
227            Literal::Backslash => Some("textbackslash"),
228            Literal::NonBreakingSpace => None,
229        }
230    }
231
232    /// The characters of the special character sequence this literal is
233    /// declared as (`"~"`), or `None` for the eight literals that are
234    /// macros.
235    pub fn trigger(self) -> Option<&'static str> {
236        match self {
237            Literal::NonBreakingSpace => Some(self.source()),
238            _ => None,
239        }
240    }
241
242    /// The syntax this literal is declared with: a macro that takes no
243    /// argument, or a special character sequence with its characters.
244    fn syntax(self) -> SyntaxDef {
245        match self.trigger() {
246            Some(trigger) => {
247                SyntaxDef::Specials { trigger: String::from(trigger), args: Vec::new() }
248            }
249            None => SyntaxDef::Macro { args: Vec::new() },
250        }
251    }
252}
253
254/// The data of one element value of `flm.literal`: the literal, and so the
255/// character it stands for.
256///
257/// A lowering rule or a stage reads it from a node with [`element_value`].
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct LiteralElement {
260    /// The literal, and so the character it produces.
261    pub literal: Literal,
262}
263
264/// The element value of one literal: a `flm.literal` element value carrying
265/// `literal`, inline (the default block role), and whitespace ([`Whitespace`])
266/// for the two space literals, `\ ` and `~`.
267fn element(literal: Literal) -> Arc<ElementSpec> {
268    let element = ElementSpec::new(LITERAL)
269        .docs(format!("The character `{}`, written `{}`.", literal.text(), literal.source()))
270        .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
271        .with_value(Arc::new(LiteralElement { literal }));
272    match literal {
273        Literal::Space | Literal::NonBreakingSpace => {
274            Arc::new(element.with::<dyn Whitespace>(Arc::new(IsWhitespace)))
275        }
276        _ => Arc::new(element),
277    }
278}
279
280/// The element value of `\@`: a `flm.sentence-spacing` element, inline (the
281/// default block role), with no data of its own.
282fn sentence_spacing_element() -> Arc<ElementSpec> {
283    Arc::new(
284        ElementSpec::new(SENTENCE_SPACING)
285            .docs(
286                "A hint about the space after a period: whether that period ends a sentence. \
287                 It produces no character.",
288            )
289            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
290    )
291}
292
293/// The body of [`RULE`]: it replaces the literal by a text node that holds the
294/// character the literal stands for ([`Literal::text`]).
295///
296/// The rule returns a [`LowerError`] when the node carries no
297/// [`LiteralElement`] or when the text node could not be staged.
298#[derive(Debug, Default)]
299pub struct LiteralRule;
300
301impl Lower for LiteralRule {
302    fn lower(
303        &self,
304        node: NodeRef<'_, Flm>,
305        cx: &mut LowerCx<'_>,
306        lw: &mut dyn Lowerer,
307    ) -> Result<Lowering, LowerError> {
308        let value = element_value::<LiteralElement>(&node)
309            .ok_or_else(|| LowerError::structure("a literal node without its value"))?;
310        let text = lw.text(cx, value.literal.text())?;
311        Ok(Lowering::Emit(vec![text]))
312    }
313}
314
315/// The body of [`SENTENCE_SPACING_RULE`]: it replaces `\@` by nothing. The
316/// hint has no form in plain text or HTML; the `latex-recomposed` backend
317/// writes it back through the rule of [`latex`]. See the [module
318/// documentation](self) for what `\@` means.
319#[derive(Debug, Default)]
320pub struct SentenceSpacingRule;
321
322impl Lower for SentenceSpacingRule {
323    fn lower(
324        &self,
325        _node: NodeRef<'_, Flm>,
326        _cx: &mut LowerCx<'_>,
327        _lw: &mut dyn Lowerer,
328    ) -> Result<Lowering, LowerError> {
329        Ok(Lowering::Emit(Vec::new()))
330    }
331}
332
333/// The `literals` feature: it registers the nine literals and `\@`, their two
334/// default lowering rules and the recomposition rules of [`latex`]. See the
335/// module documentation.
336#[derive(Debug, Default, Clone, Copy)]
337pub struct Literals;
338
339impl FlmFeature for Literals {
340    fn info(&self) -> FeatureInfo {
341        FeatureInfo::new(FEATURE, "Literal characters").docs(
342            "The commands that stand for one character of text (`\\%`, `\\#`, `\\&`, `\\$`, \
343             `\\ `, `\\{`, `\\}`, `\\textbackslash`) and the special character sequence `~` \
344             for a non-breaking space: nine values of the element type `flm.literal`. Also \
345             `\\@`, a hint about whether a period ends a sentence.",
346        )
347    }
348
349    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
350        let owner = b.feature().clone();
351        for literal in Literal::ALL {
352            b.element(
353                ElementDef::new(
354                    owner.clone(),
355                    literal.command(),
356                    literal.syntax(),
357                    element(literal),
358                )
359                .docs(match literal {
360                    Literal::Space => String::from("Writes a space."),
361                    Literal::NonBreakingSpace => String::from("Writes a non-breaking space."),
362                    _ => format!("Writes the character `{}`.", literal.text()),
363                }),
364            )?;
365        }
366        b.element_type_text(
367            LITERAL,
368            "A character written with a command or a special character sequence, because \
369             the character itself means something else in the source: `\\%` for `%`, or `~` \
370             for a non-breaking space.",
371        )?;
372        b.element(
373            ElementDef::new(
374                owner.clone(),
375                ["@"],
376                SyntaxDef::Macro { args: Vec::new() },
377                sentence_spacing_element(),
378            )
379            .docs(
380                "Gives a hint about whether a period ends a sentence. Only the recomposed \
381                 LaTeX writes it; every other output leaves it out.",
382            ),
383        )?;
384        b.element_type_text(
385            SENTENCE_SPACING,
386            "A hint about whether a period ends a sentence, which sets the space after it. It \
387             produces no character.",
388        )?;
389        b.lowering_rule(
390            LoweringRule::new(
391                RULE,
392                LITERAL,
393                LoweringDecl::new(),
394                Arc::new(LiteralRule),
395                DefaultMark::Everywhere,
396            )
397            .docs("a literal lowers to a text node holding the character it stands for"),
398        )?;
399        b.lowering_rule(
400            LoweringRule::new(
401                SENTENCE_SPACING_RULE,
402                SENTENCE_SPACING,
403                LoweringDecl::new(),
404                Arc::new(SentenceSpacingRule),
405                DefaultMark::Everywhere,
406            )
407            .docs("`\\@` lowers to nothing"),
408        )?;
409        latex::register(b)?;
410        Ok(())
411    }
412}
413
414/// The [`Literals`] feature as a shared value, ready to be listed in a package
415/// entry.
416pub fn feature() -> Arc<dyn FlmFeature> {
417    Arc::new(Literals)
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    #[test]
425    fn every_spelling_names_its_source_and_its_character() {
426        assert_eq!(Literal::Percent.source(), "\\%");
427        assert_eq!(Literal::Percent.command(), Some("%"));
428        assert_eq!(Literal::Backslash.command(), Some("textbackslash"));
429        assert_eq!(Literal::Space.command(), Some(" "));
430        assert_eq!(Literal::NonBreakingSpace.command(), None);
431        assert_eq!(Literal::NonBreakingSpace.trigger(), Some("~"));
432        assert_eq!(Literal::NonBreakingSpace.text(), "\u{a0}");
433        assert_eq!(Literal::ALL.len(), 9);
434        for literal in Literal::ALL {
435            assert_eq!(literal.text().chars().count(), 1);
436        }
437    }
438
439    #[test]
440    fn an_element_value_carries_its_spelling_and_the_inline_role() {
441        let element = element(Literal::OpenBrace);
442        assert_eq!(element.name, LITERAL);
443        assert_eq!(
444            element.value_as::<LiteralElement>().map(|v| v.literal),
445            Some(Literal::OpenBrace)
446        );
447        assert!(element.has_aspect::<dyn BlockRoleAspect>());
448    }
449
450    #[test]
451    fn the_sentence_spacing_element_carries_no_value() {
452        let element = sentence_spacing_element();
453        assert_eq!(element.name, SENTENCE_SPACING);
454        assert!(element.value_as::<LiteralElement>().is_none());
455    }
456}