socratic 0.0.1

A dialog system for games in rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! socratic is for dialog systems

#![deny(unused, missing_docs, private_in_public)]

use std::{collections::HashMap, path::Path, str::FromStr};

#[cfg(feature = "cbor")]
use std::io;

pub use error::ParseError;
use error::SocraticError;
pub use lexing::Atom;
use lexing::AtomOr;
use serde::{Deserialize, Serialize};
use tracing::{info, info_span, instrument};

mod error;
mod lexing;
mod parsing;

/// A group of atoms representing a section of text.
#[derive(Debug, Default, Hash, PartialEq, Eq, Serialize, Deserialize, Clone)]
pub struct Atoms<T = String>(pub Vec<Atom<T>>);

impl Atoms<String> {
    fn new<I, S>(input: &Vec<AtomOr<String, I>>, state: &mut S) -> Self
    where
        S: DialogState<Interpolation = I>,
    {
        let mut atoms = Vec::new();
        for atom in input {
            match atom {
                AtomOr::Atom(a) => atoms.push(a.clone()),
                AtomOr::Interpolate(i) => atoms.push(Atom::Text(state.interpolate(i))),
            }
        }
        Self(atoms)
    }
}

impl<T: std::fmt::Display> std::fmt::Display for Atoms<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.iter().try_for_each(|a| write!(f, "{a}"))
    }
}

impl<T> Atoms<T> {
    /// Returns an iterator over atoms.
    pub fn iter(&self) -> std::slice::Iter<Atom<T>> {
        self.0.iter()
    }

    /// Returns an iterator that allows modifying each value.
    pub fn iter_mut(&mut self) -> std::slice::IterMut<Atom<T>> {
        self.0.iter_mut()
    }
}

impl<T> IntoIterator for Atoms<T> {
    type Item = Atom<T>;
    type IntoIter = std::vec::IntoIter<Atom<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a Atoms<T> {
    type Item = &'a Atom<T>;
    type IntoIter = std::slice::Iter<'a, Atom<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Atoms<T> {
    type Item = &'a mut Atom<T>;
    type IntoIter = std::slice::IterMut<'a, Atom<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// Dialog stores all the dialog trees, grouped by section name.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "d")]
pub struct Dialog<DA, IF, TE> {
    #[serde(rename = "s")]
    sections: HashMap<String, DialogTree<DA, IF, TE>>,
}

impl<DA, IF, TE> Default for Dialog<DA, IF, TE> {
    fn default() -> Self {
        Self {
            sections: Default::default(),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "dt")]
struct DialogTree<DA, IF, TE> {
    #[serde(rename = "n")]
    nodes: Vec<DialogNode<DA, IF, TE>>,
}

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename = "dn")]
enum DialogNode<DA, IF, TE> {
    #[serde(rename = "cs")]
    CharacterSays(String, Vec<AtomOr<String, TE>>),
    #[serde(rename = "m")]
    Message(Vec<AtomOr<String, TE>>),
    #[serde(rename = "gt")]
    GoTo(String),
    #[serde(rename = "r")]
    #[allow(clippy::type_complexity)]
    Responses(Vec<(Vec<AtomOr<String, TE>>, Option<IF>, DialogTree<DA, IF, TE>)>),

    #[serde(rename = "da")]
    DoAction(DA),
    #[serde(rename = "c")]
    Conditional(Vec<(Option<IF>, DialogTree<DA, IF, TE>)>),
}

/// DialogItem is a single logical dialog node to be displayed to the user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DialogItem {
    /// A character says something.
    CharacterSays(String, Atoms),
    /// A simple message.
    Message(Atoms),
    /// Go to another section.
    GoTo(String),
    /// List of possible responses.
    Responses(Vec<Atoms>),
}

impl std::fmt::Display for DialogItem {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use DialogItem::*;
        match self {
            CharacterSays(ch, atoms) => write!(f, "{ch}: {atoms}"),
            Message(atoms) => write!(f, "{atoms}"),
            GoTo(gt) => write!(f, "=> {gt}"),
            Responses(resp) => write!(f, "Responses: [{resp:?}]"),
        }
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct SubIndex {
    index: usize,
    response: Option<usize>,
    inner: Box<Option<SubIndex>>,
}

/// DialogIndex is used to track where in a DialogTree a player is.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct DialogIndex {
    section: String,
    sub: Option<SubIndex>,
}

