Skip to main content

sokf_core/config/
texts.rs

1//! This module reads sokf's own texts in layers (CONF-12): sokf's English, then
2//! the files of `/.sokf/texts.d/`, in which no file takes precedence over
3//! another, then `/.sokf/texts.yaml`. An entry of each layer replaces the same
4//! entry of the layer below. The module also looks a text up in a language.
5
6use std::collections::BTreeMap;
7
8use tramlines_core::text::is_language_tag;
9
10use crate::{
11    Error, RepoPath, RepoRoot, Result, Spanned, Yaml, grammar::squash, report::and_list, source,
12    yaml,
13};
14
15/// `TEXTS_DIR` is the drop-in folder of the texts, relative to the
16/// repository root.
17const TEXTS_DIR: &str = ".sokf/texts.d";
18
19/// `ENGLISH` holds sokf's own texts in English.
20const ENGLISH: &str = include_str!("texts.yaml");
21
22/// `UNITS` names each unit that a limit counts, whose forms the entry
23/// `units` gives.
24pub(crate) const UNITS: &[&str] = &[
25    "paragraph",
26    "item",
27    "row",
28    "line",
29    "fence",
30    "image",
31    "definition",
32    "repetition",
33    "value",
34    "link",
35    "unit",
36];
37
38/// `LABELS` names each attribution label, whose words the entry `labels`
39/// gives and whose meaning the entry `attribution` gives.
40pub(crate) const LABELS: [&str; 2] = ["human", "agent"];
41
42/// `texts_path` returns the path of the project's own file of texts.
43fn texts_path() -> RepoPath {
44    RepoPath::parse("/.sokf/texts.yaml").expect("literal")
45}
46
47/// `Text` is one entry of a language: words, or the two forms of a unit.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Text {
50    /// The words of a rule or a template.
51    Words(String),
52    /// The forms of a unit: `one` for a count of 1, `other` for every other
53    /// count and for a ban.
54    Forms {
55        /// The form for a count of 1.
56        one: String,
57        /// The form for every other count.
58        other: String,
59    },
60}
61
62/// `Texts` holds sokf's texts, keyed by language, as a tag in lower case, and
63/// by entry, such as `limit.hard` or `units.item`.
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct Texts {
66    entries: BTreeMap<(String, String), Text>,
67}
68
69impl Texts {
70    /// `english` returns sokf's own English texts, without the layers of the
71    /// repository.
72    pub fn english() -> Texts {
73        let path = RepoPath::parse("/crates/lib/sokf-core/src/config/texts.yaml").expect("literal");
74        let entries = parse(&path, ENGLISH).expect("sokf's own texts parse");
75        Texts {
76            entries: entries
77                .into_iter()
78                .map(|e| ((e.language, e.entry), e.text))
79                .collect(),
80        }
81    }
82
83    /// `get` returns the entry `entry` of the language `language`: of the whole
84    /// tag, in any case, else of the tag with its last subtags removed one at a
85    /// time, down to the language alone, as the lookup of RFC 4647 does.
86    // sokf-implements: CONF-12_AC-6
87    pub(crate) fn get(&self, language: &str, entry: &str) -> Option<&Text> {
88        lookup(language)
89            .into_iter()
90            .find_map(|tag| self.entries.get(&(tag, entry.to_string())))
91    }
92
93    /// `with` returns these texts with each entry of `text`, a file of
94    /// texts, in place of the same entry.
95    #[cfg(test)]
96    pub(crate) fn with(mut self, text: &str) -> Texts {
97        let path = RepoPath::parse("/.sokf/texts.yaml").expect("literal");
98        for e in parse(&path, text).expect("the texts parse") {
99            self.entries.insert((e.language, e.entry), e.text);
100        }
101        self
102    }
103
104    /// `words` returns the words of the entry `entry` of `language`.
105    pub fn words(&self, language: &str, entry: &str) -> Option<&str> {
106        match self.get(language, entry)? {
107            Text::Words(w) => Some(w),
108            Text::Forms { .. } => None,
109        }
110    }
111
112    /// `label` returns the words of the label `key` in `language`, with each
113    /// run of whitespace made one space, or `None` where the language has
114    /// none.
115    pub fn label(&self, language: &str, key: &str) -> Option<String> {
116        self.squashed(language, &format!("labels.{key}"))
117    }
118
119    /// `attribution` returns the meaning of the label `key` in `language`,
120    /// with each run of whitespace made one space, or `None` where the
121    /// language has none.
122    pub fn attribution(&self, language: &str, key: &str) -> Option<String> {
123        self.squashed(language, &format!("attribution.{key}"))
124    }
125
126    /// `squashed` returns the words of the entry `entry` of `language`, with
127    /// each run of whitespace made one space, or `None` where they are absent
128    /// or blank.
129    fn squashed(&self, language: &str, entry: &str) -> Option<String> {
130        self.words(language, entry)
131            .map(squash)
132            .filter(|w| !w.is_empty())
133    }
134
135    /// `check_labels` refuses a language in which the labels `human` and
136    /// `agent` take the same words, each label's own words or else its key,
137    /// or in which the words of one label are the key of the other, because a
138    /// document could not tell the two apart: the engine reads a label's key
139    /// as the label where no label takes it as its words. `sources` names the
140    /// file of each entry that a file of the repository gives, and `written`
141    /// each language tag as a file writes it.
142    // sokf-implements: CONF-12_AC-10
143    fn check_labels(
144        &self,
145        sources: &BTreeMap<(String, String), RepoPath>,
146        written: &BTreeMap<String, String>,
147    ) -> Result<()> {
148        let tags: std::collections::BTreeSet<&str> = self
149            .entries
150            .keys()
151            .filter(|(_, entry)| entry.starts_with("labels."))
152            .map(|(tag, _)| tag.as_str())
153            .collect();
154        for tag in tags {
155            let [human, agent] =
156                LABELS.map(|key| self.label(tag, key).unwrap_or_else(|| key.to_string()));
157            // The fault, and the labels whose entries hold it, the later first.
158            let (fault, at): (String, &[&str]) = if human == agent {
159                (
160                    format!("the labels `human` and `agent` both take the words `{human}`"),
161                    &["agent", "human"],
162                )
163            } else if human == LABELS[1] {
164                (
165                    format!("the label `human` takes the words `{human}`, the key of `agent`"),
166                    &["human"],
167                )
168            } else if agent == LABELS[0] {
169                (
170                    format!("the label `agent` takes the words `{agent}`, the key of `human`"),
171                    &["agent"],
172                )
173            } else {
174                continue;
175            };
176            // The file that gave an entry that holds the fault, where a file
177            // of the repository gave one.
178            let file = at
179                .iter()
180                .find_map(|key| {
181                    let entry = format!("labels.{key}");
182                    lookup(tag)
183                        .into_iter()
184                        .find(|t| self.entries.contains_key(&(t.clone(), entry.clone())))
185                        .and_then(|t| sources.get(&(t, entry)))
186                })
187                .cloned()
188                .unwrap_or_else(texts_path);
189            let tag = written.get(tag).map_or(tag, String::as_str);
190            return Err(Error::config(
191                file,
192                format!(
193                    "in `{tag}`, {fault}, so a document could not tell the two labels apart; give \
194                     them other words"
195                ),
196            ));
197        }
198        Ok(())
199    }
200
201    /// `forms` returns the two forms of the unit `unit` in `language`.
202    pub fn forms(&self, language: &str, unit: &str) -> Option<(&str, &str)> {
203        match self.get(language, &format!("units.{unit}"))? {
204            Text::Forms { one, other } => Some((one, other)),
205            Text::Words(_) => None,
206        }
207    }
208}
209
210/// `lookup` returns the tags to try for `language`, in lower case: the whole
211/// tag, then the tag less each last subtag in turn, skipping a shorter tag
212/// that ends in a single-letter subtag, which only introduces an extension.
213fn lookup(language: &str) -> Vec<String> {
214    let lower = language.to_ascii_lowercase();
215    let parts: Vec<&str> = lower.split('-').collect();
216    (1..=parts.len())
217        .rev()
218        .filter(|&n| n == parts.len() || n == 1 || parts[n - 1].len() > 1)
219        .map(|n| parts[..n].join("-"))
220        .collect()
221}
222
223/// `texts_files_lenient` returns `/.sokf/texts.yaml` and each file `*.yaml`
224/// at any depth below `/.sokf/texts.d/`, as `load_texts` reads them, and
225/// skips each directory of the folder that can't be read, so that the files
226/// of every other directory still count.
227pub fn texts_files_lenient(root: &RepoRoot) -> Vec<RepoPath> {
228    let mut files = super::d_folder::d_files(root, TEXTS_DIR, "yaml", true).unwrap_or_default();
229    files.push(texts_path());
230    files
231}
232
233/// `load_texts` reads sokf's texts: its English, then each file `*.yaml` at
234/// any depth below `/.sokf/texts.d/`, then `/.sokf/texts.yaml`. An entry of
235/// a later layer replaces the same entry of an earlier one. It refuses a
236/// file that doesn't parse as a file of texts, and an entry that two files
237/// of the folder give different texts and `/.sokf/texts.yaml` doesn't give.
238// sokf-implements: CONF-12_AC-1
239// sokf-implements: CONF-12_AC-2
240// sokf-implements: CONF-12_AC-3
241pub fn load_texts(root: &RepoRoot) -> Result<Texts> {
242    let mut texts = Texts::english();
243    let mut folder: BTreeMap<(String, String), (Parsed, RepoPath)> = BTreeMap::new();
244    let mut clashes: Vec<(RepoPath, Parsed, RepoPath)> = Vec::new();
245    for path in super::d_folder::d_files(root, TEXTS_DIR, "yaml", false)? {
246        let Some(text) = source::read_optional(&path.to_fs(root))? else {
247            continue;
248        };
249        for e in parse(&path, &text)? {
250            let key = (e.language.clone(), e.entry.clone());
251            match folder.get(&key) {
252                Some((first, _)) if first.text == e.text => {}
253                Some((_, first_path)) => clashes.push((first_path.clone(), e, path.clone())),
254                None => {
255                    folder.insert(key, (e, path.clone()));
256                }
257            }
258        }
259    }
260    let repo_path = texts_path();
261    let repo = match source::read_optional(&repo_path.to_fs(root))? {
262        Some(text) => parse(&repo_path, &text)?,
263        None => Vec::new(),
264    };
265    let settled = |e: &Parsed| {
266        repo.iter()
267            .any(|r| r.language == e.language && r.entry == e.entry)
268    };
269    if let Some((first, e, later)) = clashes.iter().find(|(_, e, _)| !settled(e)) {
270        return Err(Error::config(
271            later.clone(),
272            format!(
273                "the text `{}` of `{}` is given differently in `{first}` and `{later}` of \
274                 /{TEXTS_DIR}/, and no file of the folder takes precedence; give it in `{repo_path}` \
275                 to choose one",
276                e.entry, e.written
277            ),
278        ));
279    }
280    let mut sources: BTreeMap<(String, String), RepoPath> = BTreeMap::new();
281    let mut written: BTreeMap<String, String> = BTreeMap::new();
282    for (key, (e, path)) in folder {
283        sources.insert(key.clone(), path);
284        written.insert(e.language, e.written);
285        texts.entries.insert(key, e.text);
286    }
287    for e in repo {
288        let key = (e.language.clone(), e.entry);
289        sources.insert(key.clone(), repo_path.clone());
290        written.insert(e.language, e.written);
291        texts.entries.insert(key, e.text);
292    }
293    texts.check_labels(&sources, &written)?;
294    Ok(texts)
295}
296
297/// `Parsed` is one entry of a file of texts: its language in lower case and
298/// as the file writes it, the entry, and its text.
299#[derive(Debug, Clone)]
300struct Parsed {
301    language: String,
302    written: String,
303    entry: String,
304    text: Text,
305}
306
307/// `parse` reads the file of texts `path`, whose text is `text`, as a map
308/// from language tags to their entries, and refuses any other shape, a
309/// language that the file gives twice, an entry that sokf doesn't define, a
310/// placeholder that its entry doesn't define, and a template without the
311/// count or the name that its entry states.
312// sokf-implements: CONF-12_AC-4
313// sokf-implements: CONF-12_AC-5
314// sokf-implements: CONF-12_AC-8
315fn parse(path: &RepoPath, text: &str) -> Result<Vec<Parsed>> {
316    let fail = |line: usize, message: String| {
317        Error::config(path.clone(), format!("line {line}: {message}"))
318    };
319    let doc = yaml::parse(text, 1).map_err(|e| Error::config(path.clone(), e.to_string()))?;
320    if matches!(doc.value, Yaml::Null) {
321        return Ok(Vec::new());
322    }
323    let Some(languages) = doc.as_map() else {
324        return Err(fail(
325            doc.line,
326            "the file is no map from language tags to their texts".into(),
327        ));
328    };
329    let mut out = Vec::new();
330    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
331    for (tag, value) in languages {
332        if !is_language_tag(&tag.value) {
333            return Err(fail(
334                tag.line,
335                format!("`{}` is no language tag in the syntax of BCP 47", tag.value),
336            ));
337        }
338        // A tag counts without case, so `EN` repeats `en`.
339        if let Some(first) = seen.insert(tag.value.to_ascii_lowercase(), tag.line) {
340            return Err(fail(
341                tag.line,
342                format!(
343                    "`{}` gives the language of line {first} again; give each language once",
344                    tag.value
345                ),
346            ));
347        }
348        let mut push = |entry: String, text: Text| {
349            out.push(Parsed {
350                language: tag.value.to_ascii_lowercase(),
351                written: tag.value.clone(),
352                entry,
353                text,
354            });
355        };
356        for (key, value) in map_of(value, &tag.value, &fail)? {
357            match key.value.as_str() {
358                "description" => push(
359                    key.value.clone(),
360                    words(value, &key.value, &[], &[], &fail)?,
361                ),
362                "rule-unit" => push(
363                    key.value.clone(),
364                    words(value, &key.value, &["name", "unit"], &["name"], &fail)?,
365                ),
366                "limit" => {
367                    for (kind, value) in map_of(value, "limit", &fail)? {
368                        if !["hard", "soft", "ban"].contains(&kind.value.as_str()) {
369                            return Err(fail(
370                                kind.line,
371                                format!(
372                                    "`limit.{}` is no text of sokf's; `limit` holds `hard`, `soft`, and `ban`",
373                                    kind.value
374                                ),
375                            ));
376                        }
377                        let entry = format!("limit.{}", kind.value);
378                        // A ban states no count, so only a hard and a soft
379                        // limit need one.
380                        let needs: &[&str] = if kind.value == "ban" { &[] } else { &["count"] };
381                        let text = words(value, &entry, &["count", "unit"], needs, &fail)?;
382                        push(entry, text);
383                    }
384                }
385                "units" => {
386                    for (unit, value) in map_of(value, "units", &fail)? {
387                        if !UNITS.contains(&unit.value.as_str()) {
388                            let names: Vec<String> =
389                                UNITS.iter().map(|u| format!("`{u}`")).collect();
390                            return Err(fail(
391                                unit.line,
392                                format!(
393                                    "`units.{}` is no unit of sokf's; the units are {}",
394                                    unit.value,
395                                    and_list(&names)
396                                ),
397                            ));
398                        }
399                        let entry = format!("units.{}", unit.value);
400                        push(entry.clone(), forms(value, &entry, &fail)?);
401                    }
402                }
403                what @ ("labels" | "attribution") => labelled(value, what, &fail)?
404                    .into_iter()
405                    .for_each(|(entry, text)| push(entry, text)),
406                other => {
407                    return Err(fail(
408                        key.line,
409                        format!(
410                            "`{other}` is no text of sokf's; a language holds `attribution`, `description`, `labels`, `limit`, `rule-unit`, and `units`"
411                        ),
412                    ));
413                }
414            }
415        }
416    }
417    Ok(out)
418}
419
420/// `labelled` returns each entry `<what>.<label>` of `value`, the map of the
421/// entry `what`, `labels` or `attribution`, with its words. It refuses a
422/// label other than `human` and `agent`, and words of `labels` that no label
423/// could hold.
424fn labelled(
425    value: &Spanned,
426    what: &str,
427    fail: &dyn Fn(usize, String) -> Error,
428) -> Result<Vec<(String, Text)>> {
429    let mut out = Vec::new();
430    for (label, value) in map_of(value, what, fail)? {
431        if !LABELS.contains(&label.value.as_str()) {
432            return Err(fail(
433                label.line,
434                format!(
435                    "`{what}.{}` is no label of sokf's; the labels are `human` and `agent`",
436                    label.value
437                ),
438            ));
439        }
440        let entry = format!("{what}.{}", label.value);
441        let text = words(value, &entry, &[], &[], fail)?;
442        if what == "labels" {
443            label_words(&text, &entry, value.line, fail)?;
444        }
445        out.push((entry, text));
446    }
447    Ok(out)
448}
449
450/// `label_words` refuses the words `text` of the label `entry`, at `line`,
451/// where they are blank, hold a square bracket, or begin with `^`, because
452/// the engine reads such words as none and takes the key in their place.
453// sokf-implements: CONF-12_AC-9
454fn label_words(
455    text: &Text,
456    entry: &str,
457    line: usize,
458    fail: &dyn Fn(usize, String) -> Error,
459) -> Result<()> {
460    let Text::Words(w) = text else {
461        return Ok(());
462    };
463    let words = squash(w);
464    let fault = if words.is_empty() {
465        "are blank"
466    } else if words.contains(['[', ']']) {
467        "hold a square bracket"
468    } else if words.starts_with('^') {
469        "begin with `^`, which marks a footnote"
470    } else {
471        return Ok(());
472    };
473    Err(fail(
474        line,
475        format!("the words of `{entry}` {fault}, so no label could hold them"),
476    ))
477}
478
479/// `map_of` returns the entries of `value`, the value of `what`, and refuses
480/// a value that isn't a map.
481fn map_of<'v>(
482    value: &'v Spanned,
483    what: &str,
484    fail: &dyn Fn(usize, String) -> Error,
485) -> Result<&'v [(Spanned<String>, Spanned)]> {
486    value
487        .as_map()
488        .ok_or_else(|| fail(value.line, format!("`{what}` is no map")))
489}
490
491/// `words` returns the string `value` of the entry `entry`, and refuses a
492/// value that isn't a string, that holds a placeholder other than
493/// `allowed`, or that lacks a placeholder of `needs`.
494fn words(
495    value: &Spanned,
496    entry: &str,
497    allowed: &[&str],
498    needs: &[&str],
499    fail: &dyn Fn(usize, String) -> Error,
500) -> Result<Text> {
501    let Some(text) = value.as_str() else {
502        return Err(fail(value.line, format!("`{entry}` is no string")));
503    };
504    for name in placeholders(text) {
505        if !allowed.contains(&name) {
506            let takes = if allowed.is_empty() {
507                "takes no placeholder".to_string()
508            } else {
509                let names: Vec<String> = allowed.iter().map(|a| format!("`{{{a}}}`")).collect();
510                format!("takes {}", and_list(&names))
511            };
512            return Err(fail(
513                value.line,
514                format!("`{entry}` holds `{{{name}}}`, which is no placeholder of it; it {takes}"),
515            ));
516        }
517    }
518    if let Some(name) = needs.iter().find(|n| !placeholders(text).contains(n)) {
519        return Err(fail(
520            value.line,
521            format!("`{entry}` holds no `{{{name}}}`, which it needs"),
522        ));
523    }
524    Ok(Text::Words(text.to_string()))
525}
526
527/// `forms` returns the forms `one` and `other` of the unit `entry`, a map
528/// that holds the two strings. It ignores any other form, such as `few`.
529fn forms(value: &Spanned, entry: &str, fail: &dyn Fn(usize, String) -> Error) -> Result<Text> {
530    let shape = || {
531        fail(
532            value.line,
533            format!("`{entry}` is no map of the strings `one` and `other`"),
534        )
535    };
536    value.as_map().ok_or_else(shape)?;
537    let form = |name: &str| -> Result<String> {
538        let v = value.get(name).ok_or_else(shape)?;
539        match words(v, &format!("{entry}.{name}"), &[], &[], fail)? {
540            Text::Words(w) => Ok(w),
541            Text::Forms { .. } => Err(shape()),
542        }
543    };
544    Ok(Text::Forms {
545        one: form("one")?,
546        other: form("other")?,
547    })
548}
549
550/// `name_at` returns the name of the placeholder whose `{` stands just
551/// before `after`, and where its `}` lies in `after`, or `None` where no
552/// placeholder starts there. A name is one or more letters, digits, `-`,
553/// or `_`, so `{}` is text.
554fn name_at(after: &str) -> Option<(usize, &str)> {
555    let end = after.find('}')?;
556    let name = &after[..end];
557    (!name.is_empty()
558        && name
559            .chars()
560            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'))
561    .then_some((end, name))
562}
563
564/// `placeholders` returns the name of each placeholder `{name}` of `text`.
565pub(crate) fn placeholders(text: &str) -> Vec<&str> {
566    let mut out = Vec::new();
567    let mut rest = text;
568    while let Some(start) = rest.find('{') {
569        let after = &rest[start + 1..];
570        match name_at(after) {
571            Some((end, name)) => {
572                out.push(name);
573                rest = &after[end + 1..];
574            }
575            None => rest = after,
576        }
577    }
578    out
579}
580
581/// `fill_template` returns `template` with each placeholder `{name}` of `values`
582/// replaced by its value, in one pass, so that no value is read as a
583/// template.
584pub(crate) fn fill_template(template: &str, values: &[(&str, &str)]) -> String {
585    let mut out = String::new();
586    let mut rest = template;
587    while let Some(start) = rest.find('{') {
588        out.push_str(&rest[..start]);
589        let after = &rest[start + 1..];
590        let hit = name_at(after).and_then(|(end, name)| {
591            values
592                .iter()
593                .find(|(n, _)| *n == name)
594                .map(|(_, v)| (end, *v))
595        });
596        if let Some((end, value)) = hit {
597            out.push_str(value);
598            rest = &after[end + 1..];
599        } else {
600            out.push('{');
601            rest = after;
602        }
603    }
604    out.push_str(rest);
605    out
606}
607
608#[cfg(test)]
609mod tests;