wc3 0.2.0

Read, edit, and write Warcraft III models, BLP textures, and MPQ archives
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
use super::Read;
use super::{Lexer, Span, Token, TokenKind};
use crate::model::mdl;
use crate::model::FixedText;
use std::iter::FusedIterator;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};

/// Read records, properties, or list entries from an MDL source string.
///
/// For a whole value, prefer [`Read::decode_mdl`], which also checks trailing
/// input. Failed reads may advance this parser; copy it before a speculative
/// read when you need to restore the earlier position.
#[derive(Clone, Copy, Debug)]
pub struct Parser<'a> {
    lexer: Lexer<'a>,
    lookahead: Option<Result<Token<'a>, mdl::ReadError>>,
}

impl<'a> Parser<'a> {
    /// Starts a parser at the beginning of the source.
    pub fn new(source: &'a str) -> Self {
        Self {
            lexer: Lexer::new(source),
            lookahead: None,
        }
    }
    /// Returns the original source for diagnostic formatting.
    pub fn source(&self) -> &'a str {
        self.lexer.source()
    }
    /// Returns the next buffered token's start, or the lexer's current byte offset.
    pub fn position(&self) -> usize {
        match self.lookahead {
            Some(Ok(token)) => token.span.start,
            Some(Err(error)) => error.span.start,
            None => self.lexer.position(),
        }
    }
    /// Returns the next token without consuming it, or `None` at EOF.
    pub fn peek(&mut self) -> Result<Option<Token<'a>>, mdl::ReadError> {
        if self.lookahead.is_none() {
            self.lookahead = self.lexer.next();
        }
        self.lookahead.transpose()
    }
    /// Consumes the next token, reporting an error at EOF.
    pub fn next_token(&mut self) -> Result<Token<'a>, mdl::ReadError> {
        let token = self
            .peek()?
            .ok_or_else(|| self.error(mdl::ReadErrorKind::Expected("a token")))?;
        self.lookahead = None;
        Ok(token)
    }
    /// Builds a diagnostic at the buffered token or current byte position.
    pub fn error(&self, kind: mdl::ReadErrorKind) -> mdl::ReadError {
        let span = match self.lookahead {
            Some(Ok(token)) => token.span,
            Some(Err(error)) => error.span,
            None => Span::new(self.position(), self.position()),
        };
        mdl::ReadError::new(span, kind)
    }
    /// Consumes a token only if its kind and contents exactly match `kind`.
    pub fn expect(&mut self, kind: TokenKind<'a>) -> Result<Token<'a>, mdl::ReadError> {
        let expected = match kind {
            TokenKind::Ident(_) => "the named identifier",
            TokenKind::Number(_) => "the numeric literal",
            TokenKind::Quoted(_) => "the quoted string",
            TokenKind::OpenBrace => "'{'",
            TokenKind::CloseBrace => "'}'",
            TokenKind::Comma => "','",
            TokenKind::Colon => "':'",
            TokenKind::Slot => "'<='",
        };
        match self.peek()? {
            Some(token) if token.kind == kind => self.next_token(),
            _ => Err(self.error(mdl::ReadErrorKind::Expected(expected))),
        }
    }
    /// Consumes the named identifier, matching its spelling exactly.
    pub fn expect_ident(&mut self, name: &'static str) -> Result<(), mdl::ReadError> {
        match self.peek()? {
            Some(Token {
                kind: TokenKind::Ident(actual),
                ..
            }) if actual == name => {
                self.next_token()?;
                Ok(())
            }
            _ => Err(self.error(mdl::ReadErrorKind::Expected(name))),
        }
    }
    /// Consumes a matching token and returns `true`; a mismatch leaves it buffered.
    pub fn consume(&mut self, kind: TokenKind<'a>) -> Result<bool, mdl::ReadError> {
        if self.peek()?.is_some_and(|token| token.kind == kind) {
            self.next_token()?;
            Ok(true)
        } else {
            Ok(false)
        }
    }
    /// Reads one value using its MDL codec.
    pub fn read<T: Read>(&mut self) -> Result<T, mdl::ReadError> {
        T::read_mdl(self)
    }
    /// Reads a value followed by its required comma separator.
    pub fn read_property<T: Read>(&mut self) -> Result<T, mdl::ReadError> {
        let value = self.read()?;
        self.expect(TokenKind::Comma)?;
        Ok(value)
    }
    /// Borrows a literal string. Backslashes and embedded CR/LF are unchanged.
    pub fn read_string(&mut self) -> Result<&'a str, mdl::ReadError> {
        match self.peek()? {
            Some(Token {
                kind: TokenKind::Quoted(value),
                ..
            }) => {
                self.next_token()?;
                Ok(value)
            }
            _ => Err(self.error(mdl::ReadErrorKind::Expected("a quoted string"))),
        }
    }
    /// Reads a quoted string into a fixed-width text field.
    pub fn read_fixed_text<const N: usize>(&mut self) -> Result<FixedText<N>, mdl::ReadError> {
        self.peek()?;
        let span = self
            .error(mdl::ReadErrorKind::Expected("a quoted string"))
            .span;
        let value = self.read_string()?;
        let mut text = FixedText::default();
        text.set_text(value).map_err(|_| {
            mdl::ReadError::new(
                span,
                mdl::ReadErrorKind::InvalidString {
                    max_bytes: N.saturating_sub(1),
                },
            )
        })?;
        Ok(text)
    }
    /// Enters a body at its opening brace; does not scan ahead to its end.
    pub fn begin_block(&mut self) -> Result<Block<'_, 'a>, mdl::ReadError> {
        self.expect(TokenKind::OpenBrace)?;
        Ok(Block {
            parser: self,
            ended: false,
            closing_span: None,
        })
    }
    /// Enters a count-prefixed body, yielding structured items on demand.
    /// Each item's Read implementation owns its punctuation.
    pub fn counted<T: Read>(&mut self) -> Result<Counted<'_, 'a, T>, mdl::ReadError> {
        self.counted_with_header(|_| Ok(())).map(|(_, items)| items)
    }
    /// Enters a counted body whose metadata precedes its counted items.
    /// The header reader runs after the opening brace; metadata does not count
    /// toward the declared item count. Items still own their punctuation.
    pub fn counted_with_header<T: Read, H>(
        &mut self,
        header: impl FnOnce(&mut Self) -> Result<H, mdl::ReadError>,
    ) -> Result<(H, Counted<'_, 'a, T>), mdl::ReadError> {
        let expected = self.read::<u32>()? as usize;
        self.expect(TokenKind::OpenBrace)?;
        let header = header(self)?;
        Ok((
            header,
            Counted {
                parser: self,
                expected,
                actual: 0,
                ended: false,
                failure: None,
                marker: PhantomData,
            },
        ))
    }
    /// Requires EOF after skipping whitespace and comments.
    pub fn finish(&mut self) -> Result<(), mdl::ReadError> {
        if self.peek()?.is_none() {
            Ok(())
        } else {
            Err(self.error(mdl::ReadErrorKind::TrailingInput))
        }
    }
}