impl std::fmt::Display for DialogIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.section)?;
        if let Some(ref sub) = self.sub {
            write!(f, ".{sub}")?;
        }
        Ok(())
    }
}

impl std::fmt::Display for SubIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.index)?;
        if let Some(response) = self.response {
            write!(f, "[{response}]")?;
        }
        if let Some(sub) = self.inner.as_ref() {
            write!(f, ".{sub}")?;
        }
        Ok(())
    }
}

impl SubIndex {
    fn set_response(&mut self, r: usize) {
        match self.inner.as_mut() {
            Some(ref mut i) => i.set_response(r),
            None => self.response = Some(r),
        }
    }
}

impl DialogIndex {
    /// When the dialog is on a 'Response' node, this sets the index of the response selected.
    pub fn set_response(&mut self, r: usize) {
        self.sub
            .as_mut()
            .expect("sub index to not be None")
            .set_response(r);
    }
}

/// When merging two `Dialog` objects together, duplicate sections will trigger this error.
#[derive(Debug, Default, Clone, PartialEq, Eq, thiserror::Error)]
#[error("found duplicate section key: {0}")]
pub struct DuplicateSectionKey(String);

/// Error encountered while validating
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ValidationError {
    /// All section gotos should refer to an extant section.
    #[error("found redirect (=>) that refers to a non existent section `{0}`")]
    UnknownSectionGoTo(String),
}

/// A list of validation errors
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub struct ValidationErrors(Vec<ValidationError>);

impl std::fmt::Display for ValidationErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "encountered {} validation error{}:",
            self.0.len(),
            if self.0.len() == 1 { "" } else { "s" }
        )?;
        for err in &self.0 {
            write!(f, "\n\t{err}")?;
        }
        Ok(())
    }
}

impl<DA, IF, TE> Dialog<DA, IF, TE> {
    /// Build a new empty dialog object.
    pub fn new() -> Self {
        Self::default()
    }

    /// Validate the Dialog
    pub fn validate(&self) -> Result<(), ValidationErrors> {
        let sections = self.sections.keys().collect::<Vec<_>>();
        let mut errors = Vec::new();
        self.walk(|node| {
            if let DialogNode::GoTo(gt) = node {
                if !sections.contains(&gt) {
                    errors.push(ValidationError::UnknownSectionGoTo(gt.into()));
                }
            }
        });
        if errors.is_empty() {
            Ok(())
        } else {
            Err(ValidationErrors(errors))
        }
    }

    /// Merge `other` into this dialog object.
    pub fn merge(&mut self, other: Self) -> Result<(), DuplicateSectionKey> {
        for (section, data) in other.sections {
            if self.sections.contains_key(&section) {
                return Err(DuplicateSectionKey(section));
            }
            self.sections.insert(section, data);
        }
        Ok(())
    }

    /// parse a dialog tree from a provided string.
    #[allow(clippy::type_complexity)]
    pub fn parse_str(s: &str) -> Result<Self, SocraticError<DA::Err, IF::Err, TE::Err>>
    where
        DA: FromStr,
        IF: FromStr,
        TE: FromStr,
    {
        Ok(parsing::dialog::<DA, IF, TE>(s)?)
    }

    /// Parse a dialog tree from a reader.
    #[allow(clippy::type_complexity)]
    pub fn parse_from_reader<R>(
        mut reader: R,
    ) -> Result<Self, SocraticError<DA::Err, IF::Err, TE::Err>>
    where
        R: std::io::Read,
        DA: FromStr,
        IF: FromStr,
        TE: FromStr,
    {
        let mut s = String::new();
        reader.read_to_string(&mut s)?;
        Dialog::parse_str(&s)
    }

    /// Parse a dialog tree from a file.
    #[allow(clippy::type_complexity)]
    pub fn parse_from_file<P>(path: P) -> Result<Self, SocraticError<DA::Err, IF::Err, TE::Err>>
    where
        P: AsRef<Path>,
        DA: FromStr,
        IF: FromStr,
        TE: FromStr,
    {
        let f = std::fs::File::open(path)?;
        Dialog::parse_from_reader(f)
    }

    /// Write the Dialog to a writer using the CBOR format.
    #[cfg(feature = "cbor")]
    pub fn packed_to_writer<W>(&self, writer: W) -> Result<(), ciborium::ser::Error<W::Error>>
    where
        W: ciborium_io::Write,
        W::Error: core::fmt::Debug,
        DA: Serialize,
        IF: Serialize,
        TE: Serialize,
    {
        ciborium::ser::into_writer(&self.sections, writer)
    }

