inf2ron 0.2.2

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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
// 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/>.

//! Generic stack-based parser for .inf files.
//!
//! Accepts **any** `xxx=start` / `xxx=end` block — no hardcoded names.
//! Automatically classifies each block's content as either:
//! - [`BlockContent::Structured`] — all lines parse as `key=value`
//! - [`BlockContent::Text`] — otherwise (s2s code, descriptions, …)
//!
//! Nested sub-blocks are parsed recursively.

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

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

// ── Block frame for the stack automaton ────────────────────

/// A block that is currently being parsed (on the stack).
struct BlockFrame {
    /// Block name (from `xxx=start`)
    name: String,
    /// Source line where `xxx=start` was found
    start_line: usize,
    /// Raw lines inside the block (excluding sub-block markers)
    raw_lines: Vec<String>,
    /// Already-parsed nested sub-blocks
    sub_blocks: HashMap<String, Vec<Block>>,
}

/// .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<InfEntry> = Vec::new();
        let mut header_fields: HashMap<String, Vec<String>> = HashMap::new();
        let mut current_entry: Option<CurrentEntry> = None;

        // Stack automaton for nested blocks
        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();

            // Skip empty lines and comments
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }

            if let Some(top) = stack.last_mut() {
                // ── Inside a block ────────────────────────────
                if trimmed == format!("{}={}", top.name, "end") {
                    // End of current block → pop and classify
                    let frame = stack.pop().unwrap();
                    let block = classify_frame(frame);

                    if let Some(parent) = stack.last_mut() {
                        // Nested block → add to parent's sub_blocks
                        let name = block.name.clone();
                        parent
                            .sub_blocks
                            .entry(name)
                            .or_default()
                            .push(block);
                    } else {
                        // Entry-level block → attach to current entry
                        attach_block_to_entry(&mut current_entry, &mut entries, &mut header_fields, block, line_no)?;
                    }
                } else if let Some(name) = strip_block_start(trimmed) {
                    // Nested sub-block starts
                    stack.push(BlockFrame {
                        name,
                        start_line: line_no,
                        raw_lines: Vec::new(),
                        sub_blocks: HashMap::new(),
                    });
                } else {
                    // Accumulate raw line
                    top.raw_lines.push(raw_line.to_string());
                }
            } else {
                // ── Top level (outside any block) ─────────────
                if let Some(name) = strip_block_start(trimmed) {
                    // A block starts at top level
                    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) {
                    // `xxx=end` without matching `xxx=start`
                    return Err(InfError::UnmatchedBlock {
                        line: line_no,
                        block_type: end_name,
                    });
                } else if let Some((key, value)) = parse_kv(trimmed) {
                    if key == "id" {
                        // New entry marker
                        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);
                    }
                }
                // Non-key=value lines at top level are ignored
                // (they don't appear in well-formed .inf files)
            }
        }

        // End of file — validate and flush

        // Unclosed blocks?
        if let Some(frame) = stack.last() {
            return Err(InfError::UnmatchedBlock {
                line: frame.start_line,
                block_type: frame.name.clone(),
            });
        }

        // Finalise remaining entry
        if let Some(ce) = current_entry.take() {
            entries.push(ce.into_entry(line_no));
        }

        // Flush header fields as a single entry (game.inf style config)
        if !header_fields.is_empty() {
            entries.push(InfEntry {
                line: line_no,
                fields: header_fields,
                blocks: HashMap::new(),
            });
        }

        Ok(entries)
    }
}

// ── Internal helpers ───────────────────────────────────────

/// State being accumulated for an entry.
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,
        }
    }
}

/// Attach a classified block to the current entry (or create one).
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 {
        // No current entry — create a header entry with this block
        // (e.g. game.inf with global script)
        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(())
}

/// Try to parse a line as `xxx=start`, returning the block name.
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
    }
}

/// Try to parse a line as `xxx=end`, returning the block name.
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
    }
}

/// Classify a finished block frame.
///
/// Rules (after extracting nested sub-blocks):
/// - All raw lines parse as `key=value` → `Structured { fields, sub_blocks }`
/// - Otherwise → `Text { raw_lines joined }`
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 {
        // Text: join raw lines, sub_blocks are discarded (unused in practice)
        Block {
            name,
            content: BlockContent::Text(frame.raw_lines.join("\n")),
        }
    }
}

/// Try to parse every line as `key=value`.
/// Returns `(true, fields)` if all lines parse, `(false, _)` otherwise.
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)
}

/// Parse a single `key=value` line.
/// NOTE: The original game engine does NOT strip inline `//` comments.
/// Only full-line `#` comments are skipped (handled by the caller).
fn parse_kv(line: &str) -> Option<(String, String)> {
    let line = line.trim();

    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()))
}

// ── Tests ──────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── Basic entry parsing ─────────────────────────────────

    #[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");
    }

    // ── Block parsing ───────────────────────────────────────

    #[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"),
        }
    }

    // ── Header / global entries ─────────────────────────────

    #[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());
    }

    // ── Error conditions ────────────────────────────────────

    #[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());
    }

    // ── Custom / generic block names ────────────────────────

    #[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"),
        }
    }
}