inkling 0.12.5

Limited implementation of the Ink markup language.
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! Trait and functions to validate a story.

use crate::{
    error::{parse::validate::ValidationError, utils::MetaData},
    follow::FollowData,
    knot::{get_empty_knot_counts, Address, AddressKind, KnotSet},
    story::{types::VariableSet, validate::namespace::validate_story_name_spaces},
};

use std::collections::HashMap;

pub struct ValidationData {
    /// Data required to evaluate expressions.
    ///
    /// Should be a clone of the original data object, containing all the global variables
    /// and empty knot counts directly after parsing the story structure. The trait may evaluate
    /// variable assignments by trying them out in all parts of the story.
    pub follow_data: FollowData,
    /// Structure corresponding to knots with their default stitch, stitches and meta data.
    pub knots: HashMap<String, KnotValidationInfo>,
}

/// Basic information about a knot, required to validate its content.
pub struct KnotValidationInfo {
    /// Default stitch of knot.
    pub default_stitch: String,
    /// Collection of validation data for stitches.
    ///
    /// The keys are the stitch names.
    pub stitches: HashMap<String, StitchValidationInfo>,
    /// Information about the origin of this knot.
    pub meta_data: MetaData,
}

/// Basic information about a stitch, required to validate its content.
pub struct StitchValidationInfo {
    /// Information about the origin of this stitch.
    pub meta_data: MetaData,
}

impl ValidationData {
    /// Construct the required validation data from the parsed knots and variables.
    pub fn from_data(knots: &KnotSet, variables: &VariableSet) -> Self {
        let knot_info = knots
            .iter()
            .map(|(knot_name, knot)| {
                let stitches = knot
                    .stitches
                    .iter()
                    .map(|(stitch_name, stitch_data)| {
                        (
                            stitch_name.to_string(),
                            StitchValidationInfo {
                                meta_data: stitch_data.meta_data.clone(),
                            },
                        )
                    })
                    .collect();

                let info = KnotValidationInfo {
                    default_stitch: knot.default_stitch.clone(),
                    stitches,
                    meta_data: knot.meta_data.clone(),
                };

                (knot_name.clone(), info)
            })
            .collect();

        let follow_data = FollowData {
            knot_visit_counts: get_empty_knot_counts(knots),
            variables: variables.clone(),
        };

        ValidationData {
            follow_data,
            knots: knot_info,
        }
    }
}

/// Trait for nesting into all parts of a story and validating elements.
///
/// Elements which will be validated:
///
/// *   Addresses, which should point to locations (possibly with internal shorthand in knots)
///     or global variables
/// *   Expressions, which should contain matching variable types
/// *   Conditions, which should also contain matching variable types on each side of a comparison
/// *   (If implemented) Variable assignments from other variables or expressions
///
/// Should be implemented for all types that touch the content of a constructed story.
/// This will be most if not all line elements: the criteria is if they contain parts which
/// need to be validated or nest other parts of a line that may. For example, lines contain
/// expressions which need to validated, as well as conditions which contain variables and
/// expressions which also need to be validated, and so on.
///
/// All encountered errors will be recorded in the error container but not break the nested
/// search since we want to collect all possible errors at once. To assert whether an error
/// was found we simply check whether this container is empty or not. For this use case this
/// is easier than returning a `Result`.
///
/// The `MetaData` struct is forwarded from the deepest currently active object with such an
/// item, to trace from which line an encountered error stems from. Similarly the `Address`
/// object contains the current location in the story, to be used when checking for internal
/// addressing within knot or stitch name spaces.
///
/// # Notes
/// *   Addresses are validated first, since variables need verified addresses to access
///     underlying content in expressions.
pub trait ValidateContent {
    fn validate(
        &mut self,
        errors: &mut ValidationError,
        current_location: &Address,
        current_meta_data: &MetaData,
        follow_data: &ValidationData,
    );
}