    /// Write the Dialog to a file using the CBOR format.
    #[cfg(feature = "cbor")]
    pub fn packed_to_file<P: AsRef<Path>>(
        &self,
        path: P,
    ) -> Result<(), ciborium::ser::Error<io::Error>>
    where
        DA: Serialize,
        IF: Serialize,
        TE: Serialize,
    {
        let f = std::fs::File::create(path)?;
        self.packed_to_writer(f)
    }

    /// Read the Dialog from a Reader using the CBOR format.
    #[cfg(feature = "cbor")]
    pub fn packed_from_reader<R>(reader: R) -> Result<Self, ciborium::de::Error<R::Error>>
    where
        R: ciborium_io::Read,
        R::Error: core::fmt::Debug,
        DA: serde::de::DeserializeOwned,
        IF: serde::de::DeserializeOwned,
        TE: serde::de::DeserializeOwned,
    {
        let sections: HashMap<String, DialogTree<DA, IF, TE>> = ciborium::de::from_reader(reader)?;
        Ok(Dialog { sections })
    }

    /// Read the Dialog from a Reader using the CBOR format.
    #[cfg(feature = "cbor")]
    pub fn packed_from_file<P: AsRef<Path>>(path: P) -> Result<Self, ciborium::de::Error<io::Error>>
    where
        DA: serde::de::DeserializeOwned,
        IF: serde::de::DeserializeOwned,
        TE: serde::de::DeserializeOwned,
    {
        let f = std::fs::File::open(path)?;
        Self::packed_from_reader(f)
    }
}

/// Trait for state objects that interact with dialog.
pub trait DialogState {
    /// DoAction type
    type DoAction;

    /// IF Type
    type IF;

    /// Interpolation type
    type Interpolation;

    /// Perform an action on the state.
    fn do_action(&mut self, command: &Self::DoAction);

    /// Check a conditional against the current state.
    fn check_condition(&self, command: &Self::IF) -> bool;

    /// Get a string to interpolate.
    fn interpolate(&self, command: &Self::Interpolation) -> String;
}

impl DialogState for () {
    type DoAction = String;
    type IF = String;
    type Interpolation = String;

    fn do_action(&mut self, _command: &String) {}
    fn check_condition(&self, _command: &String) -> bool {
        true
    }
    fn interpolate(&self, command: &String) -> String {
        command.into()
    }
}

impl<DA, IF, TE> Dialog<DA, IF, TE> {
    /// Get the dialog line represented by the |DialogIndex|.
    ///
    /// Returns the `DialogItem` for the associated `index` along with the next index.
    #[instrument(skip(self, state), fields(index = %index))]
    pub fn get<S: DialogState<DoAction = DA, IF = IF, Interpolation = TE>>(
        &self,
        mut index: DialogIndex,
        state: &mut S,
    ) -> Option<(DialogItem, DialogIndex)>
    where
        DA: std::fmt::Debug,
    {
        let tree = self.sections.get(&index.section)?;
        let (item, sub_index) = tree.get(index.sub, state)?;
        index.sub = Some(sub_index);
        Some((item, index))
    }

    /// Begins a new dialog session at a given section.
    #[instrument(skip(self, state))]
    pub fn begin<S: DialogState<DoAction = DA, IF = IF, Interpolation = TE>>(
        &self,
        section: &str,
        state: &mut S,
    ) -> Option<(DialogItem, DialogIndex)>
    where
        DA: std::fmt::Debug,
    {
        self.get(
            DialogIndex {
                section: section.into(),
                sub: None,
            },
            state,
        )
    }

    fn walk<F>(&self, mut cb: F)
    where
        F: FnMut(&DialogNode<DA, IF, TE>),
    {
        for tree in self.sections.values() {
            tree.walk(&mut cb);
        }
    }
}

impl<DA, IF, TE> DialogTree<DA, IF, TE> {
    fn walk<F>(&self, cb: &mut F)
    where
        F: FnMut(&DialogNode<DA, IF, TE>),
    {
        for node in &self.nodes {
            cb(node);
            match node {
                DialogNode::Conditional(parts) => {
                    for (_, tree) in parts {
                        tree.walk(cb);
                    }
                }
                DialogNode::Responses(responses) => {
                    for (_, _, tree) in responses {
                        tree.walk(cb);
                    }
                }
                _ => {}
            }
        }
    }

