1use 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
15const TEXTS_DIR: &str = ".sokf/texts.d";
18
19const ENGLISH: &str = include_str!("texts.yaml");
21
22pub(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
38pub(crate) const LABELS: [&str; 2] = ["human", "agent"];
41
42fn texts_path() -> RepoPath {
44 RepoPath::parse("/.sokf/texts.yaml").expect("literal")
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Text {
50 Words(String),
52 Forms {
55 one: String,
57 other: String,
59 },
60}
61
62#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct Texts {
66 entries: BTreeMap<(String, String), Text>,
67}
68
69impl Texts {
70 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 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 #[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 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 pub fn label(&self, language: &str, key: &str) -> Option<String> {
116 self.squashed(language, &format!("labels.{key}"))
117 }
118
119 pub fn attribution(&self, language: &str, key: &str) -> Option<String> {
123 self.squashed(language, &format!("attribution.{key}"))
124 }
125
126 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 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 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 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 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
210fn 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
223pub 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
233pub 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#[derive(Debug, Clone)]
300struct Parsed {
301 language: String,
302 written: String,
303 entry: String,
304 text: Text,
305}
306
307fn 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 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 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
420fn 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
450fn 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
479fn 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
491fn 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
527fn 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
550fn 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
564pub(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
581pub(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;