duckscript/types/
runtime.rs

1//! # runtime
2//!
3//! The runtime context structures.
4//!
5
6#[cfg(test)]
7#[path = "./runtime_test.rs"]
8mod runtime_test;
9
10use crate::types::command::Commands;
11use crate::types::env::Env;
12use crate::types::instruction::Instruction;
13use std::any::Any;
14use std::cell::RefCell;
15use std::collections::{HashMap, HashSet};
16use std::rc::Rc;
17
18/// enum defining what values can be stored in the state map
19#[derive(Debug, Clone)]
20pub enum StateValue {
21    /// boolean value
22    Boolean(bool),
23    /// signed number
24    Number(isize),
25    /// unsigned number
26    UnsignedNumber(usize),
27    /// signed number
28    Number32Bit(i32),
29    /// unsigned number
30    UnsignedNumber32Bit(u32),
31    /// signed number
32    Number64Bit(i64),
33    /// unsigned number
34    UnsignedNumber64Bit(u64),
35    /// textual value
36    String(String),
37    /// byte (u8) array
38    ByteArray(Vec<u8>),
39    /// list
40    List(Vec<StateValue>),
41    /// unique set of values
42    Set(HashSet<String>),
43    /// sub state value
44    SubState(HashMap<String, StateValue>),
45    /// any value
46    Any(Rc<RefCell<dyn Any>>),
47}
48
49/// The context structure
50#[derive(Clone)]
51pub struct Context {
52    /// The runtime variables
53    pub variables: HashMap<String, String>,
54    /// The runtime state
55    pub state: HashMap<String, StateValue>,
56    /// The command implementations
57    pub commands: Commands,
58}
59
60impl Context {
61    /// Creates and returns a new instance.
62    pub fn new() -> Context {
63        Context {
64            variables: HashMap::new(),
65            state: HashMap::new(),
66            commands: Commands::new(),
67        }
68    }
69}
70
71/// The runtime structure
72pub struct Runtime {
73    /// The script instructions
74    pub instructions: Option<Vec<Instruction>>,
75    /// Label to line number mapping
76    pub label_to_line: HashMap<String, usize>,
77    /// The runtime context
78    pub context: Context,
79    /// The runtime env
80    pub env: Env,
81}
82
83impl Runtime {
84    /// Creates and returns a new instance.
85    pub fn new(context: Context, env: Option<Env>) -> Runtime {
86        Runtime {
87            instructions: None,
88            label_to_line: HashMap::new(),
89            context,
90            env: match env {
91                Some(value) => value,
92                None => Env::default(),
93            },
94        }
95    }
96}