use std::collections::HashMap;
use std::fs;
use std::path::Path;
use crate::error::{InfError, InfResult};
use crate::types::*;
struct BlockFrame {
name: String,
start_line: usize,
raw_lines: Vec<String>,
sub_blocks: HashMap<String, Vec<Block>>,
}
pub struct InfParser;
impl InfParser {
pub fn parse_file<P: AsRef<Path>>(path: P) -> InfResult<InfFile> {
let path = path.as_ref();
let content = fs::read_to_string(path)?;
let entries = Self::parse_str(&content)?;
Ok(InfFile {
path: path.to_string_lossy().to_string(),
entries,
})
}
pub fn parse_str(content: &str) -> InfResult<Vec<InfEntry>> {
let mut entries: Vec<InfEntry> = Vec::new();
let mut header_fields: HashMap<String, Vec<String>> = HashMap::new();
let mut current_entry: Option<CurrentEntry> = None;
let mut stack: Vec<BlockFrame> = Vec::new();
let mut line_no = 0usize;
for raw_line in content.lines() {
line_no += 1;
let trimmed = raw_line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some(top) = stack.last_mut() {
if trimmed == format!("{}={}", top.name, "end") {
let frame = stack.pop().unwrap();
let block = classify_frame(frame);
if let Some(parent) = stack.last_mut() {
let name = block.name.clone();
parent
.sub_blocks
.entry(name)
.or_default()
.push(block);
} else {
attach_block_to_entry(&mut current_entry, &mut entries, &mut header_fields, block, line_no)?;
}
} else if let Some(name) = strip_block_start(trimmed) {
stack.push(BlockFrame {
name,
start_line: line_no,
raw_lines: Vec::new(),
sub_blocks: HashMap::new(),
});
} else {
top.raw_lines.push(raw_line.to_string());
}
} else {
if let Some(name) = strip_block_start(trimmed) {
stack.push(BlockFrame {
name,
start_line: line_no,
raw_lines: Vec::new(),
sub_blocks: HashMap::new(),
});
} else if let Some(end_name) = strip_block_end(trimmed) {
return Err(InfError::UnmatchedBlock {
line: line_no,
block_type: end_name,
});
} else if let Some((key, value)) = parse_kv(trimmed) {
if key == "id" {
if let Some(ce) = current_entry.take() {
entries.push(ce.into_entry(line_no));
}
current_entry = Some(CurrentEntry::new(key, value));
} else if let Some(ce) = current_entry.as_mut() {
ce.fields.entry(key).or_default().push(value);
} else {
header_fields.entry(key).or_default().push(value);
}
}
}
}
if let Some(frame) = stack.last() {
return Err(InfError::UnmatchedBlock {
line: frame.start_line,
block_type: frame.name.clone(),
});
}
if let Some(ce) = current_entry.take() {
entries.push(ce.into_entry(line_no));
}
if !header_fields.is_empty() {
entries.push(InfEntry {
line: line_no,
fields: header_fields,
blocks: HashMap::new(),
});
}
Ok(entries)
}
}
struct CurrentEntry {
fields: HashMap<String, Vec<String>>,
blocks: HashMap<String, Vec<Block>>,
}
impl CurrentEntry {
fn new(key: String, value: String) -> Self {
let mut fields = HashMap::new();
fields.insert(key, vec![value]);
Self {
fields,
blocks: HashMap::new(),
}
}
fn into_entry(self, line: usize) -> InfEntry {
InfEntry {
line,
fields: self.fields,
blocks: self.blocks,
}
}
}
fn attach_block_to_entry(
current_entry: &mut Option<CurrentEntry>,
entries: &mut Vec<InfEntry>,
header_fields: &mut HashMap<String, Vec<String>>,
block: Block,
line_no: usize,
) -> InfResult<()> {
let name = block.name.clone();
if let Some(ce) = current_entry.as_mut() {
ce.blocks.entry(name).or_default().push(block);
} else {
let fields = std::mem::take(header_fields);
let mut blocks = HashMap::new();
blocks.insert(name, vec![block]);
entries.push(InfEntry {
line: line_no,
fields,
blocks,
});
}
Ok(())
}
fn strip_block_start(line: &str) -> Option<String> {
let line = line.trim();
let eq_pos = line.find('=')?;
let key = line[..eq_pos].trim();
let value = line[eq_pos + 1..].trim();
if value == "start" && !key.is_empty() {
Some(key.to_string())
} else {
None
}
}
fn strip_block_end(line: &str) -> Option<String> {
let line = line.trim();
let eq_pos = line.find('=')?;
let key = line[..eq_pos].trim();
let value = line[eq_pos + 1..].trim();
if value == "end" && !key.is_empty() {
Some(key.to_string())
} else {
None
}
}
fn classify_frame(frame: BlockFrame) -> Block {
let name = frame.name;
let (all_kv, fields) = try_parse_all_kv(&frame.raw_lines);
if all_kv || frame.raw_lines.is_empty() {
Block {
name,
content: BlockContent::Structured {
fields,
blocks: frame.sub_blocks,
},
}
} else {
Block {
name,
content: BlockContent::Text(frame.raw_lines.join("\n")),
}
}
}
fn try_parse_all_kv(lines: &[String]) -> (bool, HashMap<String, Vec<String>>) {
let mut fields: HashMap<String, Vec<String>> = HashMap::new();
for raw in lines {
let trimmed = raw.trim();
if trimmed.is_empty() {
continue;
}
match parse_kv(trimmed) {
Some((key, value)) => {
fields.entry(key).or_default().push(value);
}
None => return (false, HashMap::new()),
}
}
(true, fields)
}
fn parse_kv(line: &str) -> Option<(String, String)> {
let line = line.trim();
let line = if let Some(pos) = line.find(" //") {
&line[..pos]
} else if let Some(pos) = line.find("\t//") {
&line[..pos]
} else {
line
};
let mut parts = line.splitn(2, '=');
let key = parts.next()?.trim();
let value = parts.next()?.trim();
if key.is_empty() {
return None;
}
Some((key.to_string(), value.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_single_entry() {
let input = r#"id=9
name=Meat
group=food
weight=500"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].fields.get("id").unwrap()[0], "9");
assert_eq!(entries[0].fields.get("name").unwrap()[0], "Meat");
assert!(entries[0].blocks.is_empty());
}
#[test]
fn test_multiple_entries() {
let input = r#"id=1
name=First
weight=100
id=2
name=Second
weight=200"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].fields.get("id").unwrap()[0], "1");
assert_eq!(entries[1].fields.get("id").unwrap()[0], "2");
}
#[test]
fn test_multivalue_keys() {
let input = r#"id=5
find=15,20,3
find=10
find=30,1"#;
let entries = InfParser::parse_str(input).unwrap();
let finds = entries[0].fields.get("find").unwrap();
assert_eq!(finds.len(), 3);
assert_eq!(finds[0], "15,20,3");
assert_eq!(finds[1], "10");
assert_eq!(finds[2], "30,1");
}
#[test]
fn test_script_block_text() {
let input = r#"id=9
name=Meat
script=start
on:eat {
eat 5,20,10,0;
}
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let scripts = entries[0].blocks.get("script").unwrap();
assert_eq!(scripts.len(), 1);
match &scripts[0].content {
BlockContent::Text(t) => {
assert!(t.contains("on:eat"));
assert!(t.contains("eat 5,20,10,0"));
}
_ => panic!("expected Text"),
}
}
#[test]
fn test_combi_block_structured() {
let input = r#"combi=start
id=makefire
req=107
req=24
gen=107
gen=24
genname=make fire
combi=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let combis = entries[0].blocks.get("combi").unwrap();
assert_eq!(combis.len(), 1);
match &combis[0].content {
BlockContent::Structured { fields, blocks } => {
assert_eq!(fields.get("id").unwrap()[0], "makefire");
assert_eq!(fields.get("req").unwrap().len(), 2);
assert_eq!(fields.get("genname").unwrap()[0], "make fire");
assert!(blocks.is_empty());
}
_ => panic!("expected Structured"),
}
}
#[test]
fn test_combi_with_nested_script() {
let input = r#"combi=start
id=test
req=1
script=start
on:create { msg "works"; }
script=end
combi=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let combis = entries[0].blocks.get("combi").unwrap();
assert_eq!(combis.len(), 1);
match &combis[0].content {
BlockContent::Structured { fields, blocks } => {
assert_eq!(fields.get("id").unwrap()[0], "test");
assert_eq!(fields.get("req").unwrap()[0], "1");
let scripts = blocks.get("script").unwrap();
assert_eq!(scripts.len(), 1);
match &scripts[0].content {
BlockContent::Text(t) => {
assert!(t.contains("msg \"works\""));
}
_ => panic!("expected Text inside combi"),
}
}
_ => panic!("expected Structured"),
}
}
#[test]
fn test_description_block_text() {
let input = r#"id=42
name=Test
description=start
This is a long description
that spans multiple lines.
description=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let descs = entries[0].blocks.get("description").unwrap();
assert_eq!(descs.len(), 1);
match &descs[0].content {
BlockContent::Text(t) => {
assert!(t.contains("long description"));
assert!(t.contains("multiple lines"));
}
_ => panic!("expected Text"),
}
}
#[test]
fn test_global_script_creates_entry() {
let input = r#"script=start
on:start { msg "Hello!"; }
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let scripts = entries[0].blocks.get("script").unwrap();
assert_eq!(scripts.len(), 1);
match &scripts[0].content {
BlockContent::Text(t) => assert!(t.contains("Hello!")),
_ => panic!("expected Text"),
}
}
#[test]
fn test_header_fields_and_script() {
let input = r#"healthsystem=4
terrain_color_normal=230,223,145
script=start
echo "Hello";
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(
entries[0].fields.get("healthsystem").unwrap()[0],
"4"
);
let scripts = entries[0].blocks.get("script").unwrap();
match &scripts[0].content {
BlockContent::Text(t) => assert!(t.contains("Hello")),
_ => panic!("expected Text"),
}
}
#[test]
fn test_pure_config() {
let input = r#"0001=Loading Interface
0002=Loading Stuff
0003=Loading Objects"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(
entries[0].fields.get("0001").unwrap()[0],
"Loading Interface"
);
assert!(entries[0].blocks.is_empty());
}
#[test]
fn test_unmatched_block_start() {
let input = "script=start\nmsg hello;\n";
let result = InfParser::parse_str(input);
assert!(result.is_err());
match result.unwrap_err() {
InfError::UnmatchedBlock { block_type, .. } => {
assert_eq!(block_type, "script");
}
_ => panic!("expected UnmatchedBlock"),
}
}
#[test]
fn test_unmatched_block_end() {
let input = "script=end\n";
let result = InfParser::parse_str(input);
assert!(result.is_err());
}
#[test]
fn test_nested_unmatched() {
let input = r#"outer=start
inner=start
data
outer=end"#;
let result = InfParser::parse_str(input);
assert!(result.is_err());
}
#[test]
fn test_custom_block_name() {
let input = r#"id=42
myplugin_block=start
some data
more data
myplugin_block=end"#;
let entries = InfParser::parse_str(input).unwrap();
let blocks = entries[0].blocks.get("myplugin_block").unwrap();
assert_eq!(blocks.len(), 1);
match &blocks[0].content {
BlockContent::Text(t) => {
assert!(t.contains("some data"));
assert!(t.contains("more data"));
}
_ => panic!("expected Text"),
}
}
#[test]
fn test_multiple_blocks_same_name() {
let input = r#"id=1
script=start
first script
script=end
script=start
second script
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
let scripts = entries[0].blocks.get("script").unwrap();
assert_eq!(scripts.len(), 2);
match &scripts[0].content {
BlockContent::Text(t) => assert!(t.contains("first")),
_ => panic!("expected Text"),
}
match &scripts[1].content {
BlockContent::Text(t) => assert!(t.contains("second")),
_ => panic!("expected Text"),
}
}
#[test]
fn test_structured_block_with_sub_blocks() {
let input = r#"id=1
custom=start
setting=hello
nested_block=start
inner text
nested_block=end
other_setting=world
custom=end"#;
let entries = InfParser::parse_str(input).unwrap();
let blocks = entries[0].blocks.get("custom").unwrap();
assert_eq!(blocks.len(), 1);
match &blocks[0].content {
BlockContent::Structured { fields, blocks } => {
assert_eq!(fields.get("setting").unwrap()[0], "hello");
assert_eq!(fields.get("other_setting").unwrap()[0], "world");
let nested = blocks.get("nested_block").unwrap();
assert_eq!(nested.len(), 1);
match &nested[0].content {
BlockContent::Text(t) => assert!(t.contains("inner text")),
_ => panic!("expected Text"),
}
}
_ => panic!("expected Structured"),
}
}
}