flm_core/stdlib/features/numbering/formats.rs
1//! The eight number formats ([`NumberFormat`]) and the number template
2//! ([`NumberTemplate`]), the text with which a counter style writes a number,
3//! in either of its two languages; and their compilation against the built
4//! language.
5//!
6//! The superscript and subscript digits are read from the text backend's
7//! table of Unicode forms ([`superscript_form`], [`subscript_form`]), so that
8//! the library holds a single table of those forms.
9
10use std::fmt;
11use std::sync::Arc;
12
13use techy::core::node::NodeTree;
14
15use crate::lang::rewrites::userdefs::template::{CompiledTemplate, TemplateLanguage};
16use crate::lang::{BuiltLang, Flm, FlmDiagnostic};
17use crate::model::names::Name;
18// A feature may read a backend module: the library's layering rules constrain
19// only the crate's top-level modules.
20use crate::stdlib::backends::text::superscript::{subscript_form, superscript_form};
21
22use super::style::{parse_text, StyleError};
23use super::template::{compile_text, number_vocabulary, occurrences_of};
24
25/// A number format: one way of writing a number as characters, as decimal
26/// digits, letters, roman numerals, footnote symbols, or superscript or
27/// subscript digits.
28///
29/// A number template refers to a format by the name that
30/// [`written_name`](NumberFormat::written_name) returns: `#{arabic}` writes the
31/// number in [`Arabic`](NumberFormat::Arabic). The settings use the same
32/// names, so these names are part of the settings format and stay fixed.
33///
34/// Every format except `Arabic` writes the empty text for a number it cannot
35/// write: zero, a negative number, and a number so large that its text would
36/// be longer than [`MAX_CHARS`](NumberFormat::MAX_CHARS) characters. `Arabic`
37/// writes the decimal digits of any number, including `0` and a leading minus
38/// sign.
39///
40/// # Examples
41///
42/// ```
43/// use flm_core::stdlib::features::numbering::NumberFormat;
44///
45/// assert_eq!(NumberFormat::Arabic.text(12), "12");
46/// assert_eq!(NumberFormat::Letters.text(27), "aa");
47/// assert_eq!(NumberFormat::CapitalRoman.text(2099), "MMXCIX");
48/// assert_eq!(NumberFormat::Roman.text(0), "");
49/// assert_eq!(NumberFormat::from_written_name("fnsymbol"), Some(NumberFormat::Symbols));
50/// ```
51#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
52pub enum NumberFormat {
53 /// The decimal digits: `1`, `2`, `12`. Written `arabic`.
54 Arabic,
55 /// Lowercase letters, repeated instead of counted in base twenty-six:
56 /// `a`, …, `z`, `aa`, `bb`, …, `zz`, `aaa`. Written `alph`.
57 Letters,
58 /// [`Letters`](NumberFormat::Letters) in uppercase: `A`, …, `AA`. Written
59 /// `Alph`.
60 CapitalLetters,
61 /// Lowercase roman numerals: `i`, `iv`, `mmxcix`. Written `roman`.
62 Roman,
63 /// [`Roman`](NumberFormat::Roman) in uppercase: `I`, `IV`, `MMXCIX`.
64 /// Written `Roman`.
65 CapitalRoman,
66 /// The footnote symbols `*`, `†`, `‡`, `§`, `¶`, `‖`, doubled from the
67 /// seventh, tripled from the thirteenth. Written `fnsymbol`.
68 Symbols,
69 /// The decimal digits as superscript characters: `¹⁷`. Written
70 /// `unicodesuperscript`.
71 Superscript,
72 /// The decimal digits as subscript characters: `₁₇`. Written
73 /// `unicodesubscript`.
74 Subscript,
75}
76
77/// The footnote symbols, in order.
78const SYMBOLS: [char; 6] = ['*', '\u{2020}', '\u{2021}', '\u{00a7}', '\u{00b6}', '\u{2016}'];
79
80/// The values of the roman numeral pieces, largest first.
81const ROMAN: [(i64, &str); 13] = [
82 (1000, "M"),
83 (900, "CM"),
84 (500, "D"),
85 (400, "CD"),
86 (100, "C"),
87 (90, "XC"),
88 (50, "L"),
89 (40, "XL"),
90 (10, "X"),
91 (9, "IX"),
92 (5, "V"),
93 (4, "IV"),
94 (1, "I"),
95];
96
97impl NumberFormat {
98 /// Every format, in the order of the variants above.
99 pub const ALL: [NumberFormat; 8] = [
100 NumberFormat::Arabic,
101 NumberFormat::Letters,
102 NumberFormat::CapitalLetters,
103 NumberFormat::Roman,
104 NumberFormat::CapitalRoman,
105 NumberFormat::Symbols,
106 NumberFormat::Superscript,
107 NumberFormat::Subscript,
108 ];
109
110 /// The length, in characters, of the longest text a format other than
111 /// [`Arabic`](NumberFormat::Arabic) writes. A number whose text would be
112 /// longer gets the empty text, so that the work of writing a number is
113 /// bounded for every number.
114 pub const MAX_CHARS: usize = 1024;
115
116 /// Returns the name by which a number template and the settings refer to
117 /// this format: `arabic`, `alph`, `Alph`, `roman`, `Roman`, `fnsymbol`,
118 /// `unicodesuperscript` or `unicodesubscript`.
119 pub fn written_name(self) -> &'static str {
120 match self {
121 NumberFormat::Arabic => "arabic",
122 NumberFormat::Letters => "alph",
123 NumberFormat::CapitalLetters => "Alph",
124 NumberFormat::Roman => "roman",
125 NumberFormat::CapitalRoman => "Roman",
126 NumberFormat::Symbols => "fnsymbol",
127 NumberFormat::Superscript => "unicodesuperscript",
128 NumberFormat::Subscript => "unicodesubscript",
129 }
130 }
131
132 /// Returns the format whose written name is `name`, or `None` when no
133 /// format has that name. The inverse of
134 /// [`written_name`](NumberFormat::written_name).
135 pub fn from_written_name(name: &str) -> Option<NumberFormat> {
136 NumberFormat::ALL.into_iter().find(|format| format.written_name() == name)
137 }
138
139 /// Returns `number` written in this format. The type's documentation says
140 /// what a format writes for a number it cannot write.
141 pub fn text(self, number: i64) -> String {
142 match self {
143 NumberFormat::Arabic => number.to_string(),
144 NumberFormat::Letters => repeated_letter(number, 'a'),
145 NumberFormat::CapitalLetters => repeated_letter(number, 'A'),
146 NumberFormat::Roman => roman(number).to_lowercase(),
147 NumberFormat::CapitalRoman => roman(number),
148 NumberFormat::Symbols => repeated_symbol(number),
149 NumberFormat::Superscript => in_forms(number, superscript_form),
150 NumberFormat::Subscript => in_forms(number, subscript_form),
151 }
152 }
153}
154
155impl fmt::Display for NumberFormat {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 f.write_str(self.written_name())
158 }
159}
160
161/// Returns the letter at `number`'s place in the alphabet, repeated once per
162/// completed round of twenty-six: 1 is `a`, 26 is `z`, 27 is `aa`, 53 is
163/// `aaa`. `first` is the first letter of the alphabet, which chooses the case.
164fn repeated_letter(number: i64, first: char) -> String {
165 let Some(index) = positive_index(number) else { return String::new() };
166 let repeats = 1 + index / 26;
167 if repeats > NumberFormat::MAX_CHARS as i64 {
168 return String::new();
169 }
170 let letter = char::from(first as u8 + (index % 26) as u8);
171 std::iter::repeat_n(letter, repeats as usize).collect()
172}
173
174/// Returns the footnote symbol at `number`'s place, repeated once per
175/// completed round of the six symbols.
176fn repeated_symbol(number: i64) -> String {
177 let Some(index) = positive_index(number) else { return String::new() };
178 let repeats = 1 + index / SYMBOLS.len() as i64;
179 if repeats > NumberFormat::MAX_CHARS as i64 {
180 return String::new();
181 }
182 let symbol = SYMBOLS[(index % SYMBOLS.len() as i64) as usize];
183 std::iter::repeat_n(symbol, repeats as usize).collect()
184}
185
186/// Returns `number` written as an uppercase roman numeral: the largest
187/// numeral that fits is written as often as it fits, then the next with the
188/// remainder.
189fn roman(number: i64) -> String {
190 if number <= 0 {
191 return String::new();
192 }
193 // Every thousand takes one character, and what is left of a number below a
194 // thousand takes at most fifteen.
195 if number / 1000 + 15 > NumberFormat::MAX_CHARS as i64 {
196 return String::new();
197 }
198 let mut left = number;
199 let mut out = String::new();
200 for (value, piece) in ROMAN {
201 while left >= value {
202 out.push_str(piece);
203 left -= value;
204 }
205 }
206 out
207}
208
209/// Returns `number`'s decimal digits, each written in the form that `form`
210/// gives it (every digit has a superscript and a subscript form). Zero and
211/// every negative number get the empty text, as the superscript and subscript
212/// formats write only positive numbers.
213fn in_forms(number: i64, form: fn(char) -> Option<char>) -> String {
214 if number <= 0 {
215 return String::new();
216 }
217 number.to_string().chars().map(|digit| form(digit).unwrap_or(digit)).collect()
218}
219
220/// Returns `number`'s place counted from zero, or `None` when the number is
221/// zero or negative and the format has nothing to write.
222fn positive_index(number: i64) -> Option<i64> {
223 (number >= 1).then(|| number - 1)
224}
225
226/// A number template: how a counter style writes the number itself, as a text
227/// with a place for the number, written in one of the eight [`NumberFormat`]s;
228/// a counter style holds one in its field `number_format`.
229///
230/// The text is FLM with a place for the number, in one of two languages, and
231/// it is compiled once, when the counter style is compiled. Around the place
232/// for the number the text is ordinary FLM: `\textbf` and `~` mean in a
233/// number template what they mean in a document.
234///
235/// - [`Formats`](NumberTemplate::Formats) is written in the template language
236/// that user definitions use ([the template language shared by
237/// features](crate::guide::concepts_overview#the-template-language-shared-by-features)):
238/// `#{name}` is the number written in the format `name`. The whole text is
239/// parsed as one, so markup may surround the number: `\textbf{#{arabic}}`
240/// writes the number in bold.
241/// - [`Initial`](NumberTemplate::Initial) is the language of an author's own
242/// item labels: the first of the characters `a`, `A`, `i`, `I` and `1` is
243/// the number, written in the format that character shows by example, and
244/// the rest is FLM: `(a)` writes `(c)` for the number three.
245///
246/// A counter style's number format
247/// ([`CounterStyleDecl::number_format`](super::CounterStyleDecl::number_format)),
248/// each of its sub-levels ([`SubLevelDecl`](super::SubLevelDecl)) and a
249/// reference point's own number template
250/// ([`NumberSource::number_format`](crate::model::aspects::NumberSource::number_format),
251/// always in the `Formats` language) are number templates.
252///
253/// # Examples
254///
255/// The number in decimal digits followed by a full stop, and the number as a
256/// lowercase letter between parentheses:
257///
258/// ```
259/// use flm_core::stdlib::features::numbering::NumberTemplate;
260///
261/// let section = NumberTemplate::formats("#{arabic}.");
262/// let item = NumberTemplate::initial("(a)");
263/// # let _ = (section, item);
264/// ```
265///
266/// Markup around the number. The language that the counter style is compiled
267/// against here holds FLM's structural elements and no feature's commands, so
268/// the example surrounds the number with a group instead of a command; a
269/// command's braces are a group, and a command behaves the same way.
270///
271/// ```
272/// use flm_core::lang::{build_language, LangInputs};
273/// use flm_core::stdlib::features::numbering::{CounterStyleDecl, NumberTemplate};
274///
275/// let lang = build_language(LangInputs::new());
276///
277/// let mut around = CounterStyleDecl::new("example.style.equation");
278/// around.number_format = NumberTemplate::formats("{#{arabic}}");
279/// assert!(around.compile(&lang).is_ok());
280///
281/// // A name that is not one of the eight formats is refused.
282/// let mut wrong = CounterStyleDecl::new("example.style.equation");
283/// wrong.number_format = NumberTemplate::formats("#{nosuchformat}");
284/// assert!(wrong.compile(&lang).is_err());
285/// ```
286#[derive(Clone, PartialEq, Eq, Debug, serde::Deserialize, serde::Serialize)]
287#[derive(schemars::JsonSchema)]
288#[serde(rename_all = "kebab-case")]
289pub enum NumberTemplate {
290 /// A number template in the template language: every `#{name}` is the
291 /// number written in the format `name`, and the rest is written as given:
292 /// `#{arabic}.` writes `3.` for the number three, and
293 /// `\textbf{#{arabic}}` writes it in bold. A `#{…}` whose name is not a
294 /// number format is refused when the counter style is compiled, and so is
295 /// a key in brackets, `#[…]{…}`, which only a within template accepts.
296 Formats(String),
297 /// A number template in the single-letter language: the first character
298 /// among `a`, `A`, `i`, `I` and `1` is the number, written in the format
299 /// that character shows by example (letters, capital letters, roman
300 /// numerals, capital roman numerals, decimal digits), and the rest is
301 /// FLM written as given: `(a)` writes `(c)` for the number three. A text
302 /// that holds none of those five characters writes itself for every
303 /// number, and the parts of the counters it is numbered within are not
304 /// written before it: it is a fixed mark, such as a bullet.
305 ///
306 /// This is the language of an author's own item labels, where the
307 /// number's format is shown by an example instead of being named. The
308 /// first of the five characters is replaced wherever it is, so `Part a.`
309 /// writes `Pcrt a.` for the number three; a text that must hold one of
310 /// these characters as a letter of its own is written in the `Formats`
311 /// language.
312 Initial(String),
313}
314
315impl NumberTemplate {
316 /// Returns a [`Formats`](NumberTemplate::Formats) number template with the
317 /// text `text`.
318 pub fn formats(text: impl Into<String>) -> NumberTemplate {
319 NumberTemplate::Formats(text.into())
320 }
321
322 /// Returns an [`Initial`](NumberTemplate::Initial) number template with
323 /// the text `text`.
324 pub fn initial(text: impl Into<String>) -> NumberTemplate {
325 NumberTemplate::Initial(text.into())
326 }
327
328 /// Returns the template's text, in the language it is written in.
329 pub fn text(&self) -> &str {
330 match self {
331 NumberTemplate::Formats(text) | NumberTemplate::Initial(text) => text,
332 }
333 }
334}
335
336/// One part of a compiled single-letter number template: FLM parsed once, or
337/// the number in a format.
338pub(super) enum NumberPart {
339 /// A literal part of the template, parsed when the counter style was
340 /// compiled.
341 Literal(Arc<NodeTree<Flm>>),
342 /// The number, written in this format.
343 Number(NumberFormat),
344}
345
346/// A number template compiled against the built language.
347///
348/// A compiled number template belongs to a compiled counter style
349/// ([`CounterStyle`](super::CounterStyle)), which writes numbers with it.
350pub(super) enum CompiledNumber {
351 /// An [`Initial`](NumberTemplate::Initial) template: its literal parts
352 /// parsed, and the single letter replaced by the format it shows.
353 Initial {
354 /// The parts, in the order they are written.
355 parts: Vec<NumberPart>,
356 /// Whether the ancestors' numbers are written before this template's
357 /// own text. Only a template that holds none of the five characters
358 /// leaves them out.
359 with_parent: bool,
360 },
361 /// A [`Formats`](NumberTemplate::Formats) template, compiled by the
362 /// template compiler of the language layer: every `#{…}` is the number in
363 /// the format between its braces, and everything around it is content
364 /// that may surround the number.
365 Written {
366 /// The compiled template.
367 template: CompiledTemplate,
368 /// The formats the template refers to, each once, in the order of
369 /// their first use: the formats in which the number is written before
370 /// the template is instantiated.
371 formats: Vec<NumberFormat>,
372 },
373}
374
375impl CompiledNumber {
376 /// Returns whether the ancestors' numbers are written before this
377 /// template's own text.
378 pub(super) fn with_parent(&self) -> bool {
379 match self {
380 CompiledNumber::Initial { with_parent, .. } => *with_parent,
381 CompiledNumber::Written { .. } => true,
382 }
383 }
384
385 /// Returns `template` compiled against `lang`; `style` is the name of the
386 /// counter style the template belongs to, which a diagnostic gives.
387 ///
388 /// # Errors
389 ///
390 /// [`StyleError::Template`] for a `Formats` template that does not compile
391 /// (one that is not valid FLM, or whose `#{…}` is not one of the eight
392 /// number formats), and the parse error of a literal part of an
393 /// `Initial` template.
394 pub(super) fn compile(
395 template: &NumberTemplate,
396 style: &Name,
397 lang: &BuiltLang,
398 language: &TemplateLanguage,
399 warnings: &mut Vec<FlmDiagnostic>,
400 ) -> Result<CompiledNumber, StyleError> {
401 match template {
402 NumberTemplate::Formats(text) => compile_formats(text, style, lang, language),
403 NumberTemplate::Initial(text) => compile_initial(text, lang, warnings),
404 }
405 }
406}
407
408/// The five characters by which an [`Initial`](NumberTemplate::Initial)
409/// template shows a format, and the format each one shows.
410const INITIALS: [(char, NumberFormat); 5] = [
411 ('a', NumberFormat::Letters),
412 ('A', NumberFormat::CapitalLetters),
413 ('i', NumberFormat::Roman),
414 ('I', NumberFormat::CapitalRoman),
415 ('1', NumberFormat::Arabic),
416];
417
418/// Compiles a [`Formats`](NumberTemplate::Formats) template with the template
419/// compiler of the language layer, and reads from it the formats it refers to.
420fn compile_formats(
421 text: &str,
422 style: &Name,
423 lang: &BuiltLang,
424 language: &TemplateLanguage,
425) -> Result<CompiledNumber, StyleError> {
426 let what = format!("the counter style `{style}`");
427 let template = compile_text(text, &what, &number_vocabulary(), lang, language)?;
428 let mut formats = Vec::new();
429 for (name, _) in occurrences_of(&template) {
430 // The template compiled against the vocabulary of the eight formats,
431 // so every name it writes is one of them.
432 if let Some(format) = NumberFormat::from_written_name(&name) {
433 if !formats.contains(&format) {
434 formats.push(format);
435 }
436 }
437 }
438 Ok(CompiledNumber::Written { template, formats })
439}
440
441/// Compiles an [`Initial`](NumberTemplate::Initial) template: the text is cut
442/// at the first of the five characters, which becomes the format, and the two
443/// texts around it are parsed as FLM.
444fn compile_initial(
445 text: &str,
446 lang: &BuiltLang,
447 warnings: &mut Vec<FlmDiagnostic>,
448) -> Result<CompiledNumber, StyleError> {
449 let found = text.char_indices().find_map(|(at, ch)| {
450 INITIALS.iter().find(|(initial, _)| *initial == ch).map(|(_, format)| (at, *format))
451 });
452 let Some((at, format)) = found else {
453 let mut parts = Vec::new();
454 let mut literal = text.to_string();
455 push_literal(&mut parts, &mut literal, text, lang, warnings)?;
456 return Ok(CompiledNumber::Initial { parts, with_parent: false });
457 };
458 let mut parts = Vec::new();
459 let mut before = text[..at].to_string();
460 push_literal(&mut parts, &mut before, text, lang, warnings)?;
461 parts.push(NumberPart::Number(format));
462 let mut after = text[at + 1..].to_string();
463 push_literal(&mut parts, &mut after, text, lang, warnings)?;
464 Ok(CompiledNumber::Initial { parts, with_parent: true })
465}
466
467/// Parses `literal` as FLM and appends it as a part, unless it is empty; then
468/// empties it for the next text.
469///
470/// `declared` is the whole template the text comes from: a refused text is
471/// reported with the whole template, because nobody wrote the text on either
472/// side of the letter on its own.
473fn push_literal(
474 parts: &mut Vec<NumberPart>,
475 literal: &mut String,
476 declared: &str,
477 lang: &BuiltLang,
478 warnings: &mut Vec<FlmDiagnostic>,
479) -> Result<(), StyleError> {
480 if literal.is_empty() {
481 return Ok(());
482 }
483 let parsed =
484 parse_text(literal, lang, warnings).map_err(|error| error.in_text(declared))?;
485 parts.push(NumberPart::Literal(parsed));
486 literal.clear();
487 Ok(())
488}
489
490#[cfg(test)]
491mod tests {
492 use super::*;
493
494 #[test]
495 fn every_format_is_written_by_its_own_name() {
496 for format in NumberFormat::ALL {
497 assert_eq!(NumberFormat::from_written_name(format.written_name()), Some(format));
498 }
499 }
500
501 #[test]
502 fn a_number_too_large_to_write_gets_the_empty_text() {
503 for format in NumberFormat::ALL {
504 let text = format.text(i64::MAX);
505 assert!(
506 text.chars().count() <= 20,
507 "{format} wrote {} characters",
508 text.chars().count()
509 );
510 }
511 assert_eq!(NumberFormat::Arabic.text(i64::MAX), i64::MAX.to_string());
512 }
513}