use crate::VmfBlock;
const MAX_WARNINGS: usize = 1000;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ParseCtx {
path: Vec<String>,
pub warnings: Vec<String>,
pub suppressed: usize,
}
impl ParseCtx {
pub(crate) fn enter(&mut self, segment: impl Into<String>) {
self.path.push(segment.into());
}
pub(crate) fn enter_indexed(&mut self, segment: &str, index: usize) {
self.path.push(format!("{}[{}]", segment, index));
}
pub(crate) fn leave(&mut self) {
self.path.pop();
}
pub(crate) fn warn(&mut self, msg: impl std::fmt::Display) {
if self.warnings.len() < MAX_WARNINGS {
self.warnings.push(format!("{}: {}", self.path.join("/"), msg));
} else {
self.suppressed += 1;
}
}
pub(crate) fn warn_missing(&mut self, key: &str, default: impl std::fmt::Display) {
self.warn(format!("missing '{}', using '{}'", key, default));
}
pub(crate) fn warn_unparsable(&mut self, key: &str, value: &str, default: impl std::fmt::Display) {
self.warn(format!(
"key '{}' has unparsable value '{}', using '{}'",
key, value, default
));
}
}
pub trait FromBlock: Sized {
fn from_block(block: VmfBlock, ctx: &mut ParseCtx) -> Self;
}
macro_rules! impl_try_from_block {
($($t:ty),* $(,)?) => {$(
impl TryFrom<$crate::VmfBlock> for $t {
type Error = $crate::VmfError;
fn try_from(block: $crate::VmfBlock) -> $crate::VmfResult<Self> {
let mut ctx = $crate::parse_ctx::ParseCtx::default();
Ok(<$t as $crate::parse_ctx::FromBlock>::from_block(block, &mut ctx))
}
}
)*};
}
pub(crate) use impl_try_from_block;