parade-rs 1.1.0

Rust rewrite of Parade - an experimental interactive-fiction playground / filesystem / operating system?
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
use capitalize::Capitalize;
use std::{collections::BTreeMap, iter};

use crate::{
    tree::{self, Node, Tree},
    vessel::{Article, Vessel, vessel_text},
};

use super::parse::{Action, Verb, VesselRequest};

/// Generates a [String] listing the children of a given [Vessel].
pub fn list_children(children: BTreeMap<String, Vessel>) -> String {
    children
        .iter()
        .fold("You see:".to_string(), |acc, (key, vessel)| {
            format!("{acc}\n\t> {}", vessel_text(key, &vessel.article))
        })
}
/// Generates a [String] containing a given [Vessel]'s note, followed by a newline, if such a note is present.
/// Otherwise, returns an empty [String].
pub fn note_text(vessel: &Vessel) -> String {
    if let Some(note) = &vessel.note {
        format!("{note}\n")
    } else {
        String::new()
    }
}
/// Generates a [String] informing a user of their [Vessel]'s location, the other contents of that location, and the contents of their [Vessel].
///
/// # Errors
///
/// This method fails if the specified [Vessel] is not present in the provided [Tree], if that [Vessel]'s parent is not present in the [Tree], or if any of the [Vessel]'s siblings or children cannot be located.
pub fn status_info(
    tree: &Tree<String, Vessel>,
    user_key: &String,
) -> Result<String, tree::Error<String>> {
    let user = tree.get(user_key)?;
    let parent = tree.get(&user.parent)?;
    let mut out = String::new();

    out += &format!(
        "You are {} in {}.\n",
        vessel_text(user_key, &user.value.article),
        vessel_text(&user.parent, &parent.value.article)
    );
    out += &note_text(&parent.value);

    for sibling in tree
        .get_all(tree.siblings(user_key, false)?)?
        .iter()
        .map(|(key, node)| vessel_text(key, &node.value.article))
    {
        out += &format!("You see {}.\n", sibling);
    }
    for child in tree
        .get_all(tree.children(user_key))?
        .iter()
        .map(|(key, node)| vessel_text(key, &node.value.article))
    {
        out += &format!("You are carrying {}.\n", child);
    }

    Ok(out)
}

/// The result of an [Action], after it has been run.
/// Instructs the client on what to tell the user.
pub enum ActionResult {
    /// The client should display the user's [Vessel]'s status, likely via [status_info].
    ShowStatus,
    /// The interface has begun programming a [Vessel], with the provided name and [Article].
    Programming(String, Option<Article>),
    /// The interface is programming a [Vessel], and has accepted the provided input.
    StillProgramming,
    /// The interface is programming a [Vessel], and has accepted an [Action::Exit], but is programming the [Vessel] to program another [Vessel], so we are not exiting the [Action::Program] state.
    StillProgrammingButExit,
    /// The interface has stopped programming a [Vessel].
    DoneProgramming,
    /// The interface has received an [Action::Exit] from the user, and the client should now exit.
    Exit,
    /// There was an issue with the user's input, and the client should inform them of it.
    /// Contains the error message to be displayed.
    UserError(String),
    /// The client has requested debug information, and the client should display it.
    /// Contains the debug informtion to be displayed.
    DebugText(String),
    /// The action has triggered a custom response message, which the client should display.
    /// Contains the message to be displayed.
    ResponseText(String),
    /// The action has triggered a "help" message, which the client should display.
    /// Contains the message to be displayed.
    HelpText(String),
    /// The interface has saved the current state, and the client should inform the user.
    Saved,
    /// The interface has loaded a previous state, and the client should inform the user.
    Loaded,
    /// There was an error saving the current state, and the client should inform the user.
    /// Contains the error to be displayed.
    SaveError(std::io::Error),
    /// There was an error loading a previous state, and the client should inform the user.
    /// Contains the error to be displayed.
    LoadError(std::io::Error),
}