/// A block field's borrowed identifier and its source range.
/// Unlike a lexical token, a field always has an identifier name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Field<'a> {
    /// The field identifier borrowed from the source.
    pub name: &'a str,
    /// The byte range of the field name, excluding its value.
    pub span: Span,
}

/// A scoped block body. Consume fields through next_field, then call finish.
/// Dropping a body does not consume or validate any remaining input.
pub struct Block<'p, 'a> {
    parser: &'p mut Parser<'a>,
    ended: bool,
    closing_span: Option<Span>,
}
impl<'a> Block<'_, 'a> {
    /// Returns the next field name, or consumes the closing brace and returns None.
    /// The caller must consume the field's value and punctuation before calling again.
    pub fn next_field(&mut self) -> Result<Option<Field<'a>>, mdl::ReadError> {
        if self.ended {
            return Ok(None);
        }
        if let Some(token) = self.parser.peek()? {
            if token.kind == TokenKind::CloseBrace {
                self.parser.next_token()?;
                self.closing_span = Some(token.span);
                self.ended = true;
                return Ok(None);
            }
        }
        match self.parser.peek()? {
            Some(Token {
                kind: TokenKind::Ident(name),
                span,
            }) => {
                self.parser.next_token()?;
                Ok(Some(Field { name, span }))
            }
            _ => Err(self
                .parser
                .error(mdl::ReadErrorKind::Expected("a field name or '}'"))),
        }
    }
    /// Reports an error at the closing brace when this body has ended.
    pub fn error(&self, kind: mdl::ReadErrorKind) -> mdl::ReadError {
        match self.closing_span {
            Some(span) => mdl::ReadError::new(span, kind),
            None => self.parser.error(kind),
        }
    }
    /// Rejects an unread field rather than silently skipping it.
    pub fn finish(mut self) -> Result<(), mdl::ReadError> {
        if !self.ended {
            self.parser.expect(TokenKind::CloseBrace)?;
            self.ended = true;
        }
        Ok(())
    }
}
impl<'a> Deref for Block<'_, 'a> {
    type Target = Parser<'a>;
    fn deref(&self) -> &Self::Target {
        self.parser
    }
}
impl DerefMut for Block<'_, '_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.parser
    }
}

