1use std::collections::BTreeMap;
7use std::fmt::Display;
8
9use crate::names::folded;
10use crate::path::Path;
11use crate::problems::{Kind, Problems};
12use crate::raw::{Raw, RawKey};
13use crate::variant::Variant;
14
15macro_rules! replaced {
17 () => {
18 fn overlay(
19 &mut self,
20 raw: &Raw,
21 path: &Path,
22 problems: &mut Problems,
23 ) -> Result<(), Unbuilt> {
24 *self = Self::read(raw, path, problems)?;
25 Ok(())
26 }
27 };
28}
29
30macro_rules! sampled {
32 ($sample:expr) => {
33 fn sample() -> Option<Self> {
34 $sample
35 }
36 };
37}
38
39pub(crate) use replaced;
40pub(crate) use sampled;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct Unbuilt;
45
46pub trait Node {
51 fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt>
53 where
54 Self: Sized;
55
56 fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt>;
59
60 fn shape(&self) -> Shape<'_>;
62
63 fn variants(&self) -> Vec<Variant> {
66 Vec::new()
67 }
68
69 fn empty() -> Option<Self>
72 where
73 Self: Sized,
74 {
75 None
76 }
77
78 fn sample() -> Option<Self>
80 where
81 Self: Sized,
82 {
83 Self::empty()
84 }
85
86 fn fill(&mut self) {}
89
90 fn check(&self, path: &Path, problems: &mut Problems) {
92 check_children!(self, path, problems);
93 }
94}
95
96pub fn check_inner(node: &dyn Node, path: &Path, problems: &mut Problems) {
99 check_children!(node, path, problems);
100}
101
102macro_rules! check_children {
104 ($node:expr, $path:expr, $problems:expr) => {
105 match $node.shape() {
106 Shape::Scalar(_) | Shape::Optional(None) => {}
107 Shape::Optional(Some(inner)) => inner.check($path, $problems),
108 Shape::Section(fields) => {
109 for field in fields {
110 field.node.check(&$path.field(field.name), $problems);
111 }
112 }
113 Shape::Sequence(items) => {
114 for (index, item) in items.into_iter().enumerate() {
115 item.check(&$path.index(index), $problems);
116 }
117 }
118 Shape::Dictionary(entries) => {
119 for (key, value) in entries {
120 value.check(&$path.field(key), $problems);
121 }
122 }
123 }
124 };
125}
126
127use check_children;
128
129pub enum Shape<'a> {
131 Scalar(String),
133 Optional(Option<&'a dyn Node>),
135 Section(Vec<Field<'a>>),
137 Sequence(Vec<&'a dyn Node>),
139 Dictionary(Vec<(&'a str, &'a dyn Node)>),
141}
142
143pub struct Field<'a> {
145 pub name: &'static str,
147 pub doc: &'static str,
149 pub obsolete: Option<&'static str>,
151 pub required: bool,
153 pub node: &'a dyn Node,
155}
156
157pub fn section_entries<'a>(
159 raw: &'a Raw,
160 path: &Path,
161 problems: &mut Problems,
162) -> Option<&'a [(RawKey, Raw)]> {
163 match raw.entries() {
164 Some(entries) => Some(entries),
165 None => {
166 wrong_shape(raw, path, problems, "a section");
167 None
168 }
169 }
170}
171
172pub fn deprecated_field(problems: &mut Problems, key: &RawKey, path: &Path, note: &str) {
174 let name = key.text();
175 let message = if note.is_empty() {
176 format!("deprecated name {name:?}")
177 } else {
178 format!("deprecated name {name:?}: {note}")
179 };
180 problems.warning(Kind::Obsolete, key.mark(), path.clone(), message);
181}
182
183pub fn required_is_missing(problems: &mut Problems, path: &Path, doc: &str) {
186 problems.error(
187 Kind::Validation,
188 &crate::mark::Mark::Model,
189 path.clone(),
190 format!("the field is required, but the value is not set — {doc}"),
191 );
192}
193
194pub fn read_enum<T>(
197 raw: &Raw,
198 path: &Path,
199 problems: &mut Problems,
200 variants: &'static [&'static str],
201 variant: impl FnOnce(&str) -> Option<T>,
202) -> Result<T, Unbuilt> {
203 read_scalar(raw, path, problems, "a value of the enumeration", |text| {
204 let read = folded(text);
205 variant(&read)
206 .ok_or_else(|| format!("unknown value; possible values: {}", variants.join(", ")))
207 })
208}
209
210pub(crate) fn read_scalar<T, E>(
212 raw: &Raw,
213 path: &Path,
214 problems: &mut Problems,
215 what: &str,
216 parse: impl FnOnce(&str) -> Result<T, E>,
217) -> Result<T, Unbuilt>
218where
219 E: Display,
220{
221 let Some(text) = raw.text() else {
222 return Err(wrong_shape(raw, path, problems, what));
223 };
224 match parse(text) {
225 Ok(value) => Ok(value),
226 Err(error) => {
227 problems.error(
228 Kind::InvalidValue,
229 raw.mark(),
230 path.clone(),
231 format!("{text:?} is not {what}: {error}"),
232 );
233 Err(Unbuilt)
234 }
235 }
236}
237
238pub(crate) fn wrong_shape(
240 raw: &Raw,
241 path: &Path,
242 problems: &mut Problems,
243 expected: &str,
244) -> Unbuilt {
245 let got = raw.describe();
246 problems.error(
247 Kind::InvalidValue,
248 raw.mark(),
249 path.clone(),
250 format!("expected {expected}, got {got}"),
251 );
252 Unbuilt
253}
254
255impl<T: Node> Node for Option<T> {
256 fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
257 if raw.is_null() {
258 return Ok(None);
259 }
260 T::read(raw, path, problems).map(Some)
261 }
262
263 fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt> {
264 if raw.is_null() {
265 *self = None;
266 return Ok(());
267 }
268 match self {
270 Some(inner) => T::overlay(inner, raw, path, problems),
271 None => {
272 *self = Some(T::read(raw, path, problems)?);
273 Ok(())
274 }
275 }
276 }
277
278 fn shape(&self) -> Shape<'_> {
279 Shape::Optional(self.as_ref().map(|inner| inner as &dyn Node))
280 }
281
282 fn variants(&self) -> Vec<Variant> {
283 match self {
284 Some(inner) => inner.variants(),
285 None => T::sample().map_or_else(Vec::new, |sample| sample.variants()),
288 }
289 }
290
291 fn fill(&mut self) {
292 if self.is_none()
293 && let Some(empty) = T::empty()
294 {
295 *self = Some(empty);
296 }
297 if let Some(inner) = self {
298 inner.fill();
299 }
300 }
301}
302
303impl<T: Node> Node for Vec<T> {
304 fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
305 let mut value = Vec::new();
306 Self::overlay(&mut value, raw, path, problems)?;
307 Ok(value)
308 }
309
310 fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt> {
311 if raw.is_empty() {
312 self.clear();
313 return Ok(());
314 }
315 if let Some(items) = raw.items() {
316 *self = read_items(items, path, problems);
317 return Ok(());
318 }
319 if raw.entries().is_some() {
320 return overlay_items(self, raw, path, problems);
321 }
322 Err(wrong_shape(raw, path, problems, "a sequence"))
323 }
324
325 fn shape(&self) -> Shape<'_> {
326 Shape::Sequence(self.iter().map(|item| item as &dyn Node).collect())
327 }
328
329 fn empty() -> Option<Self> {
330 Some(Vec::new())
331 }
332
333 fn fill(&mut self) {
334 if self.is_empty()
336 && let Some(sample) = T::sample()
337 {
338 self.push(sample);
339 if let Some(sample) = T::sample() {
340 self.push(sample);
341 }
342 }
343 for item in self.iter_mut() {
344 item.fill();
345 }
346 }
347}
348
349fn read_items<T: Node>(items: &[Raw], path: &Path, problems: &mut Problems) -> Vec<T> {
351 let mut value = Vec::with_capacity(items.len());
352 for (index, item) in items.iter().enumerate() {
353 if let Ok(element) = T::read(item, &path.index(index), problems) {
354 value.push(element);
355 }
356 }
357 value
358}
359
360fn overlay_items<T: Node>(
363 value: &mut Vec<T>,
364 raw: &Raw,
365 path: &Path,
366 problems: &mut Problems,
367) -> Result<(), Unbuilt> {
368 let entries = raw.entries().unwrap_or_default();
369 let mut patches: Vec<(usize, &Raw)> = Vec::with_capacity(entries.len());
370 for (key, item) in entries {
371 match key.text().parse::<usize>() {
372 Ok(index) => patches.push((index, item)),
373 Err(_) => {
374 let message = format!("expected an index of an element, got {:?}", key.text());
375 problems.error(Kind::InvalidValue, key.mark(), path.clone(), message);
376 return Err(Unbuilt);
377 }
378 }
379 }
380 patches.sort_by_key(|(index, _)| *index);
381 for (index, item) in patches {
382 let item_path = path.index(index);
383 if let Some(existing) = value.get_mut(index) {
384 T::overlay(existing, item, &item_path, problems).ok();
385 } else if value.len() == index {
386 if let Ok(element) = T::read(item, &item_path, problems) {
387 value.push(element);
388 }
389 } else {
390 let message =
391 "the element is out of turn: elements are numbered from 0 without gaps".to_owned();
392 problems.error(Kind::InvalidValue, item.mark(), item_path, message);
393 return Err(Unbuilt);
394 }
395 }
396 Ok(())
397}
398
399impl<T: Node> Node for BTreeMap<String, T> {
400 fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
401 let mut value = BTreeMap::new();
402 Self::overlay(&mut value, raw, path, problems)?;
403 Ok(value)
404 }
405
406 fn overlay(&mut self, raw: &Raw, path: &Path, problems: &mut Problems) -> Result<(), Unbuilt> {
407 if raw.is_empty() {
408 self.clear();
409 return Ok(());
410 }
411 let Some(entries) = raw.entries() else {
412 return Err(wrong_shape(raw, path, problems, "a mapping"));
413 };
414 if !raw.is_from_environment() {
416 self.clear();
417 }
418 for (key, item) in entries {
419 let item_path = path.field(key.text());
420 if key.text().is_empty() {
421 let message = "a dictionary key must not be empty".to_owned();
422 problems.error(Kind::InvalidValue, key.mark(), item_path, message);
423 continue;
424 }
425 if let Some(existing) = self.get_mut(key.text()) {
426 T::overlay(existing, item, &item_path, problems).ok();
427 } else if let Ok(element) = T::read(item, &item_path, problems) {
428 self.insert(key.text().to_owned(), element);
429 }
430 }
431 Ok(())
432 }
433
434 fn shape(&self) -> Shape<'_> {
435 Shape::Dictionary(
436 self.iter()
437 .map(|(key, value)| (key.as_str(), value as &dyn Node))
438 .collect(),
439 )
440 }
441
442 fn empty() -> Option<Self> {
443 Some(BTreeMap::new())
444 }
445
446 fn fill(&mut self) {
447 if self.is_empty() {
449 for key in ["key1", "key2"] {
450 if let Some(sample) = T::sample() {
451 self.insert(key.to_owned(), sample);
452 }
453 }
454 }
455 for value in self.values_mut() {
456 value.fill();
457 }
458 }
459}