multilinear-parser 0.5.1

A parser for the multilinear story systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
#![deny(missing_docs)]

//! The `multilinear-parser` library provides functionality to parse a multilinear system from a text-based format.
//! It allows you to define events, which rely on various aspect specific conditions or changes using a markdown inspired syntax.
//!
//! Example Event Syntax:
//!
//! ```text
//! # Move to Livingroom
//!
//! place: bedroom > livingroom
//!
//! # Get Dressed
//!
//! place: bedroom
//! clothes: pajamas > casual
//! ```
//!
//! Supports logical combinations:
//!
//! ```text
//! (clothes: pajamas | clothes: casual) & place: bedroom
//! ```

pub use index_map::IndexMap;

use header_parsing::parse_header;
use logical_expressions::{LogicalExpression, ParseError};
use thiserror::Error;

use multilinear::{Aspect, Change, Event, InvalidChangeError, MultilinearInfo};

use std::io::{BufRead, BufReader, Read};

mod index_map;

#[derive(Copy, Clone, Debug)]
struct ValueCheckingError(char);

type Str = Box<str>;

fn check_name(name: &str) -> Result<(), ValueCheckingError> {
    if let Some(c) = name
        .chars()
        .find(|&c| !c.is_alphanumeric() && !"_- ".contains(c))
    {
        Err(ValueCheckingError(c))
    } else {
        Ok(())
    }
}

fn valid_name(name: &str) -> Result<&str, ValueCheckingError> {
    let name = name.trim();
    check_name(name)?;
    Ok(name)
}

fn value_index(value_names: &mut Vec<Str>, name: &str) -> Result<usize, ValueCheckingError> {
    let name = valid_name(name)?;

    if let Some(index) = value_names.iter().position(|x| x.as_ref() == name) {
        return Ok(index);
    }

    let index = value_names.len();
    value_names.push(name.into());
    Ok(index)
}

fn aspect_info<'a>(
    aspects: &'a mut AspectMap,
    name: &str,
    info: &mut MultilinearInfo,
) -> Result<(Aspect, &'a mut Vec<Str>), ValueCheckingError> {
    let name = valid_name(name)?;

    if let Some(i) = aspects
        .entries
        .iter()
        .position(|(checked_name, _)| checked_name.as_ref() == name)
    {
        return Ok((Aspect(i), &mut aspects.entries[i].1));
    }

    let aspect = info.add_aspect();
    aspects.insert(aspect, (name.into(), vec!["".into()]));

    let (_, value_names) = aspects.entries.last_mut().unwrap();

    Ok((aspect, value_names))
}

/// Represents errors that can occur when adding an aspect manually.
#[derive(Debug, Error)]
pub enum AspectAddingError {
    /// Indicades that an aspect with this name has already been added.
    #[error("An aspect of this name already exists")]
    AlreadyExists,

    /// Indicates an invalid character was encountered.
    #[error("Invalid character '{0}' for condition names")]
    InvalidCharacter(char),
}

impl From<ValueCheckingError> for AspectAddingError {
    fn from(ValueCheckingError(c): ValueCheckingError) -> Self {
        Self::InvalidCharacter(c)
    }
}

/// Represents errors that can occur when parsing a single aspect default expression.
#[derive(Debug, Error)]
pub enum AspectExpressionError {
    /// Error while adding a default aspect from the aspects file.
    #[error("Error adding default aspect: {0}")]
    AddingAspect(#[source] AspectAddingError),
    /// An invalid aspect default was found in the aspects file.
    #[error("Invalid aspect default: {0}")]
    InvalidAspectDefault(Box<str>),
}

/// Represents errors that can occur when parsing conditions.
#[derive(Copy, Clone, Debug, Error)]
pub enum ConditionParsingError {
    /// Indicates an invalid character was encountered.
    #[error("Invalid character '{0}' for condition names")]
    InvalidCharacter(char),

    /// Indicates an invalid condition format.
    #[error("Invalid condition format")]
    InvalidCondition,
}

impl From<ValueCheckingError> for ConditionParsingError {
    fn from(ValueCheckingError(c): ValueCheckingError) -> Self {
        Self::InvalidCharacter(c)
    }
}

/// Represents the kinds of errors that can occur when parsing a line.
#[derive(Debug, Error)]
pub enum ErrorKind {
    /// Indicates an error occurred while parsing the line.
    #[error("Input error while parsing line")]
    LineParsing,

    /// Indicates an error occurred while parsing an expression.
    #[error("Parsing expression failed: {0}")]
    ExpressionParsing(ParseError<ConditionParsingError>),

    /// Indicates conflicting conditions were encountered.
    #[error("Encountered conflicting conditions: {0}")]
    ConflictingCondition(InvalidChangeError),