/// Runs the provided program on the provided world-state, possibly modifying the provided user key.
/// - `user_key`: The key of the user's active [Vessel].
/// - `world`: The mutable world-state.
/// - `program`: The set of [Action]s to be run.
///
/// Returns an [ActionResult] informing the client of what to tell the user, if successful.
///
/// # Errors:
///
/// This method fails if any of the [Action]s fails.
pub fn run_program(
    mut user_key: String,
    world: &mut Tree<String, Vessel>,
    program: Vec<Action>,
) -> Result<ActionResult, Box<dyn std::error::Error>> {
    let mut local_editor_stack: Vec<String> = Vec::new();
    for action in program {
        if matches!(action, Action::Save { filename: _ })
            || matches!(action, Action::Load { filename: _ })
        {
            return Ok(ActionResult::UserError(
                "Programs are not allowed to use the debug, save, or load actions.".to_string(),
            ));
        }
        match run_action(
            &mut user_key,
            world,
            Some(action.clone()),
            &mut local_editor_stack,
        ) {
            Ok(ActionResult::StillProgrammingButExit)
            | Ok(ActionResult::DoneProgramming)
            | Ok(ActionResult::ResponseText(_))
            | Ok(ActionResult::HelpText(_))
            | Ok(ActionResult::StillProgramming)
            | Ok(ActionResult::ShowStatus)
            | Ok(ActionResult::Programming(_, _)) => {}
            Ok(ActionResult::Exit) => {
                if local_editor_stack.pop().is_none() {
                    return Ok(ActionResult::Exit);
                }
            }
            Ok(ActionResult::UserError(e)) => {
                return Ok(ActionResult::UserError(e));
            }
            Ok(ActionResult::DebugText(_))
            | Ok(ActionResult::Saved)
            | Ok(ActionResult::Loaded)
            | Ok(ActionResult::SaveError(_))
            | Ok(ActionResult::LoadError(_)) => {
                return Ok(ActionResult::UserError(
                    "Programs are not allowed to use the debug, save, or load actions.".to_string(),
                ));
            }
            Err(e) => return Err(e),
        }
    }

    Ok(ActionResult::ShowStatus)
}

