inf2ron 0.1.0

Parse Stranded II .inf definition files (items, objects, units, buildings, combinations) and output RON format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// inf2ron – parse Stranded II .inf definition files to RON
// Copyright (C) 2025  inf2ron contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! State-machine parser for .inf files.
//!
//! The parser works line-by-line, tracking:
//! - Current block state: None, InScript, InDescription, InCombi
//! - Current entity being built
//! - Top-level key=value pairs (before any `id=`) for files like `game.inf`
//! - Multivalue keys (same key can appear multiple times, e.g. `req=`)

use std::collections::HashMap;
use std::fs;
use std::path::Path;

use crate::error::{InfError, InfResult};
use crate::types::*;

/// .inf file parser
pub struct InfParser;

impl InfParser {
    /// Parse an .inf file from disk
    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,
        })
    }

    /// Parse .inf content from a string
    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;

        // Top-level key=value pairs before any `id=` (e.g. game.inf config)
        let mut header_fields: HashMap<String, Vec<String>> = HashMap::new();

        // Multi-line block states
        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();

            // Skip empty lines
            if trimmed.is_empty() {
                continue;
            }

            // Skip comments
            if trimmed.starts_with('#') {
                continue;
            }

            // Inside script=start / script=end
            if let Some((start_line, ref mut acc)) = script_block {
                if trimmed.starts_with("script=end") {
                    // End script block
                    let script = std::mem::take(acc);

                    // If inside a combi block, store in combi_script
                    if combi_block.is_some() {
                        combi_script = Some((start_line, script));
                    } else if let Some(ref mut entry) = current_entry {
                        // Associate with 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 {
                        // No current entry — create a header entry with top-level fields
                        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;
            }

            // Inside description=start / description=end
            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;
            }

            // Inside combi=start / combi=end
            if let Some((start_line, ref mut fields)) = combi_block {
                if trimmed.starts_with("combi=end") {
                    // End combi block
                    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;
                }
                // Parse key=value inside combi
                if let Some((key, value)) = Self::parse_kv(trimmed) {
                    fields
                        .entry(key)
                        .or_insert_with(Vec::new)
                        .push(value);
                }
                continue;
            }

            // Start of multi-line blocks
            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;
            }

            // Parse key=value
            if let Some((key, value)) = Self::parse_kv(trimmed) {
                // `id=` starts a new entity
                if key == "id" {
                    // Flush previous entry if any
                    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,
                        });
                    }
                    // Start new entity
                    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 {
                    // key=value outside any entity — store in header_fields.
                    // This handles config files like game.inf, strings.inf, etc.
                    header_fields
                        .entry(key)
                        .or_default()
                        .push(value);
                }
            }
        }

        // Flush the last entry if any
        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,
            });
        }

        // Also flush any remaining header fields (for pure config files like strings.inf)
        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,
                });
            }
        }

        // Check for unclosed blocks
        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)
    }

    /// Parse a single key=value line.
    /// Strips inline `//` comments.
    fn parse_kv(line: &str) -> Option<(String, String)> {
        let line = line.trim();

        // Strip inline comments
        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() {
        // Simulates game.inf: config key=value + script block, no id= entries
        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() {
        // Simulates strings.inf: key=value only, no id=, no script
        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() {
        // Script block before any id= should create a header entry
        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() {
        // Note: the parser accepts description=start/end blocks but
        // does NOT attach them to entries (desc_block is cleared on
        // description=end without saving the 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);
        // description is None because the parser discards it
        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() {
        // Inside combi blocks, script=start/end lines are parsed as
        // regular key=value fields, not as script blocks.
        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();
        // script=start is stored as a key=value field
        assert_eq!(combi.fields.get("script").unwrap()[0], "start");
        // The script body is discarded (not parseable as key=value)
        // script=end is also stored
        assert_eq!(combi.fields.get("script").unwrap()[1], "end");
        // combi.script stays None in current parser implementation
        assert!(combi.script.is_none());
    }

    #[test]
    fn test_unmatched_script_flushed_as_entry() {
        // Unmatched script=start (no script=end) is flushed as a
        // header entry at end of file, not an error.
        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;"));
    }
}