    /// Indicates an invalid character was encountered while parsing the event name.
    #[error("Invalid character '{0}' in event name")]
    InvalidCharacterInEventName(char),

    /// Error while adding an aspect default from an expression.
    #[error("{0}")]
    AddingAspectExpression(#[source] AspectExpressionError),

    /// Indicates a subheader was encountered without a corresponding header.
    #[error("Subheader without matching header")]
    SubheaderWithoutHeader,
}

trait ErrorLine {
    type Output;

    fn line(self, line: usize) -> Self::Output;
}

impl ErrorLine for ErrorKind {
    type Output = Error;

    fn line(self, line: usize) -> Error {
        Error { line, kind: self }
    }
}

impl<T> ErrorLine for Result<T, ErrorKind> {
    type Output = Result<T, Error>;

    fn line(self, line: usize) -> Result<T, Error> {
        match self {
            Ok(value) => Ok(value),
            Err(err) => Err(err.line(line)),
        }
    }
}

/// Represents errors that can occur during parsing.
#[derive(Debug, Error)]
#[error("Line {line}: {kind}")]
pub struct Error {
    /// The line the error occured on.
    line: usize,
    /// The error kind.
    kind: ErrorKind,
}

type AspectMap = IndexMap<Aspect, (Str, Vec<Str>)>;

fn add_new_aspect(
    info: &mut MultilinearInfo,
    aspects: &mut AspectMap,
    aspect_name: &str,
    default_name: &str,
) -> Result<Aspect, AspectAddingError> {
    let aspect_name = valid_name(aspect_name)?;
    let default_name = valid_name(default_name)?;

    if aspects
        .entries
        .iter()
        .any(|(checked_name, _)| checked_name.as_ref() == aspect_name)
    {
        return Err(AspectAddingError::AlreadyExists);
    }

    let aspect = info.add_aspect();
    aspects.insert(aspect, (aspect_name.into(), vec![default_name.into()]));

    Ok(aspect)
}

fn add_aspect_expression(
    info: &mut MultilinearInfo,
    aspects: &mut AspectMap,
    line: &str,
) -> Result<(), AspectExpressionError> {
    let line = line.trim();
    if line.is_empty() {
        return Ok(());
    }
    let Some((aspect, default_value)) = line.split_once(':') else {
        return Err(AspectExpressionError::InvalidAspectDefault(line.into()));
    };
    if let Err(err) = add_new_aspect(info, aspects, aspect, default_value) {
        return Err(AspectExpressionError::AddingAspect(err));
    }

    Ok(())
}

/// A multilinear info containing the mapped aspect and event names.
#[derive(Default)]
pub struct NamedMultilinearInfo {
    /// The parsed `MultilinearInfo` instance.
    pub info: MultilinearInfo,
    /// A map associating events with their names.
    pub events: IndexMap<Event, Vec<Str>>,
    /// A map associating aspects with their names and the names of the aspect.
    pub aspects: AspectMap,
}

/// A parser for multilinear system definitions, supporting incremental parsing
/// across multiple files or input streams.
#[derive(Default)]
pub struct MultilinearParser(NamedMultilinearInfo);

impl MultilinearParser {
    /// Adds a new aspect and sets a default value.
    ///
    /// Fails if aspect already exists or if the names aren't valid.
    #[inline]
    pub fn add_new_aspect(
        &mut self,
        aspect_name: &str,
        default_name: &str,
    ) -> Result<Aspect, AspectAddingError> {
        let NamedMultilinearInfo { info, aspects, .. } = &mut self.0;

        add_new_aspect(info, aspects, aspect_name, default_name)
    }

    /// Adds a new aspect as a default value from an expression in the form of `aspect: name`.
    ///
    /// Fails if the format doesn't match, if aspect already exists or if the names aren't valid.
    #[inline]
    pub fn add_aspect_expression(&mut self, line: &str) -> Result<(), AspectExpressionError> {
        let NamedMultilinearInfo { info, aspects, .. } = &mut self.0;

        add_aspect_expression(info, aspects, line)
    }

