use std::collections::HashMap;
use std::fs;
use std::path::Path;
use crate::error::{InfError, InfResult};
use crate::types::*;
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::new();
let mut current_entry: Option<HashMap<String, Vec<String>>> = None;
let mut current_line = 0usize;
let mut header_fields: HashMap<String, Vec<String>> = HashMap::new();
let mut script_block: Option<(usize, String)> = None;
let mut desc_block: Option<(usize, String)> = None;
let mut combi_block: Option<(usize, HashMap<String, Vec<String>>)> = None;
let mut combi_script: Option<(usize, String)> = None;
for line in content.lines() {
current_line += 1;
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.starts_with('#') {
continue;
}
if let Some((start_line, ref mut acc)) = script_block {
if trimmed.starts_with("script=end") {
let script = std::mem::take(acc);
if combi_block.is_some() {
combi_script = Some((start_line, script));
} else if let Some(ref mut entry) = current_entry {
let fields = std::mem::take(entry);
let desc = desc_block.take().map(|(_, d)| d);
entries.push(InfEntry {
line: start_line,
fields,
script: Some(script),
description: desc,
combi: None,
});
current_entry = None;
} else {
let fields = std::mem::take(&mut header_fields);
let desc = desc_block.take().map(|(_, d)| d);
entries.push(InfEntry {
line: start_line,
fields,
script: Some(script),
description: desc,
combi: None,
});
}
script_block = None;
continue;
}
acc.push_str(line);
acc.push('\n');
continue;
}
if let Some((_start_line, ref mut acc)) = desc_block {
if trimmed.starts_with("description=end") {
desc_block = None;
continue;
}
acc.push_str(line);
acc.push('\n');
continue;
}
if let Some((start_line, ref mut fields)) = combi_block {
if trimmed.starts_with("combi=end") {
let f = std::mem::take(fields);
let script = combi_script.take().map(|(_, s)| s);
entries.push(InfEntry {
line: start_line,
fields: HashMap::new(),
script: None,
description: None,
combi: Some(CombiBlock {
fields: f,
script,
}),
});
combi_block = None;
current_entry = None;
continue;
}
if let Some((key, value)) = Self::parse_kv(trimmed) {
fields
.entry(key)
.or_insert_with(Vec::new)
.push(value);
}
continue;
}
if trimmed.starts_with("script=start") {
script_block = Some((current_line, String::new()));
continue;
}
if trimmed.starts_with("description=start") {
desc_block = Some((current_line, String::new()));
continue;
}
if trimmed.starts_with("combi=start") {
combi_block = Some((current_line, HashMap::new()));
combi_script = None;
continue;
}
if let Some((key, value)) = Self::parse_kv(trimmed) {
if key == "id" {
if let Some(fields) = current_entry.take() {
entries.push(InfEntry {
line: current_line,
fields,
script: None,
description: desc_block.take().map(|(_, d)| d),
combi: None,
});
}
let mut fields = HashMap::new();
fields.insert(key, vec![value]);
current_entry = Some(fields);
} else if let Some(ref mut entry) = current_entry {
entry
.entry(key)
.or_insert_with(Vec::new)
.push(value);
} else {
header_fields
.entry(key)
.or_default()
.push(value);
}
}
}
if let Some(fields) = current_entry.take() {
entries.push(InfEntry {
line: current_line,
fields,
script: script_block.take().map(|(_, s)| s),
description: desc_block.take().map(|(_, d)| d),
combi: None,
});
}
if !header_fields.is_empty() || script_block.is_some() || desc_block.is_some() {
let script = script_block.take().map(|(_, s)| s);
let desc = desc_block.take().map(|(_, d)| d);
let fields = std::mem::take(&mut header_fields);
if !fields.is_empty() || script.is_some() || desc.is_some() {
entries.push(InfEntry {
line: current_line,
fields,
script,
description: desc,
combi: None,
});
}
}
if let Some((line, _)) = script_block {
return Err(InfError::UnmatchedBlock {
line,
block_type: "script".into(),
});
}
if let Some((line, _)) = combi_block {
return Err(InfError::UnmatchedBlock {
line,
block_type: "combi".into(),
});
}
Ok(entries)
}
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_parse_simple_item() {
let input = r#"### Meat
id=9
name=Meat
group=food
icon=gfx\meat.bmp
model=gfx\meat.b3d
scale=0.15
mat=flesh
weight=500"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert_eq!(entry.fields.get("id").unwrap()[0], "9");
assert_eq!(entry.fields.get("name").unwrap()[0], "Meat");
assert_eq!(entry.fields.get("group").unwrap()[0], "food");
assert_eq!(entry.fields.get("weight").unwrap()[0], "500");
}
#[test]
fn test_parse_with_script() {
let input = r#"### Meat
id=9
name=Meat
script=start
on:eat {
process "eating",1000;
eat 5,20,10,0;
}
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert!(entry.script.is_some());
let script = entry.script.as_ref().unwrap();
assert!(script.contains("on:eat"));
assert!(script.contains("eat 5,20,10,0"));
}
#[test]
fn test_parse_multiple_entries() {
let input = r#"### Meat
id=9
name=Meat
### Banana
id=14
name=Banana"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].fields.get("id").unwrap()[0], "9");
assert_eq!(entries[1].fields.get("id").unwrap()[0], "14");
}
#[test]
fn test_parse_combi() {
let input = r#"### Make fire
combi=start
req=107
req=24
gen=107
gen=24
genname=make fire
script=start
event "someEvent","global";
script=end
combi=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert!(entry.combi.is_some());
let combi = entry.combi.as_ref().unwrap();
assert_eq!(combi.fields.get("req").unwrap().len(), 2);
assert_eq!(combi.fields.get("req").unwrap()[0], "107");
assert_eq!(combi.fields.get("genname").unwrap()[0], "make fire");
}
#[test]
fn test_parse_game_inf_style() {
let input = r#"menu_adventure=1
terrain_color_normal=230,223,145
healthsystem=4
script=start
on:start {
echo "Hello";
}
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert_eq!(entry.fields.get("menu_adventure").unwrap()[0], "1");
assert_eq!(entry.fields.get("healthsystem").unwrap()[0], "4");
assert!(entry.script.is_some());
assert!(entry.script.as_ref().unwrap().contains("on:start"));
}
#[test]
fn test_parse_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);
let entry = &entries[0];
assert_eq!(entry.fields.get("0001").unwrap()[0], "Loading Interface");
assert_eq!(entry.fields.get("0003").unwrap()[0], "Loading Objects");
assert!(entry.script.is_none());
}
#[test]
fn test_script_without_entry_becomes_header() {
let input = r#"script=start
on:start { }
script=end"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert!(entry.script.is_some());
assert!(entry.fields.is_empty());
}
#[test]
fn test_description_block_parsed_but_not_attached() {
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);
assert!(entries[0].description.is_none());
}
#[test]
fn test_multivalue_keys() {
let input = r#"id=5
name=Multi
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_parse_header_fields() {
let input = r#"healthsystem=4
exhaust_move=十1,0,0,2
dig_time=3000"#;
let entries = InfParser::parse_str(input).unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].fields.get("healthsystem").unwrap()[0], "4");
assert_eq!(entries[0].fields.get("dig_time").unwrap()[0], "3000");
}
#[test]
fn test_combi_block() {
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 combi = entries[0].combi.as_ref().unwrap();
assert_eq!(combi.fields.get("id").unwrap()[0], "makefire");
assert_eq!(combi.fields.get("req").unwrap().len(), 2);
assert_eq!(combi.fields.get("genname").unwrap()[0], "make fire");
}
#[test]
fn test_combi_with_script_as_fields() {
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 combi = entries[0].combi.as_ref().unwrap();
assert_eq!(combi.fields.get("script").unwrap()[0], "start");
assert_eq!(combi.fields.get("script").unwrap()[1], "end");
assert!(combi.script.is_none());
}
#[test]
fn test_unmatched_script_flushed_as_entry() {
let input = "script=start\nmsg hello;\n";
let result = InfParser::parse_str(input);
assert!(result.is_ok());
let entries = result.unwrap();
assert_eq!(entries.len(), 1);
assert!(entries[0].script.is_some());
assert!(entries[0].script.as_ref().unwrap().contains("msg hello;"));
}
}