Skip to main content

source_vmf/
parse_ctx.rs

1//! Parser context for recording non-fatal syntax warnings and defaults during VMF parsing.
2
3use crate::VmfBlock;
4
5/// Maximum number of warnings stored in [`ParseCtx`] before suppressing further entries.
6const MAX_WARNINGS: usize = 1000;
7
8/// Parsing context tracking the current block hierarchy and diagnostic warnings.
9#[derive(Debug, Default, Clone, PartialEq, Eq)]
10pub struct ParseCtx {
11    /// Path segments of the block being parsed, e.g. `["world", "solid[3]", "side[1]"]`.
12    path: Vec<String>,
13    /// Warnings recorded during parsing, prefixed with their block path.
14    pub warnings: Vec<String>,
15    /// Number of warnings suppressed after reaching [`MAX_WARNINGS`].
16    pub suppressed: usize,
17}
18
19impl ParseCtx {
20    /// Enters a nested block. Must be paired with [`ParseCtx::leave`].
21    pub(crate) fn enter(&mut self, segment: impl Into<String>) {
22        self.path.push(segment.into());
23    }
24
25    /// Enters the `index`-th nested block of a repeated kind, e.g. `side[2]`.
26    pub(crate) fn enter_indexed(&mut self, segment: &str, index: usize) {
27        self.path.push(format!("{}[{}]", segment, index));
28    }
29
30    /// Leaves the current block.
31    pub(crate) fn leave(&mut self) {
32        self.path.pop();
33    }
34
35    /// Records a problem at the current path, up to [`MAX_WARNINGS`].
36    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    /// Records a missing key that was replaced by `default`.
45    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    /// Records a value that could not be parsed and was replaced by `default`.
50    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
58/// Converts a [`VmfBlock`] into a typed structure, recording warnings in [`ParseCtx`].
59pub trait FromBlock: Sized {
60    /// Parses `block`, substituting defaults and logging warnings for missing or invalid values.
61    fn from_block(block: VmfBlock, ctx: &mut ParseCtx) -> Self;
62}
63
64/// Implements `TryFrom<VmfBlock>` for types implementing [`FromBlock`].
65macro_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;