/// Runs the provided action on the provided world-state, possibly modifying the provided user key and/or editing stack.
/// - `user_key`: The key of the user's active [Vessel].
/// - `world`: The mutable world-state.
/// - `action`: The action to be run, if any.
///
/// Returns an [ActionResult] informing the client of what to tell the user, if successful.
///
/// # Errors:
///
/// This method fails if:
/// - The [Vessel] at the provided `user_key` or its parent [Node] cannot be found
/// - Another [Node] which should exist cannot be found (such as a sibling or child of the user's [Vessel], or a child thereof)
/// - There is an issue serializing and saving or loading and deserializing the world-state.
pub fn run_action(
    user_key: &mut String,
    world: &mut Tree<String, Vessel>,
    action: Option<Action>,
    editor_stack: &mut Vec<String>,
) -> Result<ActionResult, Box<dyn std::error::Error>> {
    let parent_key = world.get_parent(user_key)?.clone();

    match editor_stack.first().map(|editing| world.get_mut(editing)) {
        Some(Ok(editing_node)) => match action {
            Some(Action::Exit) => {
                editor_stack.pop();
                if editor_stack.is_empty() {
                    Ok(ActionResult::DoneProgramming)
                } else {
                    editing_node.value.program = match &editing_node.value.program {
                        Some(program) => Some(
                            program
                                .clone()
                                .into_iter()
                                .chain(iter::once(Action::Exit))
                                .collect(),
                        ),
                        None => Some(vec![Action::Exit]),
                    };

                    Ok(ActionResult::StillProgrammingButExit)
                }
            }
            Some(Action::Program(vessel_request)) => {
                let action_copy = Action::Program(vessel_request.clone());
                let name = vessel_request
                    .map(|vr| vr.name)
                    .unwrap_or(parent_key.clone());
                editor_stack.push(name);
                editing_node.value.program = match &editing_node.value.program {
                    Some(program) => Some(
                        program
                            .clone()
                            .into_iter()
                            .chain(iter::once(action_copy))
                            .collect(),
                    ),
                    None => Some(vec![action_copy]),
                };

                Ok(ActionResult::StillProgramming)
            }
            Some(action) => {
                editing_node.value.program = match &editing_node.value.program {
                    Some(program) => Some(
                        program
                            .clone()
                            .into_iter()
                            .chain(iter::once(action))
                            .collect(),
                    ),
                    None => Some(vec![action]),
                };

                Ok(ActionResult::StillProgramming)
            }
            None => Ok(ActionResult::StillProgramming),
        },
        Some(Err(e)) => Err(Box::new(e)),
        None => match action {
            Some(action) => match action {
                Action::Create(VesselRequest { article, name }) => {
                    if let Err(e) = world.add(
                        name.clone(),
                        Node::new(Vessel::with_article(article), parent_key),
                    ) {
                        match e {
                            tree::Error::NonUniqueKey(key) => {
                                Ok(ActionResult::UserError(format!("{key} already exists")))
                            }
                            _ => Err(Box::new(e)),
                        }
                    } else {
                        Ok(ActionResult::ShowStatus)
                    }
                }
                Action::Become(VesselRequest { article, name }) => {
                    if world
                        .get_parent(&name)
                        .is_ok_and(|parent| parent == &parent_key)
                    {
                        *user_key = name;

                        Ok(ActionResult::ShowStatus)
                    } else {
                        Ok(ActionResult::UserError(format!(
                            "You don't see {}.",
                            vessel_text(&name, &article)
                        )))
                    }
                }
                Action::Enter(VesselRequest { article, name }) => {
                    if let Err(e) = world.set_parent(user_key, name.clone()) {
                        match e {
                            tree::Error::NonexistentNode(_) => Ok(ActionResult::UserError(
                                format!("You don't see {}.", vessel_text(&name, &article)),
                            )),
                            _ => Err(Box::new(e)),
                        }
                    } else {
                        Ok(ActionResult::ShowStatus)
                    }
                }
                Action::Leave => {
                    world.set_parent(user_key, world.get_parent(&parent_key)?.clone())?;

                    Ok(ActionResult::ShowStatus)
                }
                Action::Take(VesselRequest { article, name }) => {
                    if world
                        .get_parent(&name)
                        .is_ok_and(|selected_parent| selected_parent == &parent_key)
                    {
                        world.set_parent(&name, user_key.clone())?;

                        Ok(ActionResult::ShowStatus)
                    } else {
                        Ok(ActionResult::UserError(format!(
                            "You don't see {}.",
                            vessel_text(&name, &article)
                        )))
                    }
                }
                Action::Drop(VesselRequest { article, name }) => {
                    if world
                        .get_parent(&name)
                        .is_ok_and(|selected_parent| selected_parent == user_key)
                    {
                        world.set_parent(&name, parent_key.clone())?;

                        Ok(ActionResult::ShowStatus)
                    } else {
                        Ok(ActionResult::UserError(format!(
                            "You aren't carrying {}.",
                            vessel_text(&name, &article)
                        )))
                    }
                }
                Action::Move {
                    object_article,
                    object_name,
                    preposition: _,
                    target_article,
                    target_name,
                } => {
                    if world
                        .get_parent(&object_name)
                        .is_ok_and(|object_parent| object_parent == &parent_key)
                    {
                        if world
                            .get_parent(&target_name)
                            .is_ok_and(|target_parent| target_parent == &parent_key)
                        {
                            world.set_parent(&object_name, target_name)?;
                            Ok(ActionResult::ShowStatus)
                        } else {
                            Ok(ActionResult::UserError(format!(
                                "You don't see {}",
                                vessel_text(&target_name, &target_article)
                            )))
                        }
                    } else {
                        Ok(ActionResult::UserError(format!(
                            "You don't see {}",
                            vessel_text(&object_name, &object_article)
                        )))
                    }
                }
                Action::Look {
                    preposition: _,
                    basic,
                } => match basic {
                    Some(VesselRequest { article, name }) => {
                        match world
                            .get_from_parent(&name, &parent_key)
                            .ok()
                            .flatten()
                            .or_else(|| world.get_from_parent(&name, user_key).ok().flatten())
                        {
                            Some(node) => Ok(ActionResult::ResponseText(format!(
                                "You look at {}.\n{}{}",
                                vessel_text(&name, &article),
                                note_text(&node.value),
                                list_children(world.get_all_values(world.children(&name))?)
                            ))),
                            None => Ok(ActionResult::UserError(format!(
                                "You don't see {}.",
                                vessel_text(&name, &article)
                            ))),
                        }
                    }
                    None => Ok(ActionResult::ResponseText(format!(
                        "{}{}",
                        note_text(&world.get(&parent_key)?.value),
                        list_children(world.get_all_values(world.siblings(user_key, false)?)?)
                    ))),
                },
                Action::Transform {
                    preposition: _,
                    basic: VesselRequest { article: _, name },
                } => {
                    if let Err(e) = world.rename(user_key, name.clone()) {
                        match e {
                            tree::Error::NonUniqueKey(key) => {
                                Ok(ActionResult::UserError(format!("{key} already exists.")))
                            }
                            e => Err(Box::new(e)),
                        }
                    } else {
                        *user_key = name;
                        Ok(ActionResult::ShowStatus)
                    }
                }
                Action::Note { text: note } => {
                    world.get_mut(&parent_key)?.value.note = note;

                    Ok(ActionResult::ShowStatus)
                }
                Action::Warp {
                    preposition: _,
                    basic: VesselRequest { article, name },
                } => {
                    if let Err(e) = world.set_parent(user_key, name) {
                        match e {
                            tree::Error::NonexistentNode(node) => Ok(ActionResult::UserError(
                                format!("You can't find {}.", vessel_text(&node, &article)),
                            )),
                            e => Err(Box::new(e)),
                        }
                    } else {
                        Ok(ActionResult::ShowStatus)
                    }
                }
                Action::Program(vessel_request) => match vessel_request {
                    Some(VesselRequest { article, name }) => {
                        if world
                            .get_parent(&name)
                            .is_ok_and(|parent| parent == &parent_key)
                        {
                            editor_stack.push(name.clone());
                            Ok(ActionResult::Programming(name, article))
                        } else {
                            Ok(ActionResult::UserError(format!(
                                "You can't find {}.",
                                vessel_text(&name, &article)
                            )))
                        }
                    }
                    None => {
                        editor_stack.push(parent_key.clone());
                        let article = world.get(&parent_key)?.value.article;
                        Ok(ActionResult::Programming(parent_key, article))
                    }
                },
                Action::Use(VesselRequest { article, name }) => {
                    if let Some(program) = world
                        .get_from_parent(&name, &parent_key)
                        .ok()
                        .flatten()
                        .map(|node| node.value.program.clone())
                    {
                        match program {
                            Some(program) => run_program(name, world, program),
                            None => Ok(ActionResult::UserError(format!(
                                "{} has no program.",
                                vessel_text(&name, &article).capitalize_first_only()
                            ))),
                        }
                    } else {
                        Ok(ActionResult::UserError(format!(
                            "You can't find {}.",
                            vessel_text(&name, &article)
                        )))
                    }
                }
                Action::Cast {
                    spell,
                    preposition: _,
                    target,
                } => {
                    if let Some(program) = world
                        .get(&spell.name)
                        .ok()
                        .map(|node| node.value.program.clone())
                    {
                        match program {
                            Some(program) => {
                                if let Ok(Some(_)) =
                                    world.get_from_parent(&target.name, &parent_key)
                                {
                                    run_program(target.name, world, program)
                                } else {
                                    Ok(ActionResult::UserError(format!(
                                        "You can't find {}.",
                                        vessel_text(&target.name, &target.article)
                                    )))
                                }
                            }
                            None => Ok(ActionResult::UserError(format!(
                                "{} has no program.",
                                vessel_text(&spell.name, &spell.article).capitalize_first_only()
                            ))),
                        }
                    } else {
                        Ok(ActionResult::UserError(format!(
                            "You can't find {}.",
                            vessel_text(&spell.name, &spell.article)
                        )))
                    }
                }
                Action::Save { filename } => {
                    let filename = filename.unwrap_or("parade_save".to_string()) + ".json";
                    let save_data = serde_json::to_string(&world)?;
                    match std::fs::write(filename, save_data) {
                        Ok(_) => Ok(ActionResult::Saved),
                        Err(e) => Ok(ActionResult::SaveError(e)),
                    }
                }
                Action::Load { filename } => {
                    let filename = filename.unwrap_or("parade_save".to_string()) + ".json";
                    let save_data_text = match std::fs::read_to_string(filename) {
                        Ok(data) => data,
                        Err(e) => return Ok(ActionResult::LoadError(e)),
                    };
                    let save_data: Tree<String, Vessel> = serde_json::from_str(&save_data_text)?;
                    *world = save_data;
                    Ok(ActionResult::Loaded)
                }
                Action::Exit => Ok(ActionResult::Exit),
                Action::Debug => Ok(ActionResult::DebugText(format!("{:?}", world))),
                Action::Help { topic: Some(topic) } => {
                    Ok(ActionResult::HelpText(topic.help_text()))
                }
                Action::Help { topic: None } => Ok(ActionResult::HelpText(Verb::help_list_text())),
            },
            None => Ok(ActionResult::ShowStatus),
        },
    }
}