1use crate::VmfBlock;
4
5const MAX_WARNINGS: usize = 1000;
7
8#[derive(Debug, Default, Clone, PartialEq, Eq)]
10pub struct ParseCtx {
11 path: Vec<String>,
13 pub warnings: Vec<String>,
15 pub suppressed: usize,
17}
18
19impl ParseCtx {
20 pub(crate) fn enter(&mut self, segment: impl Into<String>) {
22 self.path.push(segment.into());
23 }
24
25 pub(crate) fn enter_indexed(&mut self, segment: &str, index: usize) {
27 self.path.push(format!("{}[{}]", segment, index));
28 }
29
30 pub(crate) fn leave(&mut self) {
32 self.path.pop();
33 }
34
35 pub(crate) fn warn(&mut self, msg: impl std::fmt::Display) {
37 if self.warnings.len() < MAX_WARNINGS {
38 self.warnings.push(format!("{}: {}", self.path.join("/"), msg));
39 } else {
40 self.suppressed += 1;
41 }
42 }
43
44 pub(crate) fn warn_missing(&mut self, key: &str, default: impl std::fmt::Display) {
46 self.warn(format!("missing '{}', using '{}'", key, default));
47 }
48
49 pub(crate) fn warn_unparsable(&mut self, key: &str, value: &str, default: impl std::fmt::Display) {
51 self.warn(format!(
52 "key '{}' has unparsable value '{}', using '{}'",
53 key, value, default
54 ));
55 }
56}
57
58pub trait FromBlock: Sized {
60 fn from_block(block: VmfBlock, ctx: &mut ParseCtx) -> Self;
62}
63
64macro_rules! impl_try_from_block {
66 ($($t:ty),* $(,)?) => {$(
67 impl TryFrom<$crate::VmfBlock> for $t {
68 type Error = $crate::VmfError;
69
70 fn try_from(block: $crate::VmfBlock) -> $crate::VmfResult<Self> {
71 let mut ctx = $crate::parse_ctx::ParseCtx::default();
72 Ok(<$t as $crate::parse_ctx::FromBlock>::from_block(block, &mut ctx))
73 }
74 }
75 )*};
76}
77
78pub(crate) use impl_try_from_block;