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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
// #![warn(missing_docs)]

use std::collections::HashMap;

use log::*;
use serde::Deserialize;

pub use crate::{
    yarn_proto::Program,
    utils::*,
    value::YarnValue,
};

pub mod yarn_proto {
    include!(concat!(env!("OUT_DIR"), "/yarn.rs"));
}

mod utils;
mod value;

#[derive(Debug, Deserialize)]
pub struct LineInfo {
    pub id: String,
    pub text: String,
    pub file: String,
    pub node: String,
    #[serde(rename="lineNumber")]
    pub line_number: u32,
}

/// A line of dialogue, sent from the [`VirtualMachine`] to the game.
///
/// When the game receives a `Line`, it should do the following things to prepare the line for
/// presentation to the user.
///
/// 1. Use the value in the `id` field to look up the appropriate user-facing text in the string
/// table.
///
/// 2. For each of the entries in the `substitutions` field, replace the corresponding placeholder
/// with the entry. That is, the text "`{0}`" should be replaced with the value of
/// `substitutions[0]`, "`{1}`" with `substitutions[1]`, and so on.
///
/// 3. Use [`expand_format_functions`] to expand all [format functions](
/// https://yarnspinner.dev/docs/syntax#format-functions) in the line.
///
/// You do not create instances of this struct yourself. They are created by the [`VirtualMachine`]
/// during program execution.
#[derive(Debug, Clone)]
pub struct Line {
    pub id: String,
    pub substitutions: Vec<String>,
}

impl Line {
    fn new(id: String, substitutions: Vec<String>) -> Self {
        Self {
            id,
            substitutions,
        }
    }
}

pub struct YarnOption {
    pub line: Line,
    pub id: u32,
    pub destination_node: String,
}

impl YarnOption {
    fn new(line: Line, id: u32, destination_node: String) -> Self {
        Self {
            line,
            id,
            destination_node,
        }
    }
}

pub type ReturningFunction = dyn Fn(&[YarnValue]) -> YarnValue + Send + Sync;
pub type Function = dyn Fn(&[YarnValue]) + Send + Sync;

pub enum YarnFunction {
    Void(&'static Function),
    Returning(&'static ReturningFunction),
}

impl YarnFunction {
    pub fn call(&self, params: &[YarnValue]) -> Option<YarnValue> {
        match self {
            Self::Void(func) => {
                (func)(params);
                None
            }
            Self::Returning(func) => {
                let result = (func)(params);
                Some(result)
            }
        }
    }
}

enum ParamCount {
    N(u8),
    Variadic,
}

impl From<i8> for ParamCount {
    fn from(val: i8) -> Self {
        if val >= 0 {
            Self::N(val as u8)
        } else {
            Self::Variadic
        }
    }
}

pub struct FunctionInfo {
    param_count: ParamCount,
    func: YarnFunction,
}

impl FunctionInfo {
    pub fn new(param_count: i8, func: &'static Function) -> Self {
        Self {
            param_count: param_count.into(),
            func: YarnFunction::Void(func),
        }
    }

    pub fn new_returning(param_count: i8, func: &'static ReturningFunction) -> Self {
        Self {
            param_count: param_count.into(),
            func: YarnFunction::Returning(func),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ExecutionState {
    Stopped,
    WaitingOnOptionSelection,
    Suspended,
    Running,
}

pub enum SuspendReason {
    Line(Line),
    Options(Vec<YarnOption>),
    Command(String),
    NodeChange {
        start: String,
        end: String,
    },
    DialogueComplete(String),
}

pub struct VmState {
    pub current_node_name: String,
    // TODO: Switch back to usize soon.
    pub program_counter: isize,
    pub current_options: Vec<(Line, String)>,
    pub stack: Vec<YarnValue>,
}

impl VmState {
    fn new() -> Self {
        Self {
            current_node_name: String::new(),
            program_counter: 0,
            current_options: Vec::new(),
            stack: Vec::new(),
        }
    }
}

pub struct VirtualMachine {
    pub state: VmState,
    pub variable_storage: HashMap<String, YarnValue>,
    pub library: HashMap<String, FunctionInfo>,

    pub execution_state: ExecutionState,

    pub program: Program,
}

impl VirtualMachine {
    pub fn new(program: Program) -> Self {
        let mut library = HashMap::new();
        library.insert(
            "Add".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                parameters[0].add(&parameters[1]).unwrap()
            }),
        );

        library.insert(
            "Minus".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                parameters[0].sub(&parameters[1]).unwrap()
            }),
        );

        library.insert(
            "UnaryMinus".to_string(),
            FunctionInfo::new_returning(1, &|parameters: &[YarnValue]| {
                parameters[0].neg()
            }),
        );

        library.insert(
            "Divide".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                parameters[0].div(&parameters[1]).unwrap()
            }),
        );

