Skip to main content

source_vmf/
parser.rs

1//! This module provides the VMF parser implementation using the `source-kv` library.
2
3use indexmap::IndexMap;
4
5use crate::errors::VmfResult;
6use crate::parse_ctx::{FromBlock, ParseCtx};
7use crate::VmfBlock;
8use crate::prelude::{Cameras, Entity, VersionInfo, ViewSettings, VisGroups, VmfFile, World};
9use crate::vmf::regions::{Cordon, Cordons};
10
11/// Parses a VMF string into a `VmfFile` struct.
12///
13/// # Arguments
14///
15/// * `input` - The VMF string to parse.
16///
17/// # Returns
18///
19/// A `VmfResult` containing the parsed `VmfFile` or a `VmfError` if parsing fails.
20pub fn parse_vmf(input: &str) -> VmfResult<VmfFile> {
21    let mut deserializer = source_kv::de::Deserializer::from_str(input);
22    let root = deserializer.parse_root()?;
23
24    let mut vmf_file = VmfFile::default();
25    let mut ctx = ParseCtx::default();
26
27    if let source_kv::de::Value::Obj(map) = root {
28        for (name, values) in map {
29            for value in values {
30                let block = value_to_vmf_block(name.clone(), value);
31                // Block names are case-insensitive, like every other KeyValues name.
32                let kind = block.name.to_ascii_lowercase();
33                match kind.as_str() {
34                    // -- metadatas
35                    "versioninfo" => vmf_file.versioninfo = VersionInfo::from_block(block, &mut ctx),
36                    "visgroups" => vmf_file.visgroups = VisGroups::from_block(block, &mut ctx),
37                    "viewsettings" => vmf_file.viewsettings = ViewSettings::from_block(block, &mut ctx),
38
39                    // world
40                    "world" => vmf_file.world = World::from_block(block, &mut ctx),
41
42                    // -- entities
43                    "entity" => {
44                        ctx.enter_indexed("entity", vmf_file.entities.len());
45                        let ent = Entity::from_block(block, &mut ctx);
46                        ctx.leave();
47                        vmf_file.entities.push(ent);
48                    }
49                    "hidden" => {
50                        // Read all entities enclosed in the hidden block
51                        for inner in block.blocks {
52                            ctx.enter_indexed("hidden", vmf_file.hiddens.len());
53                            let mut ent = Entity::from_block(inner, &mut ctx);
54                            ctx.leave();
55                            ent.is_hidden = true;
56                            vmf_file.hiddens.push(ent)
57                        }
58                    }
59
60                    // -- regions
61                    "cameras" => vmf_file.cameras = Cameras::from_block(block, &mut ctx),
62                    "cordons" => vmf_file.cordons = Cordons::from_block(block, &mut ctx),
63                    // for old version of VMF
64                    "cordon" => {
65                        ctx.enter("cordon");
66                        let cordon = Cordon::from_block(block, &mut ctx);
67                        ctx.leave();
68                        vmf_file.cordons.push(cordon);
69                    }
70                    _ => {
71                        ctx.warn(format!("unexpected root block '{}', kept as-is", block.name));
72                        vmf_file.extra_blocks.push(block);
73                    }
74                }
75            }
76        }
77    }
78
79    vmf_file.warnings = ctx.warnings;
80    vmf_file.suppressed_warnings = ctx.suppressed;
81    Ok(vmf_file)
82}
83
84/// Converts a `source_kv::de::Value` into a `VmfBlock`.
85fn value_to_vmf_block(name: String, value: source_kv::de::Value) -> VmfBlock {
86    match value {
87        source_kv::de::Value::Str(s) => {
88            let mut key_values = IndexMap::with_capacity(1);
89            key_values.insert(name.clone(), s);
90            VmfBlock {
91                name,
92                key_values,
93                blocks: Vec::new(),
94            }
95        }
96        source_kv::de::Value::Obj(map) => {
97            let mut key_values = IndexMap::with_capacity(map.len());
98            let mut blocks = Vec::with_capacity(map.len() / 4); // heuristics
99
100            for (key, mut values) in map {
101                if values.len() == 1 {
102                    let val = values.pop().unwrap();
103                    match val {
104                        source_kv::de::Value::Str(s) => {
105                            key_values.insert(key, s);
106                        }
107                        source_kv::de::Value::Obj(_) => {
108                            blocks.push(value_to_vmf_block(key, val));
109                        }
110                    }
111                } else {
112                    // Repeated keys: string values are joined with '\r', while blocks become separate children
113                    for val in values {
114                        match val {
115                            source_kv::de::Value::Str(s) => {
116                                key_values
117                                    .entry(key.clone())
118                                    .and_modify(|existing: &mut String| {
119                                        existing.push('\r');
120                                        existing.push_str(&s);
121                                    })
122                                    .or_insert(s);
123                            }
124                            source_kv::de::Value::Obj(_) => {
125                                blocks.push(value_to_vmf_block(key.clone(), val));
126                            }
127                        }
128                    }
129                }
130            }
131            VmfBlock {
132                name,
133                key_values,
134                blocks,
135            }
136        }
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    
144    #[test]
145    fn parse_block_valid_block() {
146        let input = "entity { \"classname\" \"logic_relay\" }";
147        let mut deserializer = source_kv::de::Deserializer::from_str(input);
148        let root = deserializer.parse_root().unwrap();
149        
150        if let source_kv::de::Value::Obj(map) = root {
151            let (name, mut values) = map.into_iter().next().unwrap();
152            let block = value_to_vmf_block(name, values.remove(0));
153            
154            assert_eq!(block.name, "entity");
155            assert_eq!(
156                block.key_values.get("classname"),
157                Some(&"logic_relay".to_string())
158            );
159            assert!(block.blocks.is_empty());
160        } else {
161            panic!("Expected Obj");
162        }
163    }
164
165    #[test]
166    fn parse_block_nested_blocks() {
167        let input = "entity { \"classname\" \"logic_relay\" solid { \"id\" \"1\" } }";
168        let mut deserializer = source_kv::de::Deserializer::from_str(input);
169        let root = deserializer.parse_root().unwrap();
170
171        if let source_kv::de::Value::Obj(map) = root {
172            let (name, mut values) = map.into_iter().next().unwrap();
173            let block = value_to_vmf_block(name, values.remove(0));
174
175            assert_eq!(block.name, "entity");
176            assert_eq!(
177                block.key_values.get("classname"),
178                Some(&"logic_relay".to_string())
179            );
180            assert_eq!(block.blocks.len(), 1);
181            assert_eq!(block.blocks[0].name, "solid");
182            assert_eq!(block.blocks[0].key_values.get("id"), Some(&"1".to_string()));
183        } else {
184            panic!("Expected Obj");
185        }
186    }
187
188    #[test]
189    fn parse_block_empty_block() {
190        let input = "entity { }";
191        let mut deserializer = source_kv::de::Deserializer::from_str(input);
192        let root = deserializer.parse_root().unwrap();
193
194        if let source_kv::de::Value::Obj(map) = root {
195            let (name, mut values) = map.into_iter().next().unwrap();
196            let block = value_to_vmf_block(name, values.remove(0));
197
198            assert_eq!(block.name, "entity");
199            assert!(block.key_values.is_empty());
200            assert!(block.blocks.is_empty());
201        } else {
202            panic!("Expected Obj");
203        }
204    }
205}