/// Validate addresses, expressions, conditions and names of all content in a story.
///
/// This function walks through all the knots and stitches in a story, and for each item
/// uses the `ValidateContent` trait to nest through its content. Additionally it checks for
/// name space collisions between variables, knots and stitches.
///
/// If any error is encountered this will yield the set of all found errors.
pub fn validate_story_content(
    knots: &mut KnotSet,
    follow_data: &FollowData,
) -> Result<(), ValidationError> {
    let validation_data = ValidationData::from_data(knots, &follow_data.variables);

    let mut error = ValidationError::new();

    knots.iter_mut().for_each(|(knot_name, knot)| {
        knot.stitches.iter_mut().for_each(|(stitch_name, stitch)| {
            let current_location = Address::Validated(AddressKind::Location {
                knot: knot_name.clone(),
                stitch: stitch_name.clone(),
            });

            stitch.root.validate(
                &mut error,
                &current_location,
                &stitch.meta_data,
                &validation_data,
            );
        })
    });

    if let Err(name_space_errors) = validate_story_name_spaces(&validation_data) {
        error.name_space_errors = name_space_errors;
    }

    if error.is_empty() {
        Ok(())
    } else {
        Err(error)
    }
}

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

    use crate::{
        consts::ROOT_KNOT_NAME,
        knot::{Knot, Stitch},
        line::Variable,
        node::RootNodeBuilder,
        story::{
            parse::read_story_content_from_string,
            types::{VariableInfo, VariableSet},
        },
    };

    pub fn construct_knots(data: &[(&str, &[&str])]) -> KnotSet {
        let mut line_index = 0;

        data.into_iter()
            .map(|(knot_name, knot_data)| {
                let default_stitch = knot_data[0].to_string();

                let knot_line_index = line_index;
                line_index += 1;

                let stitches = knot_data
                    .into_iter()
                    .map(|stitch_name| {
                        let root = RootNodeBuilder::from_address(knot_name, stitch_name).build();

                        let stitch = Stitch {
                            root,
                            stack: Vec::new(),
                            meta_data: line_index.into(),
                        };

                        line_index += 1;

                        (stitch_name.to_string(), stitch)
                    })
                    .collect();

                let knot = Knot {
                    default_stitch,
                    stitches,
                    tags: Vec::new(),
                    meta_data: knot_line_index.into(),
                };

                (knot_name.to_string(), knot)
            })
            .collect()
    }

    pub fn construct_variables<T>(data: &[(&str, T)]) -> VariableSet
    where
        T: Into<Variable> + Clone,
    {
        data.into_iter()
            .cloned()
            .enumerate()
            .map(|(i, (name, variable))| (name.to_string(), VariableInfo::new(variable.into(), i)))
            .collect()
    }

    fn get_validation_data_from_string(content: &str) -> (KnotSet, FollowData) {
        let (knots, variables, _) = read_story_content_from_string(content).unwrap();

        let data = FollowData {
            knot_visit_counts: get_empty_knot_counts(&knots),
            variables,
        };

        (knots, data)
    }

    fn get_validation_result_from_string(content: &str) -> Result<(), ValidationError> {
        let (mut knots, data) = get_validation_data_from_string(content);
        validate_story_content(&mut knots, &data)
    }

    fn get_validation_error_from_string(content: &str) -> ValidationError {
        let (mut knots, data) = get_validation_data_from_string(content);
        validate_story_content(&mut knots, &data).unwrap_err()
    }

    #[test]
    fn creating_validation_data_sets_default_knot_names() {
        let content = "
== tripoli
= cinema
-> END
= with_family
-> END

== addis_ababa
-> END
= with_family
-> END
";

        let (knots, _, _) = read_story_content_from_string(content).unwrap();

        let data = ValidationData::from_data(&knots, &HashMap::new());

        assert_eq!(data.knots.len(), 3);

        let tripoli_default = &data.knots.get("tripoli").unwrap().default_stitch;
        let addis_ababa_default = &data.knots.get("addis_ababa").unwrap().default_stitch;

        assert_eq!(tripoli_default, "cinema");
        assert_eq!(addis_ababa_default, ROOT_KNOT_NAME);
    }

    #[test]
    fn creating_validation_data_sets_stitches() {
        let content = "
== tripoli
= cinema
-> END
= with_family
-> END

== addis_ababa
-> END
= with_family
-> END
";

        let (knots, _, _) = read_story_content_from_string(content).unwrap();

        let data = ValidationData::from_data(&knots, &HashMap::new());

        let tripoli_stitches = &data.knots.get("tripoli").unwrap().stitches;
        let addis_ababa_stitches = &data.knots.get("addis_ababa").unwrap().stitches;

        assert_eq!(tripoli_stitches.len(), 2);
        assert!(tripoli_stitches.contains_key(&"cinema".to_string()));
        assert!(tripoli_stitches.contains_key(&"with_family".to_string()));

        assert_eq!(addis_ababa_stitches.len(), 2);
        assert!(addis_ababa_stitches.contains_key(&ROOT_KNOT_NAME.to_string()));
        assert!(addis_ababa_stitches.contains_key(&"with_family".to_string()));
    }

    #[test]
    fn creating_validation_data_sets_variable_names() {
        let mut variables = HashMap::new();

        variables.insert("counter".to_string(), VariableInfo::new(1, 0));
        variables.insert("health".to_string(), VariableInfo::new(75.0, 1));

        let data = ValidationData::from_data(&HashMap::new(), &variables);

        assert_eq!(data.follow_data.variables.len(), 2);
        assert!(data.follow_data.variables.contains_key("counter"));
        assert!(data.follow_data.variables.contains_key("health"));
    }

    #[test]
    fn validating_story_raises_error_if_expression_has_non_matching_types() {
        let content = "

{2 + \"string\"}
{true + 1}

";
        let error = get_validation_error_from_string(content);

        assert_eq!(error.variable_errors.len(), 2);
    }

    #[test]
    fn validating_story_raises_error_if_condition_has_invalid_types_in_comparison() {
        let content = "

{2 + \"string\" == 0: True | False}
*   {true and 3 + \"string\" == 0} Choice

";
        let error = get_validation_error_from_string(content);

        assert_eq!(error.variable_errors.len(), 2);
    }

    #[test]
    fn validating_story_raises_error_if_comparison_is_between_different_types() {
        let content = "

VAR int = 0

{\"string\" == 0: True | False}
{0 == \"string\": True | False}
{0 == \"string\": True | False}
{int == \"string\": True | False}
{0 == true: True | False}

";
        let error = get_validation_error_from_string(content);

        assert_eq!(error.variable_errors.len(), 5);
    }

    #[test]
    fn all_expressions_in_conditions_are_validated() {
        let content = "

{true and 2 + \"str\" == 0 or 3 + true == 0: True | False}

";
        let error = get_validation_error_from_string(content);

        assert_eq!(error.variable_errors.len(), 2);
    }

    #[test]
    fn validating_story_raises_error_for_every_address_that_does_not_exist() {
        let content = "

-> address
{variable}

";
        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 2);
    }

    #[test]
    fn validating_story_raises_error_for_bad_addresses_in_choices() {
        let content = "

*   {variable == 0} Choice 1
*   Choice 2 -> address
    -> address

";
        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 3);
    }

    #[test]
    fn validating_story_does_not_raise_an_error_for_internal_addressing_in_stitches_and_knots() {
        let content = "

== knot
= one 
-> two

= two
-> one

";

        assert!(get_validation_result_from_string(content).is_ok());
    }

    #[test]
    fn validating_story_raises_an_error_if_addresses_refer_to_internal_addresses_in_other_knots() {
        let content = "

== knot_one
= one 
Line one.

== knot_two
-> one

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 1);
    }

    #[test]
    fn validating_story_sets_all_addresses_to_validated_addresses() {
        let content = "

VAR variable = true

-> knot

== knot
{variable: True | False}

";

        let (mut knots, data) = get_validation_data_from_string(content);

        let pre_validated_addresses = format!("{:?}", &knots).matches("Validated(").count();
        let pre_raw_addresses = format!("{:?}", &knots).matches("Raw(").count();

        assert!(pre_raw_addresses >= 2);

        validate_story_content(&mut knots, &data).unwrap();

        let validated_addresses = format!("{:?}", &knots).matches("Validated(").count();
        let raw_addresses = format!("{:?}", &knots).matches("Raw(").count();

        assert_eq!(raw_addresses, 0);
        assert_eq!(validated_addresses, pre_validated_addresses + 2);
    }

    #[test]
    fn encountered_invalid_address_errors_stop_expressions_from_trying_to_evaluate() {
        let content = "

{knot + \"string\"}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 1);
        assert!(error.variable_errors.is_empty());
    }

    #[test]
    fn encountered_invalid_address_errors_stop_conditions_from_trying_to_evaluate() {
        let content = "

{knot + \"string\" == 0: True | False}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 1);
        assert!(error.variable_errors.is_empty());
    }

    #[test]
    fn invalid_addresses_in_choices_can_be_in_selection_text_only() {
        let content = "

*   Invalid address in selection text: [{knot}]

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 1);
        assert!(error.variable_errors.is_empty());
    }

    #[test]
    fn invalid_addresses_in_choices_can_be_in_display_text_only() {
        let content = "

*   Invalid address in display text: [] {knot}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 1);
        assert!(error.variable_errors.is_empty());
    }

    #[test]
    fn address_validation_is_done_in_first_displayed_text_of_branching_choice() {
        let content = "

*   Invalid address in same line display text: [] {knot}
*   [Selection]
    Invalid address in next line display text: {knot}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 2);
        assert!(error.variable_errors.is_empty());
    }

    #[test]
    fn expression_validation_is_done_in_first_displayed_text_of_branching_choice() {
        let content = "

*   Invalid expression in same line display text: [] {2 + \"string\"}
*   [Selection]
    Invalid expression in next line display text: {2 + \"string\"}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.variable_errors.len(), 2);
    }

    #[test]
    fn addresses_are_validated_if_correct_in_all_displayed_text_of_branching_choices() {
        let content = "

VAR variable = 0

*   \\{variable}
*   [Selection] -> knot
*   [Selection 2]
    -> knot

== knot
Line

";

        let (mut knots, data) = get_validation_data_from_string(content);

        let pre_raw_addresses = format!("{:?}", &knots).matches("Raw(").count();

        assert!(pre_raw_addresses >= 3);

        validate_story_content(&mut knots, &data).unwrap();

        dbg!(&knots);

        let raw_addresses = format!("{:?}", &knots).matches("Raw(").count();

        assert_eq!(raw_addresses, 0);
    }

    #[test]
    fn invalid_address_errors_in_choices_with_display_and_selection_text_validates_expr_once() {
        let content = "

*   {knot} Choice with an invalid address in condition
*   Choice with an invalid address in an expression: {knot}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.invalid_address_errors.len(), 2);
        assert!(error.variable_errors.is_empty());
    }

    #[test]
    fn items_inside_true_parts_of_conditions_are_validated() {
        let content = "

{true: {knot}}
{true: {2 + \"string\"}}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.num_errors(), 2);
    }

    #[test]
    fn items_inside_false_parts_of_conditions_are_validated() {
        let content = "

{true: True | {knot}}
{true: True | {2 + \"string\"}}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.num_errors(), 2);
    }

    #[test]
    fn items_inside_parts_of_alternative_sequences_are_validated() {
        let content = "

{{2 + \"string\"} | {knot} | -> other_knot}

";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.num_errors(), 3);
    }

    #[test]
    fn expressions_add_one_error_for_errors_in_nested_parts() {
        let content = "{1 + (2 + (3 + true))}";

        let error = get_validation_error_from_string(content);

        assert_eq!(error.variable_errors.len(), 1);
    }
}