        library.insert(
            "Multiply".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                parameters[0].mul(&parameters[1]).unwrap()
            }),
        );

        library.insert(
            "Modulo".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                parameters[0].rem(&parameters[1]).unwrap()
            }),
        );

        library.insert(
            "EqualTo".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0] == parameters[1]).into()
            }),
        );

        library.insert(
            "NotEqualTo".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0] != parameters[1]).into()
            }),
        );

        library.insert(
            "GreaterThan".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0] > parameters[1]).into()
            }),
        );

        library.insert(
            "GreaterThanOrEqualTo".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0] >= parameters[1]).into()
            }),
        );

        library.insert(
            "LessThan".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0] < parameters[1]).into()
            }),
        );

        library.insert(
            "LessThanOrEqualTo".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0] <= parameters[1]).into()
            }),
        );

        library.insert(
            "And".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0].as_bool() && parameters[1].as_bool()).into()
            }),
        );

        library.insert(
            "Or".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0].as_bool() || parameters[1].as_bool()).into()
            }),
        );

        library.insert(
            "Xor".to_string(),
            FunctionInfo::new_returning(2, &|parameters: &[YarnValue]| {
                (parameters[0].as_bool() ^ parameters[1].as_bool()).into()
            }),
        );

        library.insert(
            "Not".to_string(),
            FunctionInfo::new_returning(1, &|parameters: &[YarnValue]| {
                (!parameters[0].as_bool()).into()
            }),
        );

        Self {
            state: VmState::new(),
            variable_storage: HashMap::new(),
            library,
            execution_state: ExecutionState::Stopped,
            program,
        }
    }

    pub fn set_node(&mut self, node_name: &str) -> bool {
        // TODO: Handle error cases.
        // if (Program == null || Program.Nodes.Count == 0) {
        //     throw new DialogueException($"Cannot load node {nodeName}: No nodes have been loaded.");
        // }

        // if (Program.Nodes.ContainsKey(nodeName) == false) {
        //     executionState = ExecutionState.Stopped;
        //     throw new DialogueException($"No node named {nodeName} has been loaded.");
        // }

        // dialogue.LogDebugMessage ("Running node " + nodeName);

        self.state = VmState::new();
        self.state.current_node_name = node_name.to_string();

        // TODO: Suspending makes sense to me, but is it correct?
        self.execution_state = ExecutionState::Suspended;

        true
    }

    // TODO: Return the reason why we stopped execution.
    // Either Line, Options, Command, NodeStart?, NodeEnd?, DialogeEnd
    pub fn continue_dialogue(&mut self) -> SuspendReason {
        // TODO: Handle error cases.
        // if (currentNode == null)
        // {
        //     throw new DialogueException("Cannot continue running dialogue. No node has been selected.");
        // }

        if self.execution_state == ExecutionState::WaitingOnOptionSelection {
            panic!("Cannot continue running dialogue. Still waiting on option selection.");
        }

        self.execution_state = ExecutionState::Running;

        // Execute instructions until something forces us to stop
        loop {
            let instruction_count = if !self.state.current_node_name.is_empty() {
                self.program.nodes[&self.state.current_node_name].instructions.len()
            } else {
                // No node is running, so return 0.
                0
            };

            // If we've reached the end of a node, stop execution.
            if self.state.program_counter as usize >= instruction_count {
                let last_node = self.state.current_node_name.clone();
                self.execution_state = ExecutionState::Stopped;
                self.state = VmState::new();
                // dialogue.LogDebugMessage ("Run complete.");
                return SuspendReason::DialogueComplete(last_node);
            }

            let current_instruction = {
                let current_node = &self.program.nodes[&self.state.current_node_name];
                current_node.instructions[self.state.program_counter as usize].clone()
            };

            let suspend = self.run_instruction(current_instruction);

            self.state.program_counter += 1;

            if let Some(suspend) = suspend {
                return suspend;
            }
        }
    }

    pub fn set_selected_option(&mut self, selected_option_id: u32) {
        let selected_option_id = selected_option_id as usize;

        if self.execution_state != ExecutionState::WaitingOnOptionSelection {
            panic!();
            // throw new DialogueException(@"SetSelectedOption was called, but Dialogue wasn't waiting for a selection.
            // This method should only be called after the Dialogue is waiting for the user to select an option.");
        }

        if selected_option_id >= self.state.current_options.len() {
            panic!();
            // throw new ArgumentOutOfRangeException($"{selectedOptionID} is not a valid option ID (expected a number between 0 and {state.currentOptions.Count-1}.");
        }

        // We now know what number option was selected; push the
        // corresponding node name to the stack
        let destination_node = self.state.current_options[selected_option_id].1.clone();
        self.state.stack.push(YarnValue::Str(destination_node));

        // We no longer need the accumulated list of options; clear it
        // so that it's ready for the next one
        self.state.current_options.clear();

        // We're no longer in the WaitingForOptions state; we are now
        // instead Suspended
        self.execution_state = ExecutionState::Suspended;

        debug!("Selected option: {}", selected_option_id);
    }

    fn run_instruction(&mut self, instruction: yarn_proto::Instruction) -> Option<SuspendReason> {
        use yarn_proto::{
            instruction::OpCode,
            operand::Value,
        };

        let opcode = OpCode::from_i32(instruction.opcode)
            .unwrap();

        debug!("Running {:?} {:?}", opcode, instruction.operands);

        match opcode {
            OpCode::JumpTo => {
                if let Some(Value::StringValue(label)) = &instruction.operands[0].value {
                    self.state.program_counter = self.find_instruction_point_for_label(label) - 1;
                } else {
                    // TODO: Error.
                }
            }
            OpCode::Jump => {
                if let Some(YarnValue::Str(label)) = self.state.stack.last() {
                    self.state.program_counter = self.find_instruction_point_for_label(label) - 1;
                } else {
                    // TODO: Error.
                }
            }
            OpCode::RunLine => {
                // Looks up a string from the string table and passes it to the client as a line.
                if let Some(Value::StringValue(string_key)) = &instruction.operands[0].value {
                    let mut substitutions = Vec::new();

                    // The second operand, if provided (compilers prior
                    // to v1.1 don't include it), indicates the number
                    // of expressions in the command. We need to pop
                    // these values off the stack and deliver them to
                    // the line handler.
                    if let Some(Value::FloatValue(expression_count)) = instruction.operands.get(1).and_then(|o| o.value.as_ref()) {
                        let expression_count = *expression_count as u32;
                        substitutions.resize(expression_count as usize, String::new());

                        for expression_index in (0..expression_count as usize).rev() {
                            let substitution = self.state.stack.pop().unwrap().as_string();
                            // TODO: Avoid bounds check due to indexing.
                            substitutions[expression_index] = substitution;
                        }
                    }

                    self.execution_state = ExecutionState::Suspended;
                    let line = Line::new(string_key.clone(), substitutions);
                    return Some(SuspendReason::Line(line));
                } else {
                    // TODO: Handle this error!
                }
            }
            OpCode::RunCommand => {
                // Passes a string to the client as a custom command
                if let Some(Value::StringValue(command)) = &instruction.operands[0].value {
                    let mut command_text = command.clone();

                    // The second operand, if provided (compilers prior
                    // to v1.1 don't include it), indicates the number
                    // of expressions in the command. We need to pop
                    // these values off the stack and deliver them to
                    // the line handler.
                    if let Some(Value::FloatValue(expression_count)) = instruction.operands.get(1).and_then(|o| o.value.as_ref()) {
                        let expression_count = *expression_count as u32;

                        // Get the values from the stack, and
                        // substitute them into the command text
                        for expression_index in (0..expression_count).rev() {
                            let substitution = self.state.stack.pop().unwrap().as_string();

                            // TODO: Try using String::replace_range.
                            command_text = command_text.replacen(&format!("{{{}}}", expression_index), &substitution, 1);
                        }
                    }

                    self.execution_state = ExecutionState::Suspended;
                    return Some(SuspendReason::Command(command_text));
                } else {
                    // TODO: Error.
                }
            }
            OpCode::AddOption => {
                let line = if let Some(Value::StringValue(opt)) = instruction.operands.get(0).and_then(|o| o.value.as_ref()) {
                    let mut substitutions = Vec::new();

                    // get the number of expressions that we're
                    // working with out of the third operand
                    if let Some(Value::FloatValue(expression_count)) = instruction.operands.get(2).and_then(|o| o.value.as_ref()) {
                        let expression_count = *expression_count as u32;
                        substitutions.resize(expression_count as usize, String::new());

                        // pop the expression values off the stack in
                        // reverse order, and store the list of substitutions
                        for expression_index in (0..expression_count as usize).rev() {
                            let substitution = self.state.stack.pop().unwrap().as_string();
                            // TODO: Avoid bounds check due to indexing.
                            substitutions[expression_index] = substitution;
                        }
                    }
                    Line::new(opt.clone(), substitutions)
                } else {
                    // TODO: Handle error.
                    panic!();
                };
                let node_name = if let Some(Value::StringValue(opt)) = instruction.operands.get(1).and_then(|o| o.value.as_ref()) {
                    opt.clone()
                } else {
                    // TODO: Handle error.
                    panic!();
                };

                self.state.current_options.push((line, node_name));
            }
            OpCode::ShowOptions => {
                // If we have no options to show, immediately stop.
                if self.state.current_options.is_empty() {
                    self.execution_state = ExecutionState::Stopped;
                    let last_node = self.state.current_node_name.clone();
                    self.state = VmState::new();
                    return Some(SuspendReason::DialogueComplete(last_node));
                }

                // Present the list of options to the user and let them pick
                let mut options = Vec::new();

                for (i, opt) in self.state.current_options.iter().enumerate() {
                    options.push(YarnOption::new(opt.0.clone(), i as u32, opt.1.clone()));
                }

                // We can't continue until our client tell us which option to pick.
                self.execution_state = ExecutionState::WaitingOnOptionSelection;

                return Some(SuspendReason::Options(options));
            }
            OpCode::PushString => {
                if let Some(Value::StringValue(val)) = &instruction.operands[0].value {
                    self.state.stack.push(YarnValue::Str(val.clone()));
                } else {
                    // TODO: Error: bad operand.
                }
            }
            OpCode::PushFloat => {
                if let Some(Value::FloatValue(val)) = &instruction.operands[0].value {
                    self.state.stack.push(YarnValue::Number(*val));
                } else {
                    // TODO: Error: bad operand.
                }
            }
            OpCode::PushBool => {
                if let Some(Value::BoolValue(val)) = &instruction.operands[0].value {
                    self.state.stack.push(YarnValue::Bool(*val));
                } else {
                    // TODO: Error: bad operand.
                }
            }
            OpCode::PushNull => {
                self.state.stack.push(YarnValue::Null);
            },
            OpCode::JumpIfFalse => {
                // Jump to a named label if the value on the top of the stack
                // evaluates to the boolean value 'false'.
                if let Some(val) = self.state.stack.last() {
                    if !val.as_bool() {
                        if let Some(Value::StringValue(label)) = &instruction.operands[0].value {
                            self.state.program_counter = self.find_instruction_point_for_label(label) - 1;
                        } else {
                            // TODO: Error.
                        }
                    }
                } else {
                    // TODO: Error.
                }
            }
            OpCode::Pop => {
                self.state.stack.pop();
            }
            OpCode::CallFunc => {
                // Call a function, whose parameters are expected to
                // be on the stack. Pushes the function's return value,
                // if it returns one.
                if let Some(Value::StringValue(func_name)) = &instruction.operands[0].value {
                    if let Some(function) = self.library.get(func_name) {
                        let actual_param_count = self.state.stack.pop().unwrap().as_number() as u8;

                        // If a function is variadic, it takes as many parameters as it was given.
                        let expected_param_count = match function.param_count {
                            ParamCount::N(n) => n,
                            ParamCount::Variadic => actual_param_count,
                        };

                        if expected_param_count != actual_param_count {
                            panic!(
                                "Function {} expected {}, but received {}",
                                func_name,
                                expected_param_count,
                                actual_param_count,
                            );
                        }

                        let result = if actual_param_count == 0 {
                            function.func.call(&[])
                        } else {
                            // Get the parameters, which were pushed in reverse
                            let mut parameters = vec![YarnValue::Null; actual_param_count as usize];
                            for i in (0..actual_param_count as usize).rev() {
                                let value = self.state.stack.pop().unwrap();
                                parameters[i] = value;
                            }

                            function.func.call(&parameters)
                        };

                        if let Some(result) = result {
                            // If the function returns a value, push it.
                            self.state.stack.push(result);
                        }
                    } else {
                        // TODO: Error.
                    }
                } else {
                    // TODO: Error.
                }
            }
            OpCode::PushVariable => {
                if let Some(Value::StringValue(var_name)) = &instruction.operands[0].value {
                    if let Some(val) = self.variable_storage.get(var_name) {
                        self.state.stack.push(val.clone());
                    } else {
                        // Value is undefined, so push null.
                        self.state.stack.push(YarnValue::Null);
                    }
                } else {
                    // TODO: Error.
                }
            }
            OpCode::StoreVariable => {
                if let Some(Value::StringValue(var_name)) = &instruction.operands[0].value {
                    if let Some(val) = self.state.stack.last() {
                        self.variable_storage.insert(var_name.clone(), val.clone());
                    } else {
                        // TODO: Error.
                    }
                } else {
                    // TODO: Error.
                }
            }
            OpCode::Stop => {
                self.execution_state = ExecutionState::Stopped;
                let last_node = self.state.current_node_name.clone();
                self.state = VmState::new();
                return Some(SuspendReason::DialogueComplete(last_node));
            }
            OpCode::RunNode => {
                if let Some(YarnValue::Str(node_name)) = self.state.stack.pop() {
                    let old_node = self.state.current_node_name.clone();

                    self.set_node(&node_name);

                    // Decrement program counter here, because it will
                    // be incremented when this function returns, and
                    // would mean skipping the first instruction
                    self.state.program_counter -= 1;

                    self.execution_state = ExecutionState::Suspended;

                    return Some(SuspendReason::NodeChange {
                        start: node_name.clone(),
                        end: old_node,
                    })
                } else {
                    // TODO: Error!
                }
            }
        }

        None
    }

    fn find_instruction_point_for_label(&self, label: &str) -> isize {
        let instruction_point = self.program.nodes.get(&self.state.current_node_name)
            .and_then(|node| node.labels.get(label));
        if let Some(&instruction_point) = instruction_point {
            instruction_point as isize
        } else {
            panic!("Unknown label {} in node {}", label, self.state.current_node_name);
        }
    }
}