/// A fallible streaming list. Exhaustion validates the declared count and closing
/// brace; callers that stop early must call finish, which drains and validates.
pub struct Counted<'p, 'a, T> {
    parser: &'p mut Parser<'a>,
    expected: usize,
    actual: usize,
    ended: bool,
    failure: Option<mdl::ReadError>,
    marker: PhantomData<T>,
}
impl<T: Read> Counted<'_, '_, T> {
    /// Returns the count declared before the opening brace.
    pub fn declared_count(&self) -> usize {
        self.expected
    }
    /// Drains unread items and validates the closing brace and declared count.
    pub fn finish(mut self) -> Result<(), mdl::ReadError> {
        for value in self.by_ref() {
            value?;
        }
        self.failure.map_or(Ok(()), Err)
    }
    fn read_next(&mut self) -> Result<Option<T>, mdl::ReadError> {
        let token = self
            .parser
            .peek()?
            .ok_or_else(|| self.parser.error(mdl::ReadErrorKind::Expected("'}'")))?;
        if token.kind == TokenKind::CloseBrace {
            self.parser.next_token()?;
            self.ended = true;
            if self.actual != self.expected {
                return Err(mdl::ReadError::new(
                    token.span,
                    mdl::ReadErrorKind::CountMismatch {
                        expected: self.expected,
                        actual: self.actual,
                    },
                ));
            }
            return Ok(None);
        }
        if self.actual == self.expected {
            return Err(self.parser.error(mdl::ReadErrorKind::CountMismatch {
                expected: self.expected,
                actual: self.actual + 1,
            }));
        }
        let start = self.parser.position();
        let value = self.parser.read()?;
        if self.parser.position() == start {
            return Err(self.parser.error(mdl::ReadErrorKind::NoProgress));
        }
        self.actual += 1;
        Ok(Some(value))
    }
}
impl<T: Read> Iterator for Counted<'_, '_, T> {
    type Item = Result<T, mdl::ReadError>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.ended {
            return None;
        }
        match self.read_next() {
            Ok(value) => value.map(Ok),
            Err(error) => {
                self.ended = true;
                self.failure = Some(error);
                Some(Err(error))
            }
        }
    }
}

impl<T: Read> FusedIterator for Counted<'_, '_, T> {}

macro_rules! integers {
    ($($ty:ty),*) => { $(impl Read for $ty {
        fn read_mdl(parser: &mut Parser<'_>) -> Result<Self, mdl::ReadError> {
            let token = parser.next_token()?;
            match token.kind {
                TokenKind::Number(raw) => raw.parse().map_err(|_| mdl::ReadError::new(token.span, mdl::ReadErrorKind::InvalidNumber(stringify!($ty)))),
                _ => Err(mdl::ReadError::new(token.span, mdl::ReadErrorKind::Expected(stringify!($ty)))),
            }
        }
    })* };
}
integers!(u8, u16, u32, i32);
impl Read for f32 {
    fn read_mdl(parser: &mut Parser<'_>) -> Result<Self, mdl::ReadError> {
        let token = parser.next_token()?;
        let raw = match token.kind {
            TokenKind::Number(raw) | TokenKind::Ident(raw) => raw,
            _ => {
                return Err(mdl::ReadError::new(
                    token.span,
                    mdl::ReadErrorKind::Expected("f32"),
                ))
            }
        };
        let value = if raw.eq_ignore_ascii_case("nan") {
            f32::NAN
        } else if raw.eq_ignore_ascii_case("inf") || raw.eq_ignore_ascii_case("+inf") {
            f32::INFINITY
        } else if raw.eq_ignore_ascii_case("-inf") {
            f32::NEG_INFINITY
        } else {
            // Do not accept Rust's additional spellings or overflow to infinity.
            if !matches!(token.kind, TokenKind::Number(_)) {
                return Err(mdl::ReadError::new(
                    token.span,
                    mdl::ReadErrorKind::InvalidNumber("f32"),
                ));
            }
            let value: f32 = raw.parse().map_err(|_| {
                mdl::ReadError::new(token.span, mdl::ReadErrorKind::InvalidNumber("f32"))
            })?;
            if !value.is_finite() {
                return Err(mdl::ReadError::new(
                    token.span,
                    mdl::ReadErrorKind::InvalidNumber("f32"),
                ));
            }
            value
        };
        Ok(value)
    }
}
impl<T: Read + Default + Copy, const N: usize> Read for [T; N] {
    fn read_mdl(parser: &mut Parser<'_>) -> Result<Self, mdl::ReadError> {
        parser.expect(TokenKind::OpenBrace)?;
        let mut values = [T::default(); N];
        for (i, value) in values.iter_mut().enumerate() {
            if i != 0 {
                parser.expect(TokenKind::Comma)?;
            }
            *value = parser.read()?;
        }
        parser.expect(TokenKind::CloseBrace)?;
        Ok(values)
    }
}
impl<const N: usize> Read for FixedText<N> {
    fn read_mdl(parser: &mut Parser<'_>) -> Result<Self, mdl::ReadError> {
        parser.read_fixed_text()
    }
}