Skip to main content

dayzmake_core/
config.rs

1//! Functions for rapifying and derapifying Arma configs
2
3use std::cmp::min;
4use std::collections::HashSet;
5use std::io::{BufReader, BufWriter, Cursor, Error, Read, Seek, SeekFrom, Write};
6use std::iter::Sum;
7use std::path::PathBuf;
8
9use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
10
11use crate::error;
12use crate::error::{ConfigParseErrorExt, ErrorExt, located_error, printable};
13use crate::eval::{EvalValue, eval, exec};
14use crate::io::{ReadExt, WriteExt, compressed_int_len};
15use crate::preprocess::{IncludeFolders, MAX_NESTING_DEPTH, nesting_error, preprocess_in};
16use crate::warning::{Warning, WarningSink};
17
18/// Refuses a name with a control character: the config grammar has no way to write one, and it
19/// would reach the terminal raw.
20fn text_name(name: &str, what: &str) -> Result<(), Error> {
21    if name.chars().any(char::is_control) {
22        return Err(error!(
23            "{what} name \"{}\" cannot be written as config text.",
24            printable(name)
25        ));
26    }
27    Ok(())
28}
29
30/// State shared with the grammar for `__EVAL` / `__EXEC`.
31#[derive(Default)]
32pub(crate) struct EvalCtx {
33    vars: std::collections::HashMap<String, EvalValue>,
34    /// The first error raised from a grammar action, with the byte offset of the token it belongs to.
35    error: Option<(usize, Error)>,
36}
37
38impl From<EvalValue> for ConfigEntry {
39    fn from(v: EvalValue) -> ConfigEntry {
40        match v {
41            EvalValue::Str(s) => ConfigEntry::StringEntry(s),
42            EvalValue::Number(n)
43                if matches!(n.fract().classify(), std::num::FpCategory::Zero)
44                    && n.abs() < 2_147_483_648.0 =>
45            {
46                // the guard above ensures the value fits an i32 without truncation
47                #[expect(
48                    clippy::cast_possible_truncation,
49                    reason = "guarded by fract() == 0 and abs() < 2^31"
50                )]
51                {
52                    ConfigEntry::IntEntry(n as i32)
53                }
54            }
55            EvalValue::Number(n) => ConfigEntry::FloatEntry(n),
56        }
57    }
58}
59
60impl From<EvalValue> for ConfigArrayElement {
61    fn from(v: EvalValue) -> ConfigArrayElement {
62        match v {
63            EvalValue::Str(s) => ConfigArrayElement::StringElement(s),
64            EvalValue::Number(n)
65                if matches!(n.fract().classify(), std::num::FpCategory::Zero)
66                    && n.abs() < 2_147_483_648.0 =>
67            {
68                // the guard above ensures the value fits an i32 without truncation
69                #[expect(
70                    clippy::cast_possible_truncation,
71                    reason = "guarded by fract() == 0 and abs() < 2^31"
72                )]
73                {
74                    ConfigArrayElement::IntElement(n as i32)
75                }
76            }
77            EvalValue::Number(n) => ConfigArrayElement::FloatElement(n),
78        }
79    }
80}
81
82/// Warnings raised while parsing a config, with the byte offset they occurred at.
83pub(crate) struct ConfigWarnings(pub(crate) Vec<(usize, String, Option<&'static str>)>);
84
85impl ConfigWarnings {
86    fn push(&mut self, warning: (usize, String, Option<&'static str>)) {
87        self.0.push(warning);
88    }
89}
90
91peg::parser! {
92    /// PEG grammar for rapified config syntax.
93    pub(crate) grammar config_grammar(warnings: &mut ConfigWarnings, ctx: &mut EvalCtx) for str {
94        rule whitespace() = quiet!{ [' ' | '\r' | '\n' | '\t']+ }
95
96        rule exponent() = ['e' | 'E'] ['-' | '+']? ['0'..='9']+
97
98        rule float_text() -> (usize, &'input str) = p:position!() t:$((['-' | '+'])? ((['0'..='9']* "." ['0'..='9']+ exponent()?) / (['0'..='9']+ exponent()))) { (p, t) }
99
100        /// The end of an entry: `;`, the `}` of the class, or (for the last entry of a block or file,
101        /// as CfgConvert reads it) the end of the line.
102        rule entry_end() = whitespace()? [';' | '}'] / [' ' | '\t']* ['\r' | '\n']
103
104        /// A float followed by the end of an entry.
105        rule float_entry() -> f32 = f:float_text() &entry_end() v:float_value(f) { v }
106
107        /// A float followed by the end of an array element.
108        rule float_element() -> f32 = f:float_text() &(whitespace()? [',' | '}']) v:float_value(f) { v }
109
110        /// An overflowing literal (`1e999`) is an infinity, as `CfgConvert` writes it; derapify writes
111        /// `1e999` / `-1e999` for it, which reads back to the same value.
112        rule float_value(at: (usize, &str)) -> f32 = {?
113            let (pos, f) = at;
114            // `float_text` only matches what `f32::from_str` accepts, and overflow is an infinity, so the
115            // error cannot fire; it stays as a guard against a grammar change.
116            f.parse::<f32>()
117                .map_err(|e| { ctx.error.get_or_insert((pos, error!("Invalid float \"{f}\": {e}"))); "a valid float" })
118        }
119
120        /// The literal of an enum value: a sign, decimal digits or `0x` / `0X` hex of any length.
121        rule integer_text() -> &'input str = $((['-' | '+'])? (("0" ['x' | 'X'] ['0'..='9' | 'a'..='f' | 'A'..='F']+) / ['0'..='9']+))
122
123        /// A literal `CfgConvert` stores as an integer: unsigned hex (any length, `0x` or `0X`) or a decimal.
124        rule int_literal() -> (usize, &'input str) = p:position!() t:$(("0" ['x' | 'X'] ['0'..='9' | 'a'..='f' | 'A'..='F']+) / ((['-' | '+'])? ['0'..='9']+)) { (p, t) }
125
126        /// A signed hex literal (`-0x10`), which `CfgConvert` stores as a float.
127        rule signed_hex_text() -> &'input str = $(['-' | '+'] "0" ['x' | 'X'] ['0'..='9' | 'a'..='f' | 'A'..='F']+)
128
129        /// An integer followed by the end of an entry; the terminator is checked first, like for floats
130        /// (`99999999999x` stays an unquoted string).
131        rule integer_entry() -> i32 = i:int_literal() &entry_end() v:int_value(i) { v }
132
133        /// An integer followed by the end of an array element.
134        rule integer_element() -> i32 = i:int_literal() &(whitespace()? [',' | '}']) v:int_value(i) { v }
135
136        /// A signed hex literal followed by the end of an entry.
137        rule signed_hex_entry() -> f32 = t:signed_hex_text() &entry_end() { signed_hex_float(t) }
138
139        /// A signed hex literal followed by the end of an array element.
140        rule signed_hex_element() -> f32 = t:signed_hex_text() &(whitespace()? [',' | '}']) { signed_hex_float(t) }
141
142        /// A decimal literal that does not fit `i64`, which `CfgConvert` stores as a float (`1e20`); one that
143        /// fits is left to `int64_entry` and `integer_entry`.
144        rule huge_integer_text() -> (usize, &'input str) = quiet!{ p:position!() t:$((['-' | '+'])? ['0'..='9']+) {?
145            if t.parse::<i64>().is_err() { Ok((p, t)) } else { Err("an integer that fits 64 bits") }
146        } }
147
148        /// A decimal literal that fits `i64` but not `i32`, which `CfgConvert` stores as a 64-bit integer in an entry.
149        rule int64_text() -> i64 = quiet!{ t:$((['-' | '+'])? ['0'..='9']+) {?
150            match (t.parse::<i64>(), t.parse::<i32>()) {
151                (Ok(v), Err(_)) => Ok(v),
152                _ => Err("an integer between 32 and 64 bits"),
153            }
154        } }
155
156        /// A decimal literal that does not fit `i32`, in an array, where `CfgConvert` stores it as a float.
157        rule wide_integer_text() -> (usize, &'input str) = quiet!{ p:position!() t:$((['-' | '+'])? ['0'..='9']+) {?
158            if t.parse::<i32>().is_err() { Ok((p, t)) } else { Err("an integer that fits 32 bits") }
159        } }
160
161        rule huge_integer_entry() -> f32 = i:huge_integer_text() &entry_end() v:float_value(i) { v }
162
163        rule int64_entry() -> i64 = i:int64_text() &entry_end() { i }
164
165        rule wide_integer_element() -> f32 = i:wide_integer_text() &(whitespace()? [',' | '}']) v:float_value(i) { v }
166
167        /// An integer literal of an entry or array element: hex keeps its low 32 bits, as in `CfgConvert`.
168        /// A decimal one is always an `i32` here: wider ones are taken first by `huge_integer_entry` and
169        /// `int64_entry` (entries) or `wide_integer_element` (arrays).
170        rule int_value(at: (usize, &str)) -> i32 = {?
171            let (pos, i) = at;
172            match hex_digits(i) {
173                Some(digits) => Ok(hex_wrapped(digits)),
174                // the error cannot fire (see above); it stays as a guard against a grammar change
175                None => i.parse::<i32>()
176                    .map_err(|e| { ctx.error.get_or_insert((pos, error!("Invalid integer \"{i}\": {e}"))); "a valid integer" }),
177            }
178        }
179
180        /// The value of an enum literal, as `CfgConvert` computes it: an `f32` (see `enum_literal_value`).
181        rule enum_number() -> f32 = t:integer_text() { enum_literal_value(t) }
182
183        rule doublequoted_string() -> String = "\"" s:$(("\"\"" / !['"'] [_])*) "\"" {
184            s.to_string().replace("\"\"", "\"")
185        }
186
187        rule singlequoted_string() -> String = "'" s:$(("''" / !['\''] [_])*) "'" {
188            s.to_string().replace("''", "'")
189        }
190
191        rule unquoted_string() -> String = pos:position!() s:$((![';' | '}' | '\r' | '\n'] [_])*) {
192            let result = s.to_string().trim().to_string();
193            // an empty value comes from a macro that expanded to nothing (e.g. an argument-count
194            // mismatch, which has its own warning); CfgConvert makes it "" as well.
195            // `unquoted_string_entry` raises `empty-value` for it
196            if !result.is_empty() {
197                warnings.push((pos, format!("String value \"{}\" is not quoted properly.", printable(&result)), Some("unquoted-string")));
198            }
199            result
200        }
201
202        rule unquoted_string_array() -> String = pos:position!() s:$( (![',' | '}' | ' ' | '\t' | '\r' | '\n'] [_]) (![',' | '}' | '\r' | '\n'] [_])* ) {
203            let result = s.to_string().trim().to_string();
204            warnings.push((pos, format!("String array element \"{}\" is not quoted properly.", printable(&result)), Some("unquoted-string")));
205            result
206        }
207
208        /// Fails (and records the error) when `d` levels of classes, arrays or parentheses are exceeded.
209        rule nesting_ok(d: usize) = pos:position!() {?
210            if d >= MAX_NESTING_DEPTH {
211                ctx.error.get_or_insert((pos, nesting_error()));
212                Err("nesting within the limit")
213            } else {
214                Ok(())
215            }
216        }
217
218        rule eval_body(d: usize) = ("(" nesting_ok(d) eval_body(d + 1) ")" / "\"" (!"\"" [_])* "\"" / !['(' | ')'] [_])*
219
220        rule eval_value(d: usize) -> EvalValue = pos:position!() "__EVAL" whitespace()? "(" b:$(eval_body(d)) ")" {?
221            match eval(b, &mut ctx.vars) {
222                Ok(v) => Ok(v),
223                Err(e) => { ctx.error.get_or_insert((pos, e)); Err("a supported __EVAL expression") }
224            }
225        }
226
227        rule exec_entry(d: usize) = pos:position!() "__EXEC" whitespace()? "(" b:$(eval_body(d)) ")" whitespace()? ";" {?
228            match exec(b, &mut ctx.vars) {
229                Ok(()) => Ok(()),
230                Err(e) => { ctx.error.get_or_insert((pos, e)); Err("a supported __EXEC statement") }
231            }
232        }
233
234        rule string() -> String = doublequoted_string() / singlequoted_string()
235
236        /// An element that is not an array. Kept out of `array_element`, whose frame is on the recursive
237        /// path of nested arrays and must stay small (see `plain_entry`).
238        rule scalar_element(d: usize) -> ConfigArrayElement =
239            f:float_element() { ConfigArrayElement::FloatElement(f) } /
240            f:wide_integer_element() { ConfigArrayElement::FloatElement(f) } /
241            f:signed_hex_element() { ConfigArrayElement::FloatElement(f) } /
242            i:integer_element() { ConfigArrayElement::IntElement(i) } /
243            s:string()  &(whitespace()? [',' | '}']) { ConfigArrayElement::StringElement(s) } /
244            v:eval_value(d) &(whitespace()? [',' | '}']) { v.into() } /
245            s:unquoted_string_array() &(whitespace()? [',' | '}']) { ConfigArrayElement::StringElement(s) }
246
247        /// An array is tried first: the other elements cannot start with `{` except an unquoted string,
248        /// which comes last.
249        rule array_element(d: usize) -> ConfigArrayElement =
250            a:array(d)   &(whitespace()? [',' | '}']) { ConfigArrayElement::ArrayElement(a) } /
251            scalar_element(d)
252
253        rule array_elements(d: usize) -> Vec<ConfigArrayElement> = array_element(d) ** (whitespace()? "," whitespace()?)
254
255        rule array(d: usize) -> ConfigArray = "{" nesting_ok(d) whitespace()? elems:array_elements(d + 1) whitespace()? ","? whitespace()? "}" {
256            ConfigArray {
257                is_expansion: false,
258                elements: elems
259            }
260        }
261
262        rule var(d: usize) -> ConfigEntry =
263            f:float_entry() { ConfigEntry::FloatEntry(f) } /
264            f:signed_hex_entry() { ConfigEntry::FloatEntry(f) } /
265            f:huge_integer_entry() { ConfigEntry::FloatEntry(f) } /
266            i:int64_entry() { ConfigEntry::Int64Entry(i) } /
267            i:integer_entry() { ConfigEntry::IntEntry(i) } /
268            s:string()  { ConfigEntry::StringEntry(s) } /
269            v:eval_value(d) { v.into() }
270
271        rule var_entry(d: usize) -> (String, ConfigEntry) = n:name() whitespace()? "=" whitespace()? ce:var(d) {
272            (n, ce)
273        }
274
275        rule unquoted_string_entry() -> (String, ConfigEntry) = pos:position!() n:name() whitespace()? "=" whitespace()? s:unquoted_string() {
276            if s.is_empty() {
277                // `x = ;`, or a macro that expanded to nothing; kept as "" so existing mods still build
278                warnings.push((pos, format!("Entry \"{}\" has no value; it is stored as an empty string.", printable(&n)), Some("empty-value")));
279            }
280            (n, ConfigEntry::StringEntry(s))
281        }
282
283        rule array_entry(d: usize) -> (String, ConfigEntry) = n:name() whitespace()? "[" whitespace()? "]" whitespace()? "=" whitespace()? a:array(d) {
284            (n, ConfigEntry::ArrayEntry(a))
285        }
286
287        rule array_expansion_entry(d: usize) -> (String, ConfigEntry) = n:name() whitespace()? "[" whitespace()? "]" whitespace()? "+=" whitespace()? a:array(d) {
288            (n, ConfigEntry::ArrayEntry(ConfigArray {
289                is_expansion: true,
290                ..a
291            }))
292        }
293
294        rule enum_value() -> (String, Option<f32>) = n:name() v:(whitespace()? "=" whitespace()? i:enum_number() { i })? { (n, v) }
295
296        /// `enum { name [= int], ... }`: values count up from the last explicit one, names are stored lowercase. The
297        /// values are computed in `f32` like `CfgConvert` does (`enum_literal_value`, `enum_f32_to_i32`).
298        rule enum_block() -> Vec<(String, i32)> = quiet!{"enum"} whitespace()? "{" whitespace()? v:(enum_value() ** (whitespace()? "," whitespace()?)) whitespace()? ","? whitespace()? "}" {?
299            let mut base = 0.0_f32;
300            // the first implicit value is 0, so the distance starts one below
301            let mut distance = -1.0_f32;
302            let mut out = Vec::new();
303            for (n, v) in v {
304                match v {
305                    Some(explicit) => { base = enum_i32_to_f32(enum_f32_to_i32(explicit)); distance = 0.0; }
306                    None => distance += 1.0,
307                }
308                out.push((n.to_ascii_lowercase(), enum_f32_to_i32(base + distance)));
309            }
310            Ok(out)
311        }
312
313        rule array_item(d: usize) -> Item =
314            e:(array_entry(d) / array_expansion_entry(d)) whitespace()? (";" / &"}") { Item::Entry(e.0, e.1, Vec::new()) }
315
316        /// A value entry; the last one of a block or file may end at the line end instead of `;`.
317        rule var_item(d: usize) -> Item =
318            e:var_entry(d) (whitespace()? (";" / &"}") / [' ' | '\t']* &['\r' | '\n']) { Item::Entry(e.0, e.1, Vec::new()) }
319
320        /// The entries that are not classes. Kept out of `entry_or_exec`, whose frame is on the recursive path
321        /// (class, entries, entry_or_exec, class) and must stay small: a debug build gives every alternative of a
322        /// rule its own stack slots, and a 1 MiB stack (Windows) has to hold the deepest nesting (#108).
323        rule plain_entry(d: usize) -> Item =
324            e:enum_block() whitespace()? (";" / &"}") { Item::Enums(e) } /
325            e:(array_item(d) / var_item(d)) { e } /
326            e:unquoted_string_entry() (";" / &"}" / &['\r' | '\n']) { Item::Entry(e.0, e.1, Vec::new()) }
327
328        /// A class is tried first, directly in `entry_or_exec`: `class` and `delete` cannot start an `enum`
329        /// block or `__EXEC`, so the order of the alternatives does not matter.
330        rule entry_or_exec(d: usize) -> Box<Item> =
331            e:class(d) whitespace()? (";" / &"}") { e } /
332            exec_entry(d) { Box::new(Item::Nothing) } /
333            e:plain_entry(d) { Box::new(e) }
334
335        rule entries(d: usize) -> (Vec<(String, ConfigEntry)>, Vec<(String, i32)>) = v:(entry_or_exec(d) ** (whitespace()?)) {
336            let mut entries = Vec::new();
337            let mut enums = Vec::new();
338            for item in v {
339                match *item {
340                    Item::Entry(n, e, en) => { entries.push((n, e)); enums.extend(en); }
341                    Item::Enums(en) => enums.extend(en),
342                    Item::Nothing => {}
343                }
344            }
345            (entries, enums)
346        }
347
348        rule name() -> String = n:$(['a'..='z' | 'A'..='Z' | '0'..='9' | '_']+) {
349            n.to_string()
350        }
351
352        rule parent() -> String = whitespace()? ":" whitespace()? n:name() {
353            n
354        }
355
356        rule regular_class(d: usize) -> Box<Item> = "class" whitespace()+ n:name() p:parent()? whitespace()? "{" nesting_ok(d) whitespace()? e:entries(d + 1) whitespace()? "}" {
357            let parent = p.unwrap_or_default();
358            Box::new(Item::Entry(n, ConfigEntry::ClassEntry(ConfigClass {
359                parent,
360                is_external: false,
361                is_deletion: false,
362                entries: Some(e.0)
363            }), e.1))
364        }
365
366        rule external_class() -> Box<Item> = "class" whitespace()+ n:name() {
367            Box::new(Item::Entry(n, ConfigEntry::ClassEntry(ConfigClass {
368                parent: String::new(),
369                is_external: true,
370                is_deletion: false,
371                entries: None
372            }), Vec::new()))
373        }
374
375        rule deleted_class() -> Box<Item> = "delete" whitespace()+ n:name() {
376            Box::new(Item::Entry(n, ConfigEntry::ClassEntry(ConfigClass {
377                parent: String::new(),
378                is_external: false,
379                is_deletion: true,
380                entries: None
381            }), Vec::new()))
382        }
383
384        rule class(d: usize) -> Box<Item> = regular_class(d) / external_class() / deleted_class()
385
386        /// Parses a complete config: a sequence of entries until end of input.
387        pub rule config() -> Config = whitespace()? e:entries(0) whitespace()? ![_] {
388            Config {
389                root_body: ConfigClass {
390                    parent: String::new(),
391                    is_external: false,
392                    is_deletion: false,
393                    entries: Some(e.0)
394                },
395                enums: e.1,
396            }
397        }
398    }
399}
400
401/// The hex digits of an unsigned `0x` / `0X` literal.
402fn hex_digits(text: &str) -> Option<&str> {
403    text.strip_prefix("0x").or_else(|| text.strip_prefix("0X"))
404}
405
406/// The low 32 bits of a hex literal of any length, as `CfgConvert` stores it (`0x1FFFFFFFFF` is `-1`).
407fn hex_wrapped(digits: &str) -> i32 {
408    let bits = digits
409        .chars()
410        .filter_map(|c| c.to_digit(16))
411        .fold(0_u32, |acc, d| {
412            // 4 bits per digit: the high bits fall off, which is the wrap-around wanted here
413            acc.wrapping_shl(4) | d
414        });
415    bits.cast_signed()
416}
417
418/// The `f32` an enum literal stands for in `CfgConvert`: unsigned hex keeps its low 32 bits, a signed hex
419/// literal is a float, a decimal is rounded to `f32` (`16777217` is `16777216`).
420#[expect(
421    clippy::cast_precision_loss,
422    reason = "the rounding of an i32 to f32 is what CfgConvert does"
423)]
424fn enum_literal_value(text: &str) -> f32 {
425    let unsigned = text.strip_prefix(['-', '+']).unwrap_or(text);
426    match (hex_digits(unsigned), unsigned.len() < text.len()) {
427        (Some(digits), false) => hex_wrapped(digits) as f32,
428        (Some(_), true) => signed_hex_float(text),
429        // the grammar only passes digits, so this parses; NaN converts to i32::MIN if it ever did not
430        (None, _) => text.parse::<f32>().unwrap_or(f32::NAN),
431    }
432}
433
434#[expect(
435    clippy::cast_precision_loss,
436    reason = "an i32 that came from an f32 is exact; the cast is only the type change back"
437)]
438fn enum_i32_to_f32(value: i32) -> f32 {
439    value as f32
440}
441
442/// An enum value from its `f32`, as `CfgConvert` converts it: a value outside `i32` (and NaN) is `i32::MIN`.
443#[expect(
444    clippy::cast_possible_truncation,
445    reason = "the value is in the i32 range, checked right here"
446)]
447fn enum_f32_to_i32(value: f32) -> i32 {
448    if (-2_147_483_648.0..2_147_483_648.0).contains(&value) {
449        value as i32
450    } else {
451        i32::MIN
452    }
453}
454
455/// The value of a signed hex literal (`-0x10`), which `CfgConvert` stores as a float. The magnitude is rounded
456/// to an f64 digit by digit and then to an f32, the double rounding `CfgConvert` shows: `-0x8000008000000001`,
457/// `-0x1000001000000001` and `-0x10000010000000001` give `0xDF000000`, `0xDD800000` and `0xDF800000` there
458/// (golden `hex_round*`, 2026-11-17), not the singly rounded `0xDF000001` and so on.
459#[expect(
460    clippy::cast_possible_truncation,
461    reason = "the f64 magnitude is rounded to the nearest f32, overflow is an infinity"
462)]
463fn signed_hex_float(text: &str) -> f32 {
464    let (negative, rest) = match text.strip_prefix('-') {
465        Some(rest) => (true, rest),
466        None => (false, text.strip_prefix('+').unwrap_or(text)),
467    };
468    let magnitude = hex_digits(rest)
469        .unwrap_or_default()
470        .chars()
471        .filter_map(|c| c.to_digit(16))
472        .fold(0.0_f64, |acc, d| acc * 16.0 + f64::from(d));
473    let value = magnitude as f32;
474    if negative { -value } else { value }
475}
476
477/// The text of a float as derapify writes it. An infinity becomes `1e999` / `-1e999`, a literal that
478/// overflows to the same f32 when read back. NaN has no such form and stays `NaN` (a string when read).
479fn float_literal(f: f32) -> String {
480    if f.is_infinite() {
481        if f.is_sign_positive() {
482            "1e999"
483        } else {
484            "-1e999"
485        }
486        .to_string()
487    } else {
488        format!("{f:?}")
489    }
490}
491
492/// Reads the enum table at the header's `enum_offset`. The class tree is usable without it, so a bad
493/// offset, a cut-short table or a name that is not a config identifier gives the values read before
494/// it, never an error.
495fn read_enum_table<I: Read + Seek>(input: &mut I) -> Vec<(String, i32)> {
496    let mut out = Vec::new();
497    // an unreadable table is not an error: the values read so far are returned
498    let _ = (|| -> std::io::Result<()> {
499        input.seek(SeekFrom::Start(12))?;
500        let offset = input.read_u32::<LittleEndian>()?;
501        input.seek(SeekFrom::Start(offset.into()))?;
502        let count = input.read_u32::<LittleEndian>()?;
503        // no preallocation from the count: the loop ends at the first read error
504        for _ in 0..count {
505            let name = input.read_cstring()?;
506            let value = input.read_i32::<LittleEndian>()?;
507            // the table ends at the first name the config grammar cannot write
508            if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
509                break;
510            }
511            out.push((name, value));
512        }
513        Ok(())
514    })();
515    out
516}
517
518/// Returns true if `data` starts with the rapified config signature.
519#[must_use]
520pub fn is_rapified(data: &[u8]) -> bool {
521    data.starts_with(b"\0raP")
522}
523
524/// `compressed_int_len` for an in-memory length. Config element counts beyond
525/// `u32::MAX` are impossible in practice (each element costs far more than a
526/// byte of memory), so they clamp to the maximum; the write path reports them
527/// as errors instead.
528fn compressed_int_len_of(len: usize) -> usize {
529    compressed_int_len(u32::try_from(len).unwrap_or(u32::MAX))
530}
531
532/// Config
533///
534/// # Examples
535///
536/// ```
537/// # use dayzmake_core::config::Config;
538/// # use dayzmake_core::warning::Warnings;
539/// let input = String::from("
540/// #define bar 42
541///
542/// foo = bar;
543/// ");
544///
545/// let config = Config::from_string(input, None, &Vec::new(), &mut Warnings::new()).expect("Failed to parse config");
546///
547/// assert_eq!("foo = 42;\n", config.to_string().unwrap());
548/// assert_eq!(b"\0raP", &config.to_cursor().unwrap().into_inner()[..4]);
549/// ```
550#[derive(Debug)]
551pub struct Config {
552    root_body: ConfigClass,
553    enums: Vec<(String, i32)>,
554}
555
556/// One parsed config item: the grammar returns the enum values of nested blocks upwards.
557enum Item {
558    Entry(String, ConfigEntry, Vec<(String, i32)>),
559    Enums(Vec<(String, i32)>),
560    Nothing,
561}
562
563/// Config class
564#[derive(Debug)]
565pub struct ConfigClass {
566    parent: String,
567    is_external: bool,
568    is_deletion: bool,
569    entries: Option<Vec<(String, ConfigEntry)>>,
570}
571
572/// Config entry
573#[derive(Debug)]
574#[non_exhaustive]
575pub enum ConfigEntry {
576    /// String entry
577    StringEntry(String),
578    /// Float entry
579    FloatEntry(f32),
580    /// Int entry
581    IntEntry(i32),
582    /// 64-bit int entry (entry subtype 6): `CfgConvert` writes a decimal literal that fits `i64` but not `i32` this way
583    Int64Entry(i64),
584    /// Array entry
585    ArrayEntry(ConfigArray),
586    /// Class entry
587    ClassEntry(ConfigClass),
588}
589
590/// Config array
591#[derive(Debug)]
592pub struct ConfigArray {
593    is_expansion: bool,
594    elements: Vec<ConfigArrayElement>,
595}
596
597/// Config array element
598#[derive(Debug)]
599#[non_exhaustive]
600pub enum ConfigArrayElement {
601    /// String element
602    StringElement(String),
603    /// Float element
604    FloatElement(f32),
605    /// Int element
606    IntElement(i32),
607    /// Array element
608    ArrayElement(ConfigArray),
609}
610
611impl ConfigArrayElement {
612    fn rapified_length(&self) -> usize {
613        match self {
614            ConfigArrayElement::StringElement(s) => s.len() + 2,
615            ConfigArrayElement::FloatElement(_f) => 5,
616            ConfigArrayElement::IntElement(_i) => 5,
617            ConfigArrayElement::ArrayElement(a) => {
618                1 + compressed_int_len_of(a.elements.len())
619                    + usize::sum(a.elements.iter().map(ConfigArrayElement::rapified_length))
620            }
621        }
622    }
623}
624
625/// Deepest class or array nesting accepted when reading a rapified config: the root class plus the
626/// `MAX_NESTING_DEPTH` levels the text parser accepts, so every config this crate writes reads back.
627const MAX_RAPIFIED_DEPTH: u32 = 129;
628
629/// Most entries and array elements accepted in one rapified config.
630const MAX_RAPIFIED_ENTRIES: u64 = 4_000_000;
631
632/// Limits that keep reading a crafted rapified config from running away.
633struct ReadBudget {
634    depth: u32,
635    remaining: u64,
636    /// Offsets of the class bodies being read, to catch bodies that contain themselves.
637    open_bodies: Vec<u32>,
638    /// Offsets of every class body read so far. Real configs never share a body between classes; a file
639    /// that does can make the output exponentially larger than the input.
640    seen_bodies: HashSet<u32>,
641}
642
643impl ReadBudget {
644    fn new() -> Self {
645        ReadBudget {
646            depth: 0,
647            remaining: MAX_RAPIFIED_ENTRIES,
648            open_bodies: Vec::new(),
649            seen_bodies: HashSet::new(),
650        }
651    }
652
653    fn enter(&mut self) -> Result<(), Error> {
654        if self.depth >= MAX_RAPIFIED_DEPTH {
655            return Err(error!(
656                "Rapified config nesting is deeper than {MAX_RAPIFIED_DEPTH} levels."
657            ));
658        }
659        self.depth += 1;
660        Ok(())
661    }
662
663    fn leave(&mut self) {
664        self.depth = self.depth.saturating_sub(1);
665    }
666
667    fn take_entry(&mut self) -> Result<(), Error> {
668        self.remaining = self
669            .remaining
670            .checked_sub(1)
671            .ok_or_else(|| error!("Rapified config has too many entries."))?;
672        Ok(())
673    }
674}
675
676impl ConfigArray {
677    /// The array's elements.
678    #[must_use]
679    pub fn elements(&self) -> &[ConfigArrayElement] {
680        &self.elements
681    }
682
683    /// Whether this is an array expansion (`x[] += {...}`).
684    #[must_use]
685    pub fn is_expansion(&self) -> bool {
686        self.is_expansion
687    }
688
689    fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
690        output.write_all(b"{")?;
691        for (key, value) in self.elements.iter().enumerate() {
692            match value {
693                ConfigArrayElement::ArrayElement(a) => {
694                    a.write(output)?;
695                }
696                ConfigArrayElement::StringElement(s) => {
697                    output.write_all(
698                        format!(
699                            "\"{}\"",
700                            s.replace('\r', "\\r")
701                                .replace('\n', "\\n")
702                                .replace('"', "\"\"")
703                        )
704                        .as_bytes(),
705                    )?;
706                }
707                ConfigArrayElement::FloatElement(f) => {
708                    output.write_all(float_literal(*f).as_bytes())?;
709                }
710                ConfigArrayElement::IntElement(i) => {
711                    output.write_all(format!("{i}").as_bytes())?;
712                }
713            }
714            if key < self.elements.len() - 1 {
715                output.write_all(b", ")?;
716            }
717        }
718        output.write_all(b"}")?;
719        Ok(())
720    }
721
722    fn write_rapified<O: Write>(&self, output: &mut O) -> Result<usize, Error> {
723        let num_elements = u32::try_from(self.elements.len())
724            .map_err(|_| error!("too many array elements: {}", self.elements.len()))?;
725        let mut written = output.write_compressed_int(num_elements)?;
726
727        for (index, element) in self.elements.iter().enumerate() {
728            match element {
729                ConfigArrayElement::StringElement(s) => {
730                    output.write_all(&[0])?;
731                    output
732                        .write_cstring(s)
733                        .prepend_error(format!("Array element {index}:"))?;
734                    written += s.len() + 2;
735                }
736                ConfigArrayElement::FloatElement(f) => {
737                    output.write_all(&[1])?;
738                    output.write_f32::<LittleEndian>(*f)?;
739                    written += 5;
740                }
741                ConfigArrayElement::IntElement(i) => {
742                    output.write_all(&[2])?;
743                    output.write_i32::<LittleEndian>(*i)?;
744                    written += 5;
745                }
746                ConfigArrayElement::ArrayElement(a) => {
747                    output.write_all(&[3])?;
748                    written += 1 + a
749                        .write_rapified(output)
750                        .prepend_error(format!("Array element {index}:"))?;
751                }
752            }
753        }
754
755        Ok(written)
756    }
757
758    fn read_rapified<I: Read + Seek>(
759        input: &mut I,
760        budget: &mut ReadBudget,
761    ) -> Result<ConfigArray, Error> {
762        budget.enter()?;
763        let result = ConfigArray::read_rapified_elements(input, budget);
764        budget.leave();
765        result
766    }
767
768    fn read_rapified_elements<I: Read + Seek>(
769        input: &mut I,
770        budget: &mut ReadBudget,
771    ) -> Result<ConfigArray, Error> {
772        let num_elements: u32 = input.read_compressed_int()?;
773        // never preallocate the full length from untrusted input
774        let mut elements: Vec<ConfigArrayElement> =
775            Vec::with_capacity(num_elements.min(65536) as usize);
776
777        for _i in 0..num_elements {
778            budget.take_entry()?;
779            let mut buf = [0u8; 1];
780            input.read_exact(&mut buf)?;
781            let element_type = buf[0];
782
783            if element_type == 0 {
784                elements.push(ConfigArrayElement::StringElement(input.read_cstring()?));
785            } else if element_type == 1 {
786                elements.push(ConfigArrayElement::FloatElement(
787                    input.read_f32::<LittleEndian>()?,
788                ));
789            } else if element_type == 2 {
790                elements.push(ConfigArrayElement::IntElement(
791                    input.read_i32::<LittleEndian>()?,
792                ));
793            } else if element_type == 3 {
794                elements.push(ConfigArrayElement::ArrayElement(
795                    ConfigArray::read_rapified(input, budget)?,
796                ));
797            } else {
798                return Err(error!("Unrecognized array element type: {}", element_type));
799            }
800        }
801
802        Ok(ConfigArray {
803            is_expansion: false,
804            elements,
805        })
806    }
807}
808
809impl ConfigEntry {
810    // without the name
811    fn rapified_length(&self) -> usize {
812        match self {
813            ConfigEntry::StringEntry(s) => s.len() + 3,
814            ConfigEntry::FloatEntry(_f) => 6,
815            ConfigEntry::IntEntry(_i) => 6,
816            ConfigEntry::Int64Entry(_i) => 10,
817            ConfigEntry::ArrayEntry(a) => {
818                let len = 1
819                    + compressed_int_len_of(a.elements.len())
820                    + usize::sum(a.elements.iter().map(ConfigArrayElement::rapified_length));
821                if a.is_expansion { len + 4 } else { len }
822            }
823            ConfigEntry::ClassEntry(c) => {
824                if c.is_external || c.is_deletion {
825                    1
826                } else {
827                    5
828                }
829            }
830        }
831    }
832}
833
834impl ConfigClass {
835    /// The parent class name, or `None` when the class has no parent.
836    #[must_use]
837    pub fn parent(&self) -> Option<&str> {
838        if self.parent.is_empty() {
839            None
840        } else {
841            Some(&self.parent)
842        }
843    }
844
845    /// Whether this is an external declaration (`class X;`).
846    #[must_use]
847    pub fn is_external(&self) -> bool {
848        self.is_external
849    }
850
851    /// Whether this is a deletion (`delete X;`).
852    #[must_use]
853    pub fn is_deletion(&self) -> bool {
854        self.is_deletion
855    }
856
857    /// The entries in file order; empty for external classes and deletions.
858    pub fn entries(&self) -> impl Iterator<Item = (&str, &ConfigEntry)> {
859        self.entries
860            .iter()
861            .flatten()
862            .map(|(name, entry)| (name.as_str(), entry))
863    }
864
865    /// Looks up an entry by name, ASCII case-insensitively like the game.
866    ///
867    /// Returns the first entry with that name; use [`ConfigClass::entries`] to see every entry
868    /// when a config defines a name twice. A `delete X;` entry comes back
869    /// as [`ConfigEntry::ClassEntry`] with [`ConfigClass::is_deletion`] `true`.
870    #[must_use]
871    pub fn get(&self, name: &str) -> Option<&ConfigEntry> {
872        self.entries()
873            .find(|(n, _)| n.eq_ignore_ascii_case(name))
874            .map(|(_, entry)| entry)
875    }
876
877    fn write<O: Write>(&self, output: &mut O, level: usize, indent: &str) -> Result<(), Error> {
878        if let Some(entries) = &self.entries {
879            if level > 0 && !entries.is_empty() {
880                output.write_all(b"\n")?;
881            }
882            for (key, value) in entries {
883                text_name(key, "Entry")?;
884                output.write_all(indent.repeat(level).as_bytes())?;
885
886                match value {
887                    ConfigEntry::ClassEntry(c) => {
888                        if c.is_deletion {
889                            output.write_all(format!("delete {key};\n").as_bytes())?;
890                        } else if c.is_external {
891                            output.write_all(format!("class {key};\n").as_bytes())?;
892                        } else {
893                            let parent = if c.parent.is_empty() {
894                                String::new()
895                            } else {
896                                text_name(&c.parent, "Parent class")?;
897                                format!(": {}", c.parent)
898                            };
899                            match &c.entries {
900                                Some(entries) => {
901                                    if entries.is_empty() {
902                                        output.write_all(
903                                            format!("class {key}{parent} {{}};\n").as_bytes(),
904                                        )?;
905                                    } else {
906                                        output.write_all(
907                                            format!("class {key}{parent} {{").as_bytes(),
908                                        )?;
909                                        c.write(output, level + 1, indent)?;
910                                        output.write_all(indent.repeat(level).as_bytes())?;
911                                        output.write_all(b"};\n")?;
912                                    }
913                                }
914                                None => {
915                                    output.write_all(
916                                        format!("class {key}{parent} {{}};\n").as_bytes(),
917                                    )?;
918                                }
919                            }
920                        }
921                    }
922                    ConfigEntry::StringEntry(s) => {
923                        output.write_all(
924                            format!(
925                                "{} = \"{}\";\n",
926                                key,
927                                s.replace('\r', "\\r")
928                                    .replace('\n', "\\n")
929                                    .replace('"', "\"\"")
930                            )
931                            .as_bytes(),
932                        )?;
933                    }
934                    ConfigEntry::FloatEntry(f) => {
935                        output.write_all(format!("{key} = {};\n", float_literal(*f)).as_bytes())?;
936                    }
937                    ConfigEntry::IntEntry(i) => {
938                        output.write_all(format!("{key} = {i};\n").as_bytes())?;
939                    }
940                    ConfigEntry::Int64Entry(i) => {
941                        output.write_all(format!("{key} = {i};\n").as_bytes())?;
942                    }
943                    ConfigEntry::ArrayEntry(a) => {
944                        if a.is_expansion {
945                            output.write_all(format!("{key}[] += ").as_bytes())?;
946                        } else {
947                            output.write_all(format!("{key}[] = ").as_bytes())?;
948                        }
949                        a.write(output)?;
950                        output.write_all(b";\n")?;
951                    }
952                }
953            }
954        }
955
956        Ok(())
957    }
958
959    fn rapified_length(&self) -> usize {
960        match &self.entries {
961            Some(entries) => {
962                self.parent.len()
963                    + 1
964                    + compressed_int_len_of(entries.len())
965                    + usize::sum(entries.iter().map(|(k, v)| {
966                        k.len()
967                            + 1
968                            + v.rapified_length()
969                            + match v {
970                                ConfigEntry::ClassEntry(c) => c.rapified_length(),
971                                _ => 0,
972                            }
973                    }))
974            }
975            None => 0,
976        }
977    }
978
979    fn write_rapified<O: Write>(&self, output: &mut O, offset: usize) -> Result<usize, Error> {
980        let mut written = 0;
981
982        match &self.entries {
983            Some(entries) => {
984                output.write_cstring(&self.parent)?;
985                written += self.parent.len() + 1;
986
987                let num_entries = u32::try_from(entries.len())
988                    .map_err(|_| error!("too many class entries: {}", entries.len()))?;
989                written += output.write_compressed_int(num_entries)?;
990
991                let entries_len = usize::sum(
992                    entries
993                        .iter()
994                        .map(|(k, v)| k.len() + 1 + v.rapified_length()),
995                );
996                let mut class_offset = offset + written + entries_len;
997                let mut class_bodies: Vec<Cursor<Box<[u8]>>> = Vec::new();
998                let pre_entries = written;
999
1000                for (name, entry) in entries {
1001                    let pre_write = written;
1002                    match entry {
1003                        ConfigEntry::StringEntry(s) => {
1004                            output.write_all(&[1, 0])?;
1005                            output
1006                                .write_cstring(name)
1007                                .and_then(|()| output.write_cstring(s))
1008                                .prepend_error(format!("Entry \"{}\":", printable(name)))?;
1009                            written += name.len() + s.len() + 4;
1010                        }
1011                        ConfigEntry::FloatEntry(f) => {
1012                            output.write_all(&[1, 1])?;
1013                            output.write_cstring(name)?;
1014                            output.write_f32::<LittleEndian>(*f)?;
1015                            written += name.len() + 7;
1016                        }
1017                        ConfigEntry::IntEntry(i) => {
1018                            output.write_all(&[1, 2])?;
1019                            output.write_cstring(name)?;
1020                            output.write_i32::<LittleEndian>(*i)?;
1021                            written += name.len() + 7;
1022                        }
1023                        ConfigEntry::Int64Entry(i) => {
1024                            output.write_all(&[1, 6])?;
1025                            output.write_cstring(name)?;
1026                            output.write_i64::<LittleEndian>(*i)?;
1027                            written += name.len() + 11;
1028                        }
1029                        ConfigEntry::ArrayEntry(a) => {
1030                            output.write_all(if a.is_expansion { &[5] } else { &[2] })?;
1031                            if a.is_expansion {
1032                                output.write_all(&[1, 0, 0, 0])?;
1033                                written += 4;
1034                            }
1035                            output.write_cstring(name)?;
1036                            written += name.len()
1037                                + 2
1038                                + a.write_rapified(output)
1039                                    .prepend_error(format!("Entry \"{}\":", printable(name)))?;
1040                        }
1041                        ConfigEntry::ClassEntry(c) => {
1042                            if c.is_external || c.is_deletion {
1043                                output.write_all(if c.is_deletion { &[4] } else { &[3] })?;
1044                                output.write_cstring(name)?;
1045                                written += name.len() + 2;
1046                            } else {
1047                                output.write_all(&[0])?;
1048                                output.write_cstring(name)?;
1049                                let class_offset_u32 =
1050                                    u32::try_from(class_offset).map_err(|_| {
1051                                        error!("class body offset out of range: {class_offset}")
1052                                    })?;
1053                                output.write_u32::<LittleEndian>(class_offset_u32)?;
1054                                written += name.len() + 6;
1055
1056                                let buffer: Box<[u8]> =
1057                                    vec![0; c.rapified_length()].into_boxed_slice();
1058                                let mut cursor: Cursor<Box<[u8]>> = Cursor::new(buffer);
1059                                class_offset +=
1060                                    c.write_rapified(&mut cursor, class_offset).prepend_error(
1061                                        format!("Failed to rapify {}:", printable(name)),
1062                                    )?;
1063
1064                                class_bodies.push(cursor);
1065                            }
1066                        }
1067                    }
1068                    assert_eq!(
1069                        written - pre_write,
1070                        entry.rapified_length() + name.len() + 1
1071                    );
1072                }
1073
1074                assert_eq!(written - pre_entries, entries_len);
1075
1076                for cursor in class_bodies {
1077                    output.write_all(cursor.get_ref())?;
1078                    written += cursor.get_ref().len();
1079                }
1080            }
1081            None => {
1082                return Err(error!("Cannot rapify a class without entries."));
1083            }
1084        }
1085
1086        Ok(written)
1087    }
1088
1089    fn read_rapified<I: Read + Seek>(
1090        input: &mut I,
1091        level: u32,
1092        budget: &mut ReadBudget,
1093    ) -> Result<ConfigClass, Error> {
1094        let mut fp = 0;
1095        let body_offset: u32 = if level == 0 {
1096            input.seek(SeekFrom::Start(16))?;
1097            16
1098        } else {
1099            let classbody_fp: u32 = input.read_u32::<LittleEndian>()?;
1100
1101            fp = input.stream_position()?;
1102            input.seek(SeekFrom::Start(classbody_fp.into()))?;
1103            classbody_fp
1104        };
1105
1106        if budget.open_bodies.contains(&body_offset) {
1107            return Err(error!("Rapified class body cycle at offset {body_offset}."));
1108        }
1109        if !budget.seen_bodies.insert(body_offset) {
1110            return Err(error!(
1111                "Rapified class body shared at offset {body_offset}."
1112            ));
1113        }
1114        budget.enter()?;
1115        budget.open_bodies.push(body_offset);
1116        let result = ConfigClass::read_rapified_body(input, level, budget);
1117        budget.open_bodies.pop();
1118        budget.leave();
1119        let class = result?;
1120
1121        if level > 0 {
1122            input.seek(SeekFrom::Start(fp))?;
1123        }
1124
1125        Ok(class)
1126    }
1127
1128    fn read_rapified_body<I: Read + Seek>(
1129        input: &mut I,
1130        level: u32,
1131        budget: &mut ReadBudget,
1132    ) -> Result<ConfigClass, Error> {
1133        let parent = input.read_cstring()?;
1134        let num_entries: u32 = input.read_compressed_int()?;
1135        // never preallocate the full length from untrusted input
1136        let mut entries: Vec<(String, ConfigEntry)> =
1137            Vec::with_capacity(num_entries.min(65536) as usize);
1138
1139        for _i in 0..num_entries {
1140            budget.take_entry()?;
1141            let mut buf = [0u8; 1];
1142            input.read_exact(&mut buf)?;
1143            let entry_type = buf[0];
1144
1145            if entry_type == 0 {
1146                let name = input.read_cstring()?;
1147
1148                let class_entry = ConfigClass::read_rapified(input, level + 1, budget)
1149                    .prepend_error(format!(
1150                        "Failed to read rapified class \"{}\":",
1151                        printable(&name)
1152                    ))?;
1153                entries.push((name, ConfigEntry::ClassEntry(class_entry)));
1154            } else if entry_type == 1 {
1155                let mut buf = [0u8; 1];
1156                input.read_exact(&mut buf)?;
1157                let subtype = buf[0];
1158                let name = input.read_cstring()?;
1159
1160                if subtype == 0 {
1161                    entries.push((name, ConfigEntry::StringEntry(input.read_cstring()?)));
1162                } else if subtype == 1 {
1163                    entries.push((
1164                        name,
1165                        ConfigEntry::FloatEntry(input.read_f32::<LittleEndian>()?),
1166                    ));
1167                } else if subtype == 2 {
1168                    entries.push((
1169                        name,
1170                        ConfigEntry::IntEntry(input.read_i32::<LittleEndian>()?),
1171                    ));
1172                } else if subtype == 6 {
1173                    entries.push((
1174                        name,
1175                        ConfigEntry::Int64Entry(input.read_i64::<LittleEndian>()?),
1176                    ));
1177                } else {
1178                    return Err(error!("Unrecognized variable entry subtype: {}.", subtype));
1179                }
1180            } else if entry_type == 2 || entry_type == 5 {
1181                if entry_type == 5 {
1182                    input.seek(SeekFrom::Current(4))?;
1183                }
1184
1185                let name = input.read_cstring()?;
1186                let mut array = ConfigArray::read_rapified(input, budget)
1187                    .prepend_error("Failed to read rapified array:")?;
1188                array.is_expansion = entry_type == 5;
1189
1190                entries.push((name.clone(), ConfigEntry::ArrayEntry(array)));
1191            } else if entry_type == 3 || entry_type == 4 {
1192                let name = input.read_cstring()?;
1193                let class_entry = ConfigClass {
1194                    parent: String::new(),
1195                    is_external: entry_type == 3,
1196                    is_deletion: entry_type == 4,
1197                    entries: None,
1198                };
1199
1200                entries.push((name.clone(), ConfigEntry::ClassEntry(class_entry)));
1201            } else {
1202                return Err(error!("Unrecognized class entry type: {}.", entry_type));
1203            }
1204        }
1205
1206        Ok(ConfigClass {
1207            parent,
1208            is_external: false,
1209            is_deletion: false,
1210            entries: Some(entries),
1211        })
1212    }
1213}
1214
1215/// Options for [`Config::write_with`].
1216#[derive(Debug, Clone, PartialEq, Eq)]
1217#[non_exhaustive]
1218pub struct WriteOptions {
1219    indent: String,
1220}
1221
1222impl Default for WriteOptions {
1223    fn default() -> Self {
1224        Self {
1225            indent: "    ".to_string(),
1226        }
1227    }
1228}
1229
1230impl WriteOptions {
1231    /// The default options: four spaces of indentation.
1232    #[must_use]
1233    pub fn new() -> Self {
1234        Self::default()
1235    }
1236
1237    /// Sets the string written once per nesting level.
1238    ///
1239    /// The string may be empty and may only contain spaces and tabs, at most 64 characters, so the
1240    /// output stays parsable.
1241    ///
1242    /// # Errors
1243    ///
1244    /// Returns an error naming the value if it contains other characters or is too long.
1245    pub fn indent(mut self, indent: impl Into<String>) -> Result<Self, Error> {
1246        let indent = indent.into();
1247        let length = indent.chars().count();
1248        if length > 64 {
1249            return Err(error!(
1250                "Invalid indentation: it is {length} characters, at most 64 are allowed."
1251            ));
1252        }
1253        if !indent.chars().all(|c| c == ' ' || c == '\t') {
1254            return Err(error!(
1255                "Invalid indentation \"{}\": use spaces and tabs only.",
1256                printable(&indent)
1257            ));
1258        }
1259        self.indent = indent;
1260        Ok(self)
1261    }
1262}
1263
1264impl Config {
1265    /// The unnamed top-level class holding all entries of the file.
1266    #[must_use]
1267    pub fn root(&self) -> &ConfigClass {
1268        &self.root_body
1269    }
1270
1271    /// The values of the `enum { ... }` blocks, in source order (or table order for a rapified config).
1272    ///
1273    /// Names are lowercase, as the game stores them. The values of all blocks, at any class level,
1274    /// land in this one table.
1275    #[must_use]
1276    pub fn enum_values(&self) -> &[(String, i32)] {
1277        &self.enums
1278    }
1279
1280    fn rapified_enum_table_length(&self) -> usize {
1281        4 + self
1282            .enums
1283            .iter()
1284            .map(|(n, _)| n.len() + 1 + 4)
1285            .sum::<usize>()
1286    }
1287
1288    /// Writes the config (unrapified) to the output.
1289    ///
1290    /// # Errors
1291    ///
1292    /// Returns an error on I/O failure.
1293    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
1294        self.write_with(output, &WriteOptions::new())
1295    }
1296
1297    /// Writes the config (unrapified) to the output with the given options.
1298    ///
1299    /// # Errors
1300    ///
1301    /// Returns an error on I/O failure or if a name cannot be written as text.
1302    pub fn write_with<O: Write>(
1303        &self,
1304        output: &mut O,
1305        options: &WriteOptions,
1306    ) -> Result<(), Error> {
1307        // check everything before the first byte: a block is never half-written
1308        for (name, _) in &self.enums {
1309            text_name(name, "Enum")?;
1310        }
1311        if !self.enums.is_empty() {
1312            output.write_all(b"enum {\n")?;
1313            for (i, (name, value)) in self.enums.iter().enumerate() {
1314                let comma = if i + 1 < self.enums.len() { "," } else { "" };
1315                output
1316                    .write_all(format!("{}{name} = {value}{comma}\n", options.indent).as_bytes())?;
1317            }
1318            output.write_all(b"};\n")?;
1319        }
1320        self.root_body.write(output, 0, &options.indent)
1321    }
1322
1323    /// Returns the unrapified config as a string.
1324    ///
1325    /// # Errors
1326    ///
1327    /// Returns an error on I/O failure or invalid UTF-8 in the output.
1328    pub fn to_string(&self) -> Result<String, Error> {
1329        let buffer = Vec::new();
1330        let mut cursor: Cursor<Vec<u8>> = Cursor::new(buffer);
1331        self.write(&mut cursor)?;
1332
1333        String::from_utf8(cursor.into_inner())
1334            .map_err(|e| error!("Invalid UTF-8 in config output: {e}"))
1335    }
1336
1337    /// Writes the rapified config to the output.
1338    ///
1339    /// # Errors
1340    ///
1341    /// Returns an error on I/O failure or if the config cannot be rapified.
1342    pub fn write_rapified<O: Write>(&self, output: &mut O) -> Result<(), Error> {
1343        let mut writer = BufWriter::new(output);
1344
1345        writer.write_all(b"\0raP")?;
1346        writer.write_all(b"\0\0\0\0\x08\0\0\0")?; // always_0, always_8
1347
1348        let buffer: Box<[u8]> = vec![0; self.root_body.rapified_length()].into_boxed_slice();
1349        let mut cursor: Cursor<Box<[u8]>> = Cursor::new(buffer);
1350        self.root_body
1351            .write_rapified(&mut cursor, 16)
1352            .prepend_error("Failed to rapify root class:")?;
1353
1354        let enum_offset = u32::try_from(16 + cursor.get_ref().len())
1355            .map_err(|_| error!("config too large: {} bytes", cursor.get_ref().len()))?;
1356        writer.write_u32::<LittleEndian>(enum_offset)?;
1357
1358        writer.write_all(cursor.get_ref())?;
1359
1360        let count = u32::try_from(self.enums.len())
1361            .map_err(|_| error!("too many enum values: {}", self.enums.len()))?;
1362        writer.write_u32::<LittleEndian>(count)?;
1363        for (name, value) in &self.enums {
1364            writer.write_all(name.as_bytes())?;
1365            writer.write_all(b"\0")?;
1366            writer.write_i32::<LittleEndian>(*value)?;
1367        }
1368        writer.flush()?;
1369
1370        Ok(())
1371    }
1372
1373    /// Returns the rapified config as a `Cursor`.
1374    ///
1375    /// # Errors
1376    ///
1377    /// Returns an error if the config cannot be rapified.
1378    pub fn to_cursor(&self) -> Result<Cursor<Box<[u8]>>, Error> {
1379        let len = self.root_body.rapified_length() + 16 + self.rapified_enum_table_length();
1380
1381        let buffer: Box<[u8]> = vec![0; len].into_boxed_slice();
1382        let mut cursor: Cursor<Box<[u8]>> = Cursor::new(buffer);
1383        self.write_rapified(&mut cursor)?;
1384
1385        Ok(cursor)
1386    }
1387
1388    /// Reads the unrapified config from input, preprocessing it.
1389    ///
1390    /// `path` is the path to the input if it is known and is used for relative includes and error
1391    /// messages. `includefolders` are the folders searched recursively for absolute includes.
1392    ///
1393    /// # Errors
1394    ///
1395    /// Returns an error on preprocessing or parse failures.
1396    pub fn read<I: Read>(
1397        input: &mut I,
1398        path: Option<PathBuf>,
1399        includefolders: &[PathBuf],
1400        warnings: &mut dyn WarningSink,
1401    ) -> Result<Config, Error> {
1402        Self::read_in(
1403            input,
1404            path,
1405            &IncludeFolders::new(includefolders.to_vec()),
1406            warnings,
1407        )
1408    }
1409
1410    /// Like [`Config::read`], with the include folders given as an [`IncludeFolders`] (some of them can be checked
1411    /// directly instead of searched recursively).
1412    ///
1413    /// # Errors
1414    ///
1415    /// Returns an error on preprocessing or parse failures.
1416    pub fn read_in<I: Read>(
1417        input: &mut I,
1418        path: Option<PathBuf>,
1419        includefolders: &IncludeFolders,
1420        warnings: &mut dyn WarningSink,
1421    ) -> Result<Config, Error> {
1422        let mut bytes = Vec::new();
1423        input
1424            .read_to_end(&mut bytes)
1425            .prepend_error("Failed to read input file:")?;
1426        if is_rapified(&bytes) {
1427            return Config::read_rapified(&mut Cursor::new(bytes));
1428        }
1429        let buffer =
1430            String::from_utf8(bytes).map_err(|e| error!("Failed to read input file: {}", e))?;
1431        let (preprocessed, info) = preprocess_in(buffer, path, includefolders, warnings)
1432            .prepend_error("Failed to preprocess config:")?;
1433
1434        // The preprocessor ends its output with a line end. A file whose last source line is an entry
1435        // (not empty, a directive, a comment or inside an unterminated comment) has no line end of its own there, so that entry ends at the end of the file, which CfgConvert
1436        // rejects unless it is closed by `;` or `}`.
1437        let preprocessed = match preprocessed.strip_suffix('\n') {
1438            Some(text) if info.ends_in_entry => text.to_string(),
1439            _ => preprocessed,
1440        };
1441
1442        let mut found = ConfigWarnings(Vec::new());
1443
1444        let mut ctx = EvalCtx::default();
1445        let parsed = config_grammar::config(&preprocessed, &mut found, &mut ctx);
1446        // The line the parse failed on starts at `failed_line_start`. Warnings raised from there on are by
1447        // the attempts that failed (`x = 1 // c` is tried as an unquoted string first), not about the
1448        // input, so they are dropped; the ones from earlier lines are real and stay. One search for the
1449        // line start, so the filter is linear in the number of warnings.
1450        let failed_at = match (&ctx.error, &parsed) {
1451            (Some((pos, _)), _) => Some(*pos),
1452            (None, Err(pe)) => Some(pe.location.offset),
1453            (None, Ok(_)) => None,
1454        };
1455        if let Some(at) = failed_at {
1456            let before = preprocessed.get(..at).unwrap_or(&preprocessed);
1457            let failed_line_start = before.rfind('\n').map_or(0, |i| i + 1);
1458            found.0.retain(|w| w.0 < failed_line_start);
1459        }
1460        let result = match ctx.error.take() {
1461            Some((pos, e)) => Err(located_error(&info, &preprocessed, pos, &e)),
1462            _ => ConfigParseErrorExt::format_error(parsed, &info, &preprocessed),
1463        };
1464
1465        // PEG backtracking runs rule actions more than once; report each warning once.
1466        let mut seen = std::collections::HashSet::new();
1467        found.0.retain(|w| seen.insert((w.0, w.1.clone())));
1468
1469        for w in found.0 {
1470            let location = if warnings.is_suppressed(w.2) {
1471                (None, None)
1472            } else {
1473                let lines_before = preprocessed[..w.0].chars().filter(|c| c == &'\n').count();
1474                let idx = min(lines_before, info.line_origins.len().saturating_sub(1)); // origins are 1-based line numbers
1475                let file = info
1476                    .line_origins
1477                    .get(idx)
1478                    .and_then(|o| o.1.as_ref())
1479                    .map(|p| p.display().to_string());
1480                let line = match info.line_origins.get(idx) {
1481                    Some(o) => o.0,
1482                    None => u32::try_from(lines_before + 1)
1483                        .map_err(|_| error!("line number out of range"))?,
1484                };
1485
1486                (file, Some(line))
1487            };
1488
1489            let mut warning = Warning::new(w.2, w.1);
1490            if let Some(file) = location.0 {
1491                warning = warning.in_file(file);
1492            }
1493            if let Some(line) = location.1 {
1494                warning = warning.at_line(line);
1495            }
1496            warnings.warn(warning);
1497        }
1498
1499        result
1500    }
1501
1502    /// Preprocesses and parses input string.
1503    ///
1504    /// `path` is the path to the input if it is known and is used for relative includes and error
1505    /// messages. `includefolders` are the folders searched recursively for absolute includes.
1506    ///
1507    /// # Errors
1508    ///
1509    /// Returns an error on preprocessing or parse failures.
1510    pub fn from_string(
1511        input: String,
1512        path: Option<PathBuf>,
1513        includefolders: &[PathBuf],
1514        warnings: &mut dyn WarningSink,
1515    ) -> Result<Config, Error> {
1516        let mut cursor = Cursor::new(input.into_bytes());
1517        Self::read(&mut cursor, path, includefolders, warnings)
1518    }
1519
1520    /// Like [`Config::from_string`], with the include folders given as an [`IncludeFolders`].
1521    ///
1522    /// # Errors
1523    ///
1524    /// Returns an error on preprocessing or parse failures.
1525    pub fn from_string_in(
1526        input: String,
1527        path: Option<PathBuf>,
1528        includefolders: &IncludeFolders,
1529        warnings: &mut dyn WarningSink,
1530    ) -> Result<Config, Error> {
1531        let mut cursor = Cursor::new(input.into_bytes());
1532        Self::read_in(&mut cursor, path, includefolders, warnings)
1533    }
1534
1535    /// Reads the rapified config from input.
1536    ///
1537    /// # Errors
1538    ///
1539    /// Returns an error if the input is not a rapified config or cannot be parsed.
1540    pub fn read_rapified<I: Read + Seek>(input: &mut I) -> Result<Config, Error> {
1541        let mut reader = BufReader::new(input);
1542
1543        let mut buffer = [0; 4];
1544        reader.read_exact(&mut buffer)?;
1545
1546        if &buffer != b"\0raP" {
1547            return Err(error!("File doesn't seem to be a rapified config."));
1548        }
1549
1550        let root_body = ConfigClass::read_rapified(&mut reader, 0, &mut ReadBudget::new())?;
1551        let enums = read_enum_table(&mut reader);
1552
1553        Ok(Config { root_body, enums })
1554    }
1555}