chara 0.2.1

Parser for layered character definition files
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
#![deny(missing_docs)]

//! A parser for layered character definition files.
//!
//! Handles a simple line-based format where:
//! - Each layer starts with its internal name
//! - Optional display name can follow
//! - Variants are listed with `-` prefix
//! - First variant is default
//! - Empty path indicates disabled state

use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
};

/// A single visual variant within a character layer
#[derive(Debug)]
pub struct LayerEntry {
    /// Display name for this variant
    pub name: Box<str>,
    /// Path to image asset; can be empty
    pub path: Box<str>,
}

/// Collection of variants for a logical character layer
#[derive(Debug)]
pub struct LayerGroup {
    /// Machine identifier
    pub internal_name: Box<str>,
    /// Optional human-readable name for UIs
    pub display_name: Option<Box<str>>,
    /// Available variants in declaration order
    pub entries: Vec<LayerEntry>,
}

/// Complete character configuration
#[derive(Debug)]
pub struct CharacterDefinition {
    /// All layers in their original definition order
    pub layers: Vec<LayerGroup>,
}

/// Reasons [`CharacterDefinition::try_parse`] can reject an input
#[derive(Debug)]
pub enum ParseError {
    /// A variant line (`-`) appeared before any layer was declared
    OrphanVariant {
        /// Line number of the offending variant
        line: usize,
    },
    /// A layer was declared without an internal name
    EmptyName {
        /// Line number of the nameless layer
        line: usize,
    },
    /// A layer was declared but contains no variants
    LayerWithoutEntries {
        /// Line number where the empty layer was declared
        line: usize,
    },
    /// Two layers share the same internal name
    DuplicateName {
        /// The repeated internal name
        name: Box<str>,
        /// Line number of the second declaration
        line: usize,
    },
}

impl Display for ParseError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        match self {
            Self::OrphanVariant { line } => {
                write!(formatter, "line {line}: variant declared before any layer")
            }
            Self::EmptyName { line } => {
                write!(formatter, "line {line}: layer without internal name")
            }
            Self::LayerWithoutEntries { line } => {
                write!(formatter, "line {line}: layer has no variants")
            }
            Self::DuplicateName { name, line } => {
                write!(formatter, "line {line}: duplicate layer name '{name}'")
            }
        }
    }
}

impl Error for ParseError {}

enum Line<'a> {
    Layer {
        internal_name: &'a str,
        display_name: Option<&'a str>,
    },
    Variant {
        name: &'a str,
        path: &'a str,
    },
}

fn classify(line: &str) -> Option<Line<'_>> {
    let line = line
        .split_once('#')
        .map_or(line, |(entry, _comment)| entry)
        .trim();
    if line.is_empty() {
        return None;
    }

    if let Some(entry) = line.strip_prefix('-') {
        let entry = entry.trim();
        let (name, path) = entry.split_once(':').map_or((entry, ""), |(name, path)| {
            (name.trim_end(), path.trim_start())
        });
        return Some(Line::Variant { name, path });
    }

    let (internal_name, display_name) = line
        .split_once(':')
        .map_or((line, None), |(internal, display)| {
            (internal.trim(), Some(display.trim()))
        });
    Some(Line::Layer {
        internal_name,
        display_name,
    })
}

impl CharacterDefinition {
    /// Parses character definition from string content
    ///
    /// Lenient: malformed lines (such as a variant before any layer) are
    /// silently ignored. Use [`Self::try_parse`] to reject them instead.
    /// Supports `#` for comments and empty lines are ignored
    ///
    /// # Format
    ///
    /// ```text
    /// # Comment line
    /// [internal_name]: [display_name]  # Inline comment
    /// - [variant_name]: [image_path]
    /// - None  # Special case to disable layer
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// let input = r"
    /// base
    /// - Default: base.png
    ///
    /// expression: Mood
    /// - Happy: happy.png
    /// - Sad: sad.png
    /// ";
    ///
    /// let def = chara::CharacterDefinition::parse(input);
    /// ```
    pub fn parse(input: &str) -> Self {
        let mut layers = Vec::new();
        let mut current_group: Option<LayerGroup> = None;

        for line in input.lines() {
            match classify(line) {
                None => {}
                Some(Line::Variant { name, path }) => {
                    if let Some(group) = &mut current_group {
                        group.entries.push(LayerEntry {
                            name: name.into(),
                            path: path.into(),
                        });
                    }
                }
                Some(Line::Layer {
                    internal_name,
                    display_name,
                }) => {
                    if let Some(group) = current_group.take() {
                        layers.push(group);
                    }
                    current_group = Some(LayerGroup {
                        internal_name: internal_name.into(),
                        display_name: display_name.map(Into::into),
                        entries: Vec::new(),
                    });
                }
            }
        }

        if let Some(group) = current_group.take() {
            layers.push(group);
        }

        Self { layers }
    }