    /// Parses additional multilinear data from the given reader.
    ///
    /// # Arguments
    ///
    /// - `reader` - The input source to parse from
    /// - `namespace` - Initial header context/path for events (e.g., `vec!["Main Story".into()]`)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::fs::File;
    /// use multilinear_parser::MultilinearParser;
    ///
    /// let mut parser = MultilinearParser::default();
    /// parser.parse(File::open("chapter1.mld").unwrap(), &[]).unwrap();
    /// parser.parse(File::open("chapter2.mld").unwrap(), &[]).unwrap();
    /// ```
    pub fn parse<R: Read>(&mut self, reader: R, parent_namespace: &[Str]) -> Result<(), Error> {
        let mut child_namespace = Vec::new();

        let NamedMultilinearInfo {
            info,
            events,
            aspects,
        } = &mut self.0;

        let mut condition_groups = Vec::new();
        let mut condition_lines = Vec::new();

        let mut last_header_line = 0;

        for (line_number, line) in BufReader::new(reader).lines().enumerate() {
            let line_number = line_number + 1;
            let Ok(line) = line else {
                return Err(ErrorKind::LineParsing.line(line_number));
            };

            if line.trim().is_empty() {
                if !condition_lines.is_empty() {
                    condition_groups.push(LogicalExpression::and(condition_lines));
                    condition_lines = Vec::new();
                }
                continue;
            }

            if let Some(success) = parse_header(&mut child_namespace, &line) {
                let Ok(changes) = success else {
                    return Err(ErrorKind::SubheaderWithoutHeader.line(line_number));
                };

                if let Err(ValueCheckingError(c)) = check_name(&changes.header) {
                    return Err(ErrorKind::InvalidCharacterInEventName(c)).line(line_number);
                }

                if !condition_lines.is_empty() {
                    condition_groups.push(LogicalExpression::and(condition_lines));
                    condition_lines = Vec::new();
                }

                if !condition_groups.is_empty() {
                    let mut event_edit = info.add_event();
                    for conditions in LogicalExpression::or(condition_groups).expand() {
                        if let Err(err) = event_edit.add_change(&conditions) {
                            return Err(ErrorKind::ConflictingCondition(err).line(last_header_line));
                        }
                    }

                    let mut namespace = parent_namespace.to_vec();
                    namespace.extend(changes.path.clone());
                    events.insert(event_edit.event(), namespace);

                    condition_groups = Vec::new();
                }

                last_header_line = line_number + 1;

                changes.apply();

                continue;
            }

            if parent_namespace.is_empty() && child_namespace.is_empty() {
                if let Err(err) = add_aspect_expression(info, aspects, &line) {
                    return Err(ErrorKind::AddingAspectExpression(err).line(line_number));
                }
                continue;
            }

            let line: &str = line.split_once('#').map_or(&line, |(line, _comment)| line);

            let parse_expression = |condition: &str| {
                let Some((aspect, changes)) = condition.split_once(':') else {
                    return Err(ConditionParsingError::InvalidCondition);
                };

                let (aspect, value_names) = aspect_info(aspects, aspect.trim(), info)?;
                Ok(LogicalExpression::or(
                    changes
                        .split(';')
                        .map(|change| -> Result<_, ValueCheckingError> {
                            Ok(LogicalExpression::Condition(
                                if let Some((from, to)) = change.split_once('>') {
                                    let from = value_index(value_names, from)?;
                                    let to = value_index(value_names, to)?;
                                    Change::transition(aspect, from, to)
                                } else {
                                    let change = value_index(value_names, change)?;
                                    Change::condition(aspect, change)
                                },
                            ))
                        })
                        .collect::<Result<_, _>>()?,
                ))
            };

            let conditions = LogicalExpression::parse_with_expression(line, parse_expression);

            let conditions = match conditions {
                Ok(conditions) => conditions,
                Err(err) => return Err(ErrorKind::ExpressionParsing(err).line(line_number)),
            };

            condition_lines.push(conditions);
        }

        if !condition_lines.is_empty() {
            condition_groups.push(LogicalExpression::and(condition_lines));
        }

        if !condition_groups.is_empty() {
            let mut event_edit = info.add_event();
            for conditions in LogicalExpression::or(condition_groups).expand() {
                if let Err(err) = event_edit.add_change(&conditions) {
                    return Err(ErrorKind::ConflictingCondition(err).line(last_header_line));
                }
            }

            let mut namespace = parent_namespace.to_vec();
            namespace.extend(child_namespace);
            events.insert(event_edit.event(), namespace);
        }

        Ok(())
    }

    /// Consumes the parser and returns the fully parsed data.
    ///
    /// After calling this, the parser can no longer be used.
    pub fn into_info(self) -> NamedMultilinearInfo {
        self.0
    }
}

/// Parses a complete multilinear system from a single reader.
///
/// This is a convenience wrapper for single-file parsing. For multi-file parsing,
/// use [`MultilinearParser`] directly.
///
/// # Example
///
/// ```no_run
/// use std::fs::File;
/// use multilinear_parser::parse_multilinear;
///
/// let story = parse_multilinear(File::open("story.mld").unwrap()).unwrap();
/// ```
pub fn parse_multilinear<R: Read>(reader: R) -> Result<NamedMultilinearInfo, Error> {
    let mut result = MultilinearParser::default();
    result.parse(reader, &[])?;
    Ok(result.0)
}

mod extended;

pub use extended::{
    AspectError, AspectErrorKind, DirectoryOrFileError, DirectoryOrFileErrorKind, ExtendedError,
    parse_multilinear_extended,
};