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