    /// Parses character definition, rejecting malformed input
    ///
    /// Unlike [`Self::parse`], this reports the first structural problem with
    /// its line number instead of silently skipping it.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] for an orphan variant, a layer without an
    /// internal name, a layer with no variants, or a duplicated internal name.
    pub fn try_parse(input: &str) -> Result<Self, ParseError> {
        let mut layers: Vec<LayerGroup> = Vec::new();
        let mut current_group: Option<(LayerGroup, usize)> = None;

        for (index, line) in input.lines().enumerate() {
            let number = index + 1;
            match classify(line) {
                None => {}
                Some(Line::Variant { name, path }) => {
                    let Some((group, _declared)) = &mut current_group else {
                        return Err(ParseError::OrphanVariant { line: number });
                    };
                    group.entries.push(LayerEntry {
                        name: name.into(),
                        path: path.into(),
                    });
                }
                Some(Line::Layer {
                    internal_name,
                    display_name,
                }) => {
                    if internal_name.is_empty() {
                        return Err(ParseError::EmptyName { line: number });
                    }
                    if let Some((group, declared)) = current_group.take() {
                        if group.entries.is_empty() {
                            return Err(ParseError::LayerWithoutEntries { line: declared });
                        }
                        layers.push(group);
                    }
                    if layers
                        .iter()
                        .any(|group| group.internal_name.as_ref() == internal_name)
                    {
                        return Err(ParseError::DuplicateName {
                            name: internal_name.into(),
                            line: number,
                        });
                    }
                    current_group = Some((
                        LayerGroup {
                            internal_name: internal_name.into(),
                            display_name: display_name.map(Into::into),
                            entries: Vec::new(),
                        },
                        number,
                    ));
                }
            }
        }

        if let Some((group, declared)) = current_group.take() {
            if group.entries.is_empty() {
                return Err(ParseError::LayerWithoutEntries { line: declared });
            }
            layers.push(group);
        }

        Ok(Self { layers })
    }
}

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

    #[test]
    fn parses_basic_definition() {
        let input = r"
base
- Default: base.png

expression: Mood
- Happy: happy.png
- Sad: sad.png
";

        let def = CharacterDefinition::parse(input);
        assert_eq!(def.layers.len(), 2);
        assert_eq!(def.layers[0].internal_name.as_ref(), "base");
        assert_eq!(def.layers[1].display_name.as_deref(), Some("Mood"));
        assert_eq!(def.layers[1].entries[1].name.as_ref(), "Sad");
    }

    #[test]
    fn handles_empty_paths() {
        let input = r"
outfit
- Shirt: shirt.png
- None
";

        let def = CharacterDefinition::parse(input);
        assert!(def.layers[0].entries[1].path.is_empty());
    }

    #[test]
    fn ignores_comments() {
        let input = r"
# This is a comment
base  # Base layer comment
- Default: base.png  # Default variant

# Expression group
expression: Mood
- Happy: happy.png
- Sad: sad.png  # Disabled below
- None
";

        let def = CharacterDefinition::parse(input);
        assert_eq!(def.layers.len(), 2);
        assert_eq!(def.layers[0].internal_name.as_ref(), "base");
        assert!(def.layers[1].entries[2].path.is_empty());
    }

    #[test]
    fn handles_inline_comments() {
        let input = r"
base # Important base layer
- Default: base.png # Main variant
- Alternate: alternate.png
";

        let def = CharacterDefinition::parse(input);
        assert_eq!(def.layers[0].entries[0].name.as_ref(), "Default");
        assert_eq!(def.layers[0].entries[1].path.as_ref(), "alternate.png");
    }

    #[test]
    fn try_parse_accepts_valid_input() {
        let input = r"
base
- Default: base.png
";

        let def = CharacterDefinition::try_parse(input).unwrap();
        assert_eq!(def.layers.len(), 1);
    }

    #[test]
    fn try_parse_rejects_orphan_variant() {
        let input = r"
- Default: base.png
";

        assert!(matches!(
            CharacterDefinition::try_parse(input),
            Err(ParseError::OrphanVariant { line: 2 })
        ));
    }

    #[test]
    fn try_parse_rejects_empty_name() {
        let input = r"
: Mood
- Happy: happy.png
";

        assert!(matches!(
            CharacterDefinition::try_parse(input),
            Err(ParseError::EmptyName { line: 2 })
        ));
    }

    #[test]
    fn try_parse_rejects_layer_without_entries() {
        let input = r"
base
- Default: base.png

expression: Mood
";

        assert!(matches!(
            CharacterDefinition::try_parse(input),
            Err(ParseError::LayerWithoutEntries { line: 5 })
        ));
    }

    #[test]
    fn try_parse_rejects_duplicate_name() {
        let input = r"
base
- Default: base.png

base
- Alternate: alternate.png
";

        assert!(matches!(
            CharacterDefinition::try_parse(input),
            Err(ParseError::DuplicateName { line: 5, .. })
        ));
    }
}