    fn get<S: DialogState<DoAction = DA, IF = IF, Interpolation = TE>>(
        &self,
        index: Option<SubIndex>,
        state: &mut S,
    ) -> Option<(DialogItem, SubIndex)>
    where
        DA: std::fmt::Debug,
    {
        let span = match &index {
            Some(ref i) => info_span!("get", index = %i),
            None => info_span!("get", index = %"None"),
        };
        let _enter = span.enter();

        let mut index = index.unwrap_or_default();
        match self.nodes.get(index.index)? {
            DialogNode::CharacterSays(character, says) => {
                let says = Atoms::new(says, state);
                info!("CharacterSays({character}, {says})");
                index.index += 1;
                Some((DialogItem::CharacterSays(character.clone(), says), index))
            }
            DialogNode::Message(msg) => {
                let msg = Atoms::new(msg, state);
                info!("Message({msg})");
                index.index += 1;
                Some((DialogItem::Message(msg), index))
            }
            DialogNode::GoTo(gt) => {
                info!("GoTo({gt})");
                index.index += 1;
                Some((DialogItem::GoTo(gt.clone()), index))
            }
            DialogNode::Responses(responses) => {
                let responses = responses
                    .iter()
                    .filter(|(_, i, _)| {
                        i.as_ref().map(|i| state.check_condition(i)).unwrap_or(true)
                    })
                    .collect::<Vec<_>>();
                info!("Ask...");
                if let Some(resp) = index.response {
                    let response_tree = &responses.get(resp)?.2;
                    match response_tree.get(*index.inner, state) {
                        None => {
                            index.index += 1;
                            index.response = None;
                            index.inner = Box::new(None);
                            self.get(Some(index), state)
                        }
                        Some((item, inner)) => {
                            *index.inner = Some(inner);
                            Some((item, index))
                        }
                    }
                } else {
                    Some((
                        DialogItem::Responses(
                            responses
                                .iter()
                                .map(|(q, _, _)| Atoms::new(q, state))
                                .collect(),
                        ),
                        index,
                    ))
                }
            }
            DialogNode::DoAction(cmd) => {
                info!("DoAction({cmd:?})");
                index.index += 1;
                state.do_action(cmd);
                self.get(Some(index), state)
            }
            DialogNode::Conditional(conditions) => {
                if index.response.is_none() {
                    for (i, (check, _)) in conditions.iter().enumerate() {
                        if let Some(c) = check {
                            if state.check_condition(c) {
                                index.response = Some(i);
                            }
                        } else {
                            index.response = Some(i)
                        }
                    }
                    // No checks passed.
                    if index.response.is_none() {
                        index.index += 1;
                        return self.get(Some(index), state);
                    }
                }
                let resp = index.response.expect("to be not none");
                let response_tree = &conditions.get(resp)?.1;
                match response_tree.get(*index.inner, state) {
                    None => {
                        index.index += 1;
                        index.response = None;
                        index.inner = Box::new(None);
                        self.get(Some(index), state)
                    }
                    Some((item, inner)) => {
                        *index.inner = Some(inner);
                        Some((item, index))
                    }
                }
            }
        }
    }
}

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

    #[cfg(feature = "cbor")]
    #[test]
    fn test_socrates() -> Result<(), anyhow::Error> {
        let s = Dialog::parse_str(
            r#"

:: section_name
doot
- hi
    test
- hello
    test2
- trust issues => section_name
boot
=> dingle

:: dingle
bingle"#,
        )?;
        let (line, ix) = s.begin("section_name", &mut ()).unwrap();
        info!("1 {line} {ix:?}");
        let (line, mut ix) = s.get(ix, &mut ()).unwrap();
        info!("2 {line} {ix:?}");
        ix.set_response(2);
        info!("3 {ix:?}");
        let (line, ix) = s.get(ix, &mut ()).unwrap();
        info!("4 {line} {ix:?}");
        let (line, ix) = s.get(ix, &mut ()).unwrap();
        info!("5 {line} {ix:?}");
        s.packed_to_file("test.txt").unwrap();

        let s2 = Dialog::packed_from_file("test.txt").unwrap();
        println!("{:?}", s2);
        assert_eq!(s, s2);

        Ok(())
    }
}