tramlines_core/grammar/registry.rs
1//! The layered registry of line formats and the hole types they are
2//! written with (`TL_34` to `TL_41`): the schema, the host, the pack layer,
3//! and the shared layer.
4
5use std::{borrow::Cow, collections::BTreeMap};
6
7use saphyr::{Mapping, Scalar, Sequence, Yaml as SYaml, YamlEmitter};
8
9use super::{
10 Format, Grammar, RegexCache, TypeDef, TypeRegistry, format::lower_format, patch::merge_patch,
11 validate,
12};
13use crate::{Finding, Problem, RepoPath, Result, Spanned, Yaml, yaml};
14
15// sokf:begin format-source
16/// Where a registry entry comes from.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum FormatSource {
19 /// Defined by the tool itself: the built-in types.
20 BuiltIn,
21 /// The tool's embedded formats.
22 Embedded,
23 /// The host's layer, as a formats file the host reads.
24 Repo,
25 /// A formats file that the caller names, by its path as the caller
26 /// spells it.
27 File(String),
28 /// A schema's `formats`, by schema id.
29 Schema(String),
30 /// A formats file of the pack layer, by the name of its pack.
31 Pack(String),
32}
33// sokf:end format-source
34
35impl FormatSource {
36 /// The `source` value a printed registry carries.
37 pub fn label(&self) -> Cow<'_, str> {
38 match self {
39 FormatSource::BuiltIn => Cow::Borrowed("built-in"),
40 FormatSource::Embedded => Cow::Borrowed("embedded"),
41 FormatSource::Repo => Cow::Borrowed("repo"),
42 FormatSource::File(path) => Cow::Borrowed(path),
43 FormatSource::Schema(id) => Cow::Borrowed(id),
44 // sokf-implements: CORE-5_AC-15
45 FormatSource::Pack(name) => Cow::Owned(format!("pack:{name}")),
46 }
47 }
48}
49
50// sokf:begin format-registry
51/// A named set of formats, each with its source, and the hole types the
52/// layers declared.
53#[derive(Debug, Clone, Default)]
54pub struct FormatRegistry {
55 /// The entries, by name.
56 pub entries: BTreeMap<String, (Format, FormatSource)>,
57 /// The types the layers declared, the built-ins apart.
58 pub types: TypeRegistry,
59}
60// sokf:end format-registry
61
62// sokf:begin format-registry
63/// A format of the receiver of `layered` that no longer compiles against
64/// the types of the nearer layer, which `layered` leaves out.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct BrokenFormat {
67 /// The name of the format.
68 pub name: String,
69 /// Each type of the nearer layer that the format uses and that differs
70 /// from the farther one, in the order in which its holes name them.
71 pub types: Vec<String>,
72 /// Each reason, its message naming the format, its layer, and the
73 /// types.
74 pub problems: Vec<Problem>,
75}
76// sokf:end format-registry
77
78impl BrokenFormat {
79 /// The format `name` of the layer `source`, which `types` break, with
80 /// each reason of `said`. Each line of `said` lies in the file of the
81 /// format, which no finding lies on, so the line is dropped.
82 fn of(name: &str, source: &FormatSource, types: &[&str], said: Vec<(usize, Problem)>) -> Self {
83 Self::of_layers(name, source, types, &[], &RepoPath::root(), said)
84 }
85
86 /// As `of`, where the types `host` of the host's file `path` take part
87 /// beside `types`, each group in the order of the holes, and a group
88 /// that is empty goes unnamed.
89 fn of_layers(
90 name: &str,
91 source: &FormatSource,
92 types: &[&str],
93 host: &[&str],
94 path: &RepoPath,
95 said: Vec<(usize, Problem)>,
96 ) -> Self {
97 let group = |types: &[&str], whose: &str| {
98 let quoted: Vec<String> = types.iter().map(|t| format!("`{t}`")).collect();
99 let what = if quoted.len() == 1 { "type" } else { "types" };
100 format!("the {what} {} of {whose}", quoted.join(", "))
101 };
102 let mut groups = Vec::new();
103 if !types.is_empty() {
104 groups.push(group(types, "this layer"));
105 }
106 if !host.is_empty() {
107 groups.push(group(host, &format!("`{path}`")));
108 }
109 let prefix = format!(
110 "format `{name}`: the entry of the layer `{}` no longer compiles against {}: ",
111 source.label(),
112 groups.join(" and ")
113 );
114 BrokenFormat {
115 name: name.to_string(),
116 types: types.iter().chain(host).map(|t| (*t).to_string()).collect(),
117 problems: said.into_iter().map(|(_, p)| p.prefixed(&prefix)).collect(),
118 }
119 }
120
121 /// Each reason as an error finding on `path` at `line`.
122 // sokf:begin format-registry
123 pub fn findings(&self, path: &RepoPath, line: Option<usize>) -> Vec<Finding> {
124 // sokf:end format-registry
125 self.problems
126 .iter()
127 .map(|p| p.clone().error(path.clone(), line))
128 .collect()
129 }
130}
131
132impl FormatRegistry {
133 /// A host's embedded registry: the built-in types it adds, reserved as
134 /// the engine's are, then the formats file `text`, whose entries are
135 /// `embedded`. A file that does not read is a defect of the build.
136 // sokf:begin format-registry
137 pub fn from_text(
138 text: &str,
139 built_ins: &[(&str, &str)],
140 grammar: &Grammar,
141 regexes: &RegexCache,
142 ) -> Result<Self> {
143 // sokf:end format-registry
144 // sokf-implements: CORE-5_AC-9
145 let fail = |m: String| crate::Error::Internal(format!("embedded formats: {m}"));
146 // sokf-implements: CORE-5_AC-7
147 let base = FormatRegistry {
148 entries: BTreeMap::new(),
149 types: TypeRegistry::reserved(built_ins),
150 };
151 let root = yaml::parse(text, 1).map_err(|e| fail(e.to_string()))?;
152 let registry = root
153 .get("registry")
154 .ok_or_else(|| fail("no registry".into()))?;
155 let own = Self::from_yaml_at(
156 registry,
157 root.get("types"),
158 FormatSource::Embedded,
159 grammar,
160 regexes,
161 &RepoPath::root(),
162 Some(&base),
163 )
164 .map_err(|findings| {
165 fail(
166 findings
167 .iter()
168 .map(|f| f.message.clone())
169 .collect::<Vec<_>>()
170 .join("; "),
171 )
172 })?;
173 // The base holds no format, so no type of the file breaks one.
174 Ok(base.layered(&own).0)
175 }
176
177 /// Build a registry from a `registry` map with no types of its own,
178 /// validating each entry against grammar `format`. Findings are on `/`.
179 // sokf-implements: TL_34
180 // sokf-implements: TL_36
181 pub fn from_yaml(
182 registry: &Spanned,
183 source: FormatSource,
184 grammar: &Grammar,
185 regexes: &RegexCache,
186 ) -> std::result::Result<Self, Vec<Finding>> {
187 Self::from_yaml_at(
188 registry,
189 None,
190 source,
191 grammar,
192 regexes,
193 &RepoPath::root(),
194 None,
195 )
196 }
197
198 /// As `from_yaml`, with the layer's `types` map, findings on `path`,
199 /// and the farther layers in `base`: an entry declaring `patch` is
200 /// merged onto the same-named entry of `base` before it is checked
201 /// (grammar `format`), and every template compiles against the types of
202 /// `base` with this layer's on top.
203 // sokf-implements: TL_27
204 // sokf-implements: CORE-5_AC-1
205 // sokf-implements: CORE-5_AC-2
206 // sokf-implements: TL_35
207 // sokf:begin format-registry
208 pub fn from_yaml_at(
209 registry: &Spanned,
210 types: Option<&Spanned>,
211 source: FormatSource,
212 grammar: &Grammar,
213 regexes: &RegexCache,
214 path: &RepoPath,
215 base: Option<&FormatRegistry>,
216 ) -> std::result::Result<Self, Vec<Finding>> {
217 // sokf:end format-registry
218 let (out, findings) = Self::layer(registry, types, source, grammar, regexes, path, base);
219 if findings.is_empty() {
220 Ok(out)
221 } else {
222 Err(findings)
223 }
224 }
225
226 /// As `from_yaml_at`, keeping what loads beside the findings of what
227 /// does not: each type and format that fails is reported once, and
228 /// what uses it reports nothing more. A type that fails stands as one
229 /// that matches anything, so a template that names it still compiles;
230 /// a format that fails is left out.
231 // sokf-implements: TL_125
232 // sokf-implements: CORE-5_AC-12
233 // sokf:begin format-registry
234 #[expect(
235 clippy::needless_pass_by_value,
236 reason = "a public signature of a published crate"
237 )]
238 pub fn layer(
239 registry: &Spanned,
240 types: Option<&Spanned>,
241 source: FormatSource,
242 grammar: &Grammar,
243 regexes: &RegexCache,
244 path: &RepoPath,
245 base: Option<&FormatRegistry>,
246 ) -> (Self, Vec<Finding>) {
247 // sokf:end format-registry
248 let fail = |line: usize, problem: Problem| problem.error(path.clone(), Some(line));
249 let mut findings = Vec::new();
250 let below = base.map(|b| b.types.clone()).unwrap_or_default();
251 let own_types = match types {
252 Some(node) => {
253 // sokf-implements: CORE-5_AC-8
254 let (mut own, problems) = TypeRegistry::from_yaml(node, &source, &below);
255 findings.extend(problems.into_iter().map(|(l, m)| fail(l, m)));
256 let failed = node
257 .as_map()
258 .unwrap_or(&[])
259 .iter()
260 .map(|(name, _)| &name.value)
261 .filter(|name| !own.entries.contains_key(*name) && !below.reserves(name));
262 for name in failed.collect::<Vec<_>>() {
263 own.entries
264 .insert(name.clone(), (TypeDef::Regex(".*?".into()), source.clone()));
265 }
266 own
267 }
268 None => TypeRegistry::default(),
269 };
270 let seen = TypeRegistry::built_ins()
271 .layered(&below)
272 .layered(&own_types);
273 // A layer's registry carries its own types alone; the farther
274 // layers' come back when it is layered on them.
275 let mut out = FormatRegistry {
276 entries: BTreeMap::new(),
277 types: own_types,
278 };
279 // sokf-implements: CORE-5_AC-5
280 let Some(entries) = registry.as_map() else {
281 findings.push(fail(
282 registry.line,
283 Problem::new("TL_101", "the format registry must be a map of formats"),
284 ));
285 return (out, findings);
286 };
287 for (name, whole) in entries {
288 // A patch says how it differs from the entry it shadows, so it
289 // is merged first and checked as the entry it becomes.
290 // sokf-implements: CORE-5_AC-3
291 // sokf-implements: TL_37
292 // sokf-implements: TL_41
293 let merged;
294 let entry = if whole.get("patch").and_then(Spanned::as_bool) == Some(true) {
295 if let Some((f, _)) = base.and_then(|b| b.entries.get(&name.value)) {
296 merged = merge_patch(&f.raw, whole);
297 &merged
298 } else {
299 findings.push(fail(
300 whole.line,
301 Problem::new(
302 "TL_41",
303 format!("format `{}` patches no farther entry", name.value),
304 ),
305 ));
306 continue;
307 }
308 } else {
309 whole
310 };
311 // sokf-implements: CORE-5_AC-4
312 let mut problems =
313 validate::validate_map(entry, "format", grammar, regexes, path, None);
314 if problems.is_empty() {
315 match lower_format(entry, &seen, regexes) {
316 Ok(mut format) => {
317 format.patched = !std::ptr::eq(entry, whole);
318 out.entries
319 .insert(name.value.clone(), (format, source.clone()));
320 continue;
321 }
322 Err(said) => problems.extend(said.into_iter().map(|(l, m)| fail(l, m))),
323 }
324 }
325 // sokf-implements: CORE-5_AC-6
326 for p in &mut problems {
327 p.message = format!("format `{}`: {}", name.value, p.message);
328 }
329 findings.extend(problems);
330 }
331 (out, findings)
332 }
333
334 /// The types a schema under this registry sees: the built-ins, then
335 /// the layers' own.
336 pub fn types_seen(&self) -> TypeRegistry {
337 TypeRegistry::built_ins().layered(&self.types)
338 }
339
340 /// This registry with `over` on top, and each format of this registry
341 /// that no longer compiles against the types of `over`: a same-named
342 /// entry of `over` replaces this one whole, and a same-named type
343 /// likewise. An entry of `over` that declared a patch was merged onto
344 /// the farther one when it was built. Where `over` declares a type that
345 /// differs from this registry's, each entry that uses it is compiled
346 /// again against it, so a type means one thing to every format a schema
347 /// sees, and an entry that no longer compiles is left out, so the engine
348 /// checks no line against its old compile.
349 // sokf-implements: TL_34
350 // sokf-implements: TL_36
351 // sokf:begin format-registry
352 // sokf-implements: TL_51
353 pub fn layered(&self, over: &FormatRegistry) -> (FormatRegistry, Vec<BrokenFormat>) {
354 // sokf:end format-registry
355 let types = self.types.layered(&over.types);
356 let seen = TypeRegistry::built_ins().layered(&types);
357 let regexes = RegexCache::new();
358 let mut entries = self.entries.clone();
359 let mut broken = Vec::new();
360 // sokf-implements: CORE-5_AC-11
361 // Only a type this registry defines otherwise can change one of its
362 // formats: a new name is one no farther template uses, and the same
363 // value compiles to the same format.
364 let changed: Vec<&str> = over
365 .types
366 .entries
367 .iter()
368 .filter(|(n, (def, _))| self.types.get(n).is_some_and(|d| d != def))
369 .map(|(n, _)| n.as_str())
370 .collect();
371 if !changed.is_empty() {
372 entries.retain(|name, (format, source)| {
373 // An entry that `over` replaces is one that no schema sees.
374 if over.entries.contains_key(name) {
375 return true;
376 }
377 let used = format.uses(&changed);
378 if used.is_empty() {
379 return true;
380 }
381 match lower_format(&format.raw, &seen, ®exes) {
382 Ok(mut again) => {
383 again.patched = format.patched;
384 *format = again;
385 true
386 }
387 // sokf-implements: TL_140
388 // sokf-implements: CORE-5_AC-17
389 Err(said) => {
390 broken.push(BrokenFormat::of(name, source, &used, said));
391 false
392 }
393 }
394 });
395 }
396 // sokf-implements: CORE-5_AC-10
397 for (name, entry) in &over.entries {
398 entries.insert(name.clone(), entry.clone());
399 }
400 (FormatRegistry { entries, types }, broken)
401 }
402
403 /// This registry, the shared layer, with the pack layer on top: the
404 /// entries and the types of `files`, each a formats file of the layer
405 /// built with `layer` on this registry with the source
406 /// `FormatSource::Pack`. The files are read in the order of their
407 /// paths, whatever order the caller gives, so no entry patches another
408 /// file's; where two files define one name, the entry of the first
409 /// stands, and the layer keeps the clash for `PackLayer::with_host`.
410 /// Each format that uses a type of the layer is compiled again against
411 /// it, so a type means one thing to every format that a schema sees. A
412 /// format of a file that no longer compiles is left out and reported on
413 /// that file. A format of this registry that no longer compiles stays
414 /// as this registry compiled it, for the host's layer to settle, and
415 /// `PackLayer::with_host` reports it where the host's layer leaves it
416 /// broken.
417 // sokf-implements: TL_34
418 // sokf-implements: TL_27
419 // sokf-implements: CORE-5_AC-13
420 // sokf:begin format-registry
421 pub fn with_packs(&self, files: &[(RepoPath, FormatRegistry)]) -> PackLayer {
422 // sokf:end format-registry
423 let mut files: Vec<&(RepoPath, FormatRegistry)> = files.iter().collect();
424 files.sort_by(|a, b| a.0.cmp(&b.0));
425 let mut packs = FormatRegistry::default();
426 let mut origin: BTreeMap<&str, &RepoPath> = BTreeMap::new();
427 let mut type_origin: BTreeMap<&str, &RepoPath> = BTreeMap::new();
428 let mut clashes = Vec::new();
429 for (path, file) in files.iter().copied() {
430 for (name, entry) in &file.entries {
431 if let Some(first) = origin.get(name.as_str()) {
432 clashes.push(Clash {
433 what: "format",
434 name: name.clone(),
435 first: (*first).clone(),
436 later: path.clone(),
437 line: Some(entry.0.raw.line),
438 });
439 } else {
440 origin.insert(name, path);
441 packs.entries.insert(name.clone(), entry.clone());
442 }
443 }
444 for (name, def) in &file.types.entries {
445 if let Some(first) = type_origin.get(name.as_str()) {
446 clashes.push(Clash {
447 what: "type",
448 name: name.clone(),
449 first: (*first).clone(),
450 later: path.clone(),
451 line: None,
452 });
453 } else {
454 type_origin.insert(name, path);
455 packs.types.entries.insert(name.clone(), def.clone());
456 }
457 }
458 }
459 // A file's formats were compiled against its own types, and a
460 // type of another file can stand in their place.
461 let names: Vec<&str> = packs.types.entries.keys().map(String::as_str).collect();
462 let seen = self.types_seen().layered(&packs.types);
463 let regexes = RegexCache::new();
464 let mut findings = Vec::new();
465 let mut again: Vec<(String, Option<Format>)> = Vec::new();
466 for (name, (format, _)) in &packs.entries {
467 if !format.uses_any(&names) {
468 continue;
469 }
470 // sokf-implements: TL_134
471 // sokf-implements: CORE-5_AC-16
472 match lower_format(&format.raw, &seen, ®exes) {
473 Ok(mut lowered) => {
474 lowered.patched = format.patched;
475 again.push((name.clone(), Some(lowered)));
476 }
477 Err(said) => {
478 let path = origin[name.as_str()];
479 findings.extend(said.into_iter().map(|(line, mut problem)| {
480 problem.message = format!("format `{name}`: {}", problem.message);
481 problem.error(path.clone(), Some(line))
482 }));
483 again.push((name.clone(), None));
484 }
485 }
486 }
487 let mut refused = Vec::new();
488 for (name, format) in again {
489 if let Some(format) = format {
490 if let Some(entry) = packs.entries.get_mut(&name) {
491 entry.0 = format;
492 }
493 } else {
494 packs.entries.remove(&name);
495 refused.push(name);
496 }
497 }
498 // A shared format that a type of the layer breaks stays as this
499 // registry compiled it, so that the host's layer can patch it, and
500 // `with_host` decides it once the host's types are known. Its
501 // findings, kept for a host that changes no type of the format, lie
502 // on the file of the first type that it uses and that the layer
503 // changes: every type of the layer has a file. The shared format of
504 // a name that a refused format of a file takes stays out, because
505 // that format has its finding already.
506 let (mut registry, broken) = self.layered(&packs);
507 let mut pending = BTreeMap::new();
508 for b in broken {
509 if refused.contains(&b.name) {
510 continue;
511 }
512 let entry = self.entries[&b.name].clone();
513 registry.entries.insert(b.name.clone(), entry);
514 let findings = b.findings(type_origin[b.types[0].as_str()], None);
515 pending.insert(b.name, findings);
516 }
517 PackLayer {
518 registry,
519 clashes,
520 findings,
521 shared_types: self.types.clone(),
522 pending,
523 type_origin: type_origin
524 .into_iter()
525 .map(|(name, path)| (name.to_string(), path.clone()))
526 .collect(),
527 }
528 }
529
530 /// The format named `name`.
531 // sokf:begin format-registry
532 pub fn get(&self, name: &str) -> Option<&Format> {
533 // sokf:end format-registry
534 self.entries.get(name).map(|(f, _)| f)
535 }
536
537 /// The registry as one YAML document in the shape of
538 /// a formats file, each type and entry carrying `source`. The
539 /// built-in types are printed where `built_ins` asks for them.
540 pub fn to_yaml(&self, built_ins: bool) -> String {
541 let types = if built_ins {
542 self.types_seen()
543 } else {
544 self.types.clone()
545 };
546 let mut type_map = Mapping::new();
547 for (name, (def, source)) in &types.entries {
548 let value = match def {
549 TypeDef::Regex(r) => ystr(r),
550 TypeDef::Choices(c) => SYaml::Sequence(c.iter().map(ystr).collect::<Sequence>()),
551 };
552 let mut entry = Mapping::new();
553 entry.insert(ystr("match"), value);
554 entry.insert(ystr("source"), ystr(source.label()));
555 type_map.insert(ystr(name), SYaml::Mapping(entry));
556 }
557 let mut registry = Mapping::new();
558 for (name, (format, source)) in &self.entries {
559 let mut entry = match to_saphyr(&format.raw) {
560 SYaml::Mapping(m) => m,
561 _ => Mapping::new(),
562 };
563 entry.insert(ystr("source"), ystr(source.label()));
564 registry.insert(ystr(name), SYaml::Mapping(entry));
565 }
566 let mut root = Mapping::new();
567 if !type_map.is_empty() {
568 root.insert(ystr("types"), SYaml::Mapping(type_map));
569 }
570 root.insert(ystr("registry"), SYaml::Mapping(registry));
571 let mut out = String::new();
572 let mut emitter = YamlEmitter::new(&mut out);
573 emitter.multiline_strings(true);
574 emitter
575 .dump(&SYaml::Mapping(root))
576 .expect("emitting to a string cannot fail");
577 out.push('\n');
578 out.strip_prefix("---\n").map(str::to_string).unwrap_or(out)
579 }
580}
581
582// sokf:begin format-registry
583/// The shared layer with the pack layer on top, which the host builds its
584/// own layer on, and what the pack layer reports once the host's layer is
585/// known.
586#[derive(Debug, Clone)]
587#[must_use = "`PackLayer::with_host` gives the registry and the findings of the pack layer"]
588pub struct PackLayer {
589 registry: FormatRegistry,
590 clashes: Vec<Clash>,
591 findings: Vec<Finding>,
592 /// The types of the shared layer, the built-ins apart.
593 shared_types: TypeRegistry,
594 /// Each shared format that a type of the layer breaks, which `registry`
595 /// holds as the shared layer compiled it, with its findings on the file
596 /// of the first such type.
597 pending: BTreeMap<String, Vec<Finding>>,
598 /// The first file of the layer that declares each type.
599 type_origin: BTreeMap<String, RepoPath>,
600}
601// sokf:end format-registry
602
603/// A format or a type that two files of the pack layer define: the first
604/// and the later file in the order of their paths, and the line of the
605/// later entry where the layer keeps one.
606#[derive(Debug, Clone)]
607struct Clash {
608 what: &'static str,
609 name: String,
610 first: RepoPath,
611 later: RepoPath,
612 line: Option<usize>,
613}
614
615impl PackLayer {
616 /// The shared layer with the pack layer on top, the base of the host's
617 /// own layer. It holds each shared format that a type of the layer
618 /// breaks as the shared layer compiled it, so that the host's layer can
619 /// patch it; a schema compiles against the registry of `with_host`.
620 // sokf-implements: CORE-5_AC-13
621 // sokf:begin format-registry
622 pub fn registry(&self) -> &FormatRegistry {
623 // sokf:end format-registry
624 &self.registry
625 }
626
627 /// The registry with `host`, the host's own layer built on `registry`
628 /// from the file `path`, on top, and the findings of the pack layer and
629 /// of `host`: each format of a file that does not compile against the
630 /// types of the layer, each format and type that two files define and
631 /// `host` does not define in full, each format of a file that no longer
632 /// compiles against a type of `host`, on `path`, and each shared format
633 /// that no longer compiles against the types of the registry. A patch
634 /// in `host` settles no clash, because it was merged onto the entry of
635 /// whichever file came first. A shared format that a type of the layer
636 /// breaks is settled where `host` defines the format, patches it, or
637 /// defines a type against which it compiles.
638 // sokf-implements: TL_128
639 // sokf-implements: CORE-5_AC-14
640 // sokf:begin format-registry
641 pub fn with_host(
642 &self,
643 host: &FormatRegistry,
644 path: &RepoPath,
645 ) -> (FormatRegistry, Vec<Finding>) {
646 // sokf:end format-registry
647 let settled = |c: &Clash| match c.what {
648 "format" => host.entries.get(&c.name).is_some_and(|(f, _)| !f.patched),
649 _ => host.types.entries.contains_key(&c.name),
650 };
651 // A shared format that a type of the layer broke is decided apart,
652 // so that it compiles once, against the types of the layer under
653 // `host`; `layered` decides every other format.
654 let mut base = self.registry.clone();
655 base.entries
656 .retain(|name, _| !self.pending.contains_key(name));
657 let (mut registry, broken) = base.layered(host);
658 let seen = registry.types_seen();
659 let regexes = RegexCache::new();
660 let mut of_packs = Vec::new();
661 for (name, said) in &self.pending {
662 // An entry of `host` replaces the format, or patches it.
663 if host.entries.contains_key(name) {
664 continue;
665 }
666 let (format, source) = &self.registry.entries[name];
667 let hosts = self.host_types(format, host);
668 // sokf-implements: TL_140
669 // sokf-implements: CORE-5_AC-18
670 if hosts.is_empty() {
671 of_packs.extend(said.iter().cloned());
672 continue;
673 }
674 // sokf-implements: CORE-5_AC-20
675 match lower_format(&format.raw, &seen, ®exes) {
676 Ok(mut again) => {
677 again.patched = format.patched;
678 registry
679 .entries
680 .insert(name.clone(), (again, source.clone()));
681 }
682 Err(said) => of_packs.extend(self.still_broken(name, host, &hosts, said, path)),
683 }
684 }
685 let mut findings = self.findings.clone();
686 findings.extend(of_packs);
687 findings.extend(self.clashes.iter().filter(|c| !settled(c)).map(|c| {
688 Problem::new(
689 "TL_128",
690 format!(
691 "{} `{}` is defined in both `{}` and `{}` of the pack layer; define it in full in the host's layer to choose one",
692 c.what, c.name, c.first, c.later
693 ),
694 )
695 .error(c.later.clone(), c.line)
696 }));
697 // sokf-implements: TL_140
698 // sokf-implements: CORE-5_AC-19
699 findings.extend(broken.iter().flat_map(|b| b.findings(path, None)));
700 (registry, findings)
701 }
702
703 /// Each type of `host` that `format` uses and that differs from the
704 /// type of the layer, in the order of the holes.
705 fn host_types<'h>(&self, format: &Format, host: &'h FormatRegistry) -> Vec<&'h str> {
706 let differ: Vec<&str> = host
707 .types
708 .entries
709 .iter()
710 .filter(|(n, (def, _))| self.registry.types.get(n) != Some(def))
711 .map(|(n, _)| n.as_str())
712 .collect();
713 format.uses(&differ)
714 }
715
716 /// The findings, for each reason of `said`, on the shared format `name`,
717 /// which a type of the layer broke and which the types `hosts` of the
718 /// host's layer `host`, of the file `path`, take part in and leave
719 /// broken. Each type that the format uses and that differs from the
720 /// shared one is named: one of `hosts` by `path`, and any other as a
721 /// type of the layer. The findings lie on the file of the first type of
722 /// the layer, because the layer broke the format first, or on `path`
723 /// where only `hosts` take part.
724 // sokf-implements: TL_140
725 // sokf-implements: CORE-5_AC-18
726 fn still_broken(
727 &self,
728 name: &str,
729 host: &FormatRegistry,
730 hosts: &[&str],
731 said: Vec<(usize, Problem)>,
732 path: &RepoPath,
733 ) -> Vec<Finding> {
734 let (format, source) = &self.registry.entries[name];
735 let differs = |n: &str| {
736 let now = if hosts.contains(&n) {
737 host.types.get(n)
738 } else {
739 self.registry.types.get(n)
740 };
741 now != self.shared_types.get(n)
742 };
743 let all: Vec<&str> = self
744 .registry
745 .types
746 .entries
747 .keys()
748 .map(String::as_str)
749 .collect();
750 let used: Vec<&str> = format
751 .uses(&all)
752 .into_iter()
753 .filter(|t| differs(t))
754 .collect();
755 let (of_host, of_packs): (Vec<&str>, Vec<&str>) =
756 used.iter().partition(|t| hosts.contains(t));
757 match of_packs.first().and_then(|t| self.type_origin.get(*t)) {
758 Some(file) => {
759 let mut broken =
760 BrokenFormat::of_layers(name, source, &of_packs, &of_host, path, said);
761 // The types in the order of the holes.
762 broken.types = used.iter().map(|t| (*t).to_string()).collect();
763 broken.findings(file, None)
764 }
765 None => BrokenFormat::of(name, source, &used, said).findings(path, None),
766 }
767 }
768}
769
770fn to_saphyr(node: &Spanned) -> SYaml<'static> {
771 match &node.value {
772 Yaml::Null => SYaml::Value(Scalar::Null),
773 Yaml::Bool(b) => SYaml::Value(Scalar::Boolean(*b)),
774 Yaml::Int(i) => SYaml::Value(Scalar::Integer(*i)),
775 Yaml::Float(f) => SYaml::Value(Scalar::FloatingPoint((*f).into())),
776 Yaml::Str(s) => ystr(s),
777 Yaml::Seq(items) => SYaml::Sequence(items.iter().map(to_saphyr).collect::<Sequence>()),
778 Yaml::Map(entries) => {
779 let mut m = Mapping::new();
780 for (k, v) in entries {
781 m.insert(ystr(&k.value), to_saphyr(v));
782 }
783 SYaml::Mapping(m)
784 }
785 }
786}
787
788/// A YAML string scalar of `s`.
789fn ystr(s: impl AsRef<str>) -> SYaml<'static> {
790 SYaml::Value(Scalar::String(s.as_ref().to_string().into()))
791}