Skip to main content

scratch_test_interpreter/
default_state.rs

1use std::collections::{BTreeSet, HashMap};
2#[cfg(feature = "rand")]
3use std::fmt::Debug;
4
5use either::Either;
6#[cfg(feature = "rand")]
7use rand::RngExt;
8use smodel::{
9    ProjectDoc,
10    attrs::{List, Variable},
11};
12use svalue::{SList, SNumber, SValue};
13
14use crate::state::{OutputKind, State};
15
16#[derive(Debug, PartialEq, PartialOrd, Clone)]
17pub enum Action {
18    Output {
19        kind: crate::state::OutputKind,
20        message: SValue,
21    },
22    AskQuestion {
23        message: SValue,
24    },
25    RequestRandom {
26        from: SNumber,
27        to: SNumber,
28        received: SNumber,
29    },
30    WaitFor {
31        secs: SNumber,
32    },
33}
34
35#[derive(derive_more::Debug, Default, derive_more::PartialEq, derive_getters::Getters)]
36pub struct DefaultState {
37    /// All data (variable/list) identifiers which were
38    /// used before initialized
39    ///
40    /// - variables are initialized by set operation
41    /// - lists are initialized by deleting all elements with clear block
42    uninitialized_usages: BTreeSet<Either<Variable, List>>,
43    /// All data (variable/list) identifiers which were
44    /// used to initialize the corresponding data.
45    ///
46    /// - variables are initialized by set operation
47    /// - lists are initialized by deleting all elements with clear block
48    initialized_data: BTreeSet<Either<Variable, List>>,
49    variables: HashMap<Variable, SValue>,
50    lists: HashMap<List, SList>,
51    actions: Vec<Action>,
52
53    answer_index: Option<usize>,
54    answer_inputs: Vec<svalue::ARc<str>>,
55
56    #[cfg(feature = "rand")]
57    #[debug("randoms: ...")]
58    #[partial_eq(skip)]
59    randoms: Option<Box<dyn rand::Rng>>,
60    predefined_randoms: Option<(svalue::ARc<[svalue::SNumber]>, usize)>,
61}
62
63#[allow(unused)]
64impl DefaultState {
65    pub fn new() -> Self {
66        DefaultState {
67            uninitialized_usages: Default::default(),
68            initialized_data: Default::default(),
69            variables: HashMap::new(),
70            lists: HashMap::new(),
71            actions: vec![],
72            answer_index: None,
73            answer_inputs: vec![],
74            #[cfg(feature = "rand")]
75            randoms: None,
76            predefined_randoms: None,
77        }
78    }
79
80    pub fn from_doc(doc: &ProjectDoc, max_list_length: i64) -> Self {
81        let mut s = Self::new();
82        s.add_data_from_doc(doc, max_list_length);
83        s
84    }
85
86    pub fn add_data_from_doc(&mut self, doc: &ProjectDoc, max_length: i64) -> &mut Self {
87        self.add_variables_from_doc(doc)
88            .add_lists_from_doc(doc, max_length)
89    }
90
91    pub fn add_variables_from_doc(&mut self, doc: &ProjectDoc) -> &mut Self {
92        self.variables.extend(
93            doc.targets()
94                .iter()
95                .flat_map(|t| t.variables().values())
96                .cloned(),
97        );
98        self
99    }
100
101    pub fn add_lists_from_doc(&mut self, doc: &ProjectDoc, max_length: i64) -> &mut Self {
102        self.lists
103            .extend(
104                doc.targets()
105                    .iter()
106                    .flat_map(|t| t.lists().values())
107                    .map(|(dataid, v)| {
108                        let mut list = SList::new(max_length);
109                        for i in v {
110                            // TODO: rethink
111                            list.append_item(i.clone());
112                        }
113                        (dataid.clone(), list)
114                    }),
115            );
116        self
117    }
118
119    fn use_uninitialized_list(&mut self, list_id: &List) -> Result<(), <Self as State>::Error> {
120        let list_id = Either::Right(list_id.clone());
121        if !self.initialized_data.contains(&list_id) {
122            self.uninitialized_usages.insert(list_id);
123        }
124        Ok(())
125    }
126
127    fn use_uninitialized_variable(
128        &mut self,
129        variable_id: &Variable,
130    ) -> Result<(), <Self as State>::Error> {
131        let variable_id = Either::Left(variable_id.clone());
132        if !self.initialized_data.contains(&variable_id) {
133            self.uninitialized_usages.insert(variable_id);
134        }
135        Ok(())
136    }
137
138    pub fn output_lines(&self) -> impl DoubleEndedIterator<Item = (&SValue)> {
139        self.output_actions().map(|(_, text)| text)
140    }
141
142    pub fn output_actions(&self) -> impl DoubleEndedIterator<Item = (&OutputKind, &SValue)> {
143        self.actions().iter().flat_map(|a| {
144            if let Action::Output { kind, message } = a {
145                Some((kind, message))
146            } else {
147                None
148            }
149        })
150    }
151    pub fn used_randoms(&self) -> impl DoubleEndedIterator<Item = &SNumber> {
152        self.actions().iter().flat_map(|a| {
153            if let Action::RequestRandom { received, .. } = a {
154                Some(received)
155            } else {
156                None
157            }
158        })
159    }
160
161    #[cfg(feature = "rand")]
162    pub fn set_randoms(&mut self, rng: Option<Box<dyn rand::Rng>>) -> &mut Self {
163        self.randoms = rng;
164        self
165    }
166    pub fn set_predefined_randoms(
167        &mut self,
168        predefined: svalue::ARc<[svalue::SNumber]>,
169    ) -> &mut Self {
170        self.predefined_randoms = Some((predefined, 0));
171        self
172    }
173    pub fn set_answers(&mut self, answers: Vec<svalue::ARc<str>>) -> &mut Self {
174        self.answer_inputs = answers;
175        self.answer_index = None;
176        self
177    }
178    pub fn variables_mut(&mut self) -> &mut HashMap<Variable, SValue> {
179        &mut self.variables
180    }
181    pub fn lists_mut(&mut self) -> &mut HashMap<List, SList> {
182        &mut self.lists
183    }
184}
185
186#[derive(Debug, PartialEq, PartialOrd, Clone, thiserror::Error)]
187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
188#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
189#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
190pub enum DefaultStateError {
191    #[error("variable {0:?} does not exist in state")]
192    VariableNotFound(Variable),
193    #[error("list {0:?} does not exist in state")]
194    ListNotFound(List),
195    #[error("list {id:?} is full, no item can be inserted")]
196    ListFull { id: List },
197    #[error("program is not allowed to request random numbers")]
198    RandomsDisabled,
199    #[error("program requested random number that doesn't match predefined ones")]
200    IncompatibleRandomRequested {
201        predefined: SNumber,
202        #[cfg_attr(feature = "utoipa", schema(value_type = Value))]
203        #[cfg_attr(feature = "schemars", schemars(skip))]
204        range: either::Either<(i64, i64), (f64, f64)>,
205    },
206    #[error("program asked question without a predefined answer remaining")]
207    NoMoreAnswers,
208}
209
210impl State for DefaultState {
211    type Error = DefaultStateError;
212
213    fn ask_question(&mut self, question: SValue) -> Result<(), Self::Error> {
214        self.actions.push(Action::AskQuestion { message: question });
215        self.answer_index = Some(self.answer_index.map(|x| x + 1).unwrap_or(0));
216
217        self.answer_index
218            .and_then(|index| self.answer_inputs.get(index))
219            .ok_or(DefaultStateError::NoMoreAnswers)?;
220        Ok(())
221    }
222    fn last_answer(&mut self) -> Result<&str, Self::Error> {
223        if let Some(index) = self.answer_index {
224            Ok(self
225                .answer_inputs
226                .get(index)
227                .or(self.answer_inputs.last())
228                .map(|s| s.as_ref())
229                .unwrap_or(""))
230        } else {
231            Ok("")
232        }
233    }
234
235    fn request_int_random(
236        &mut self,
237        range: std::ops::RangeInclusive<i64>,
238    ) -> Result<i64, Self::Error> {
239        let received = if let Some((pred, pos)) = self.predefined_randoms.as_mut()
240            && let Some(received) = pred.get(*pos)
241        {
242            match received {
243                SNumber::Float(_) => {
244                    return Err(DefaultStateError::IncompatibleRandomRequested {
245                        predefined: *received,
246                        range: Either::Left(range.into_inner()),
247                    });
248                }
249                SNumber::Int(i) => {
250                    *pos += 1;
251                    *i
252                }
253            }
254        } else {
255            #[cfg(not(feature = "rand"))]
256            return Err(DefaultStateError::RandomsDisabled);
257            #[cfg(feature = "rand")]
258            self.randoms
259                .as_mut()
260                .ok_or(DefaultStateError::RandomsDisabled)?
261                .random_range(range.clone())
262        };
263
264        let (from, to) = range.into_inner();
265        self.actions.push(Action::RequestRandom {
266            from: SNumber::Int(from),
267            to: SNumber::Int(to),
268            received: SNumber::Int(received),
269        });
270        Ok(received)
271    }
272
273    fn request_float_random(
274        &mut self,
275        range: std::ops::RangeInclusive<f64>,
276    ) -> Result<f64, Self::Error> {
277        let received = if let Some((pred, pos)) = self.predefined_randoms.as_mut()
278            && let Some(received) = pred.get(*pos)
279        {
280            match received {
281                SNumber::Int(_) => {
282                    return Err(DefaultStateError::IncompatibleRandomRequested {
283                        predefined: *received,
284                        range: Either::Right(range.into_inner()),
285                    });
286                }
287                SNumber::Float(i) => {
288                    *pos += 1;
289                    *i
290                }
291            }
292        } else {
293            #[cfg(not(feature = "rand"))]
294            return Err(DefaultStateError::RandomsDisabled);
295            #[cfg(feature = "rand")]
296            self.randoms
297                .as_mut()
298                .ok_or(DefaultStateError::RandomsDisabled)?
299                .random_range(range.clone())
300        };
301
302        let (from, to) = range.into_inner();
303        self.actions.push(Action::RequestRandom {
304            from: SNumber::Float(from),
305            to: SNumber::Float(to),
306            received: SNumber::Float(received),
307        });
308        Ok(received)
309    }
310    fn write_output(&mut self, output_kind: crate::state::OutputKind, message: SValue) {
311        self.actions.push(Action::Output {
312            kind: output_kind,
313            message,
314        });
315    }
316
317    fn wait_for_secs(&mut self, secs: SNumber) -> Result<(), Self::Error> {
318        self.actions.push(Action::WaitFor { secs });
319        Ok(())
320    }
321
322    fn data_set_variable(&mut self, var_id: &Variable, value: SValue) -> Result<(), Self::Error> {
323        let store = self
324            .variables
325            .get_mut(var_id)
326            .ok_or_else(|| unknown_var(var_id))?;
327        *store = value;
328        self.initialized_data.insert(Either::Left(var_id.clone()));
329        Ok(())
330    }
331    fn data_read_variable(&mut self, var_id: &Variable) -> Result<&SValue, Self::Error> {
332        self.use_uninitialized_variable(var_id)?;
333        self.variables
334            .get(var_id)
335            .ok_or_else(|| unknown_var(var_id))
336    }
337    fn data_insert_at_list(
338        &mut self,
339        list_id: &List,
340        one_based_index: &SValue,
341        item: SValue,
342    ) -> Result<(), Self::Error> {
343        self.use_uninitialized_list(list_id)?;
344        self.list_mut(list_id)?
345            .insert_item_at(one_based_index, item, &mut ())
346            .map_err(|_err| DefaultStateError::ListFull {
347                id: list_id.clone(),
348            })?;
349        Ok(())
350    }
351    fn data_replace_list_at(
352        &mut self,
353        list_id: &List,
354        one_based_index: &SValue,
355        item: SValue,
356    ) -> Result<(), Self::Error> {
357        self.use_uninitialized_list(list_id)?;
358        self.list_mut(list_id)?
359            .replace_nth_item(one_based_index, item, &mut ());
360        Ok(())
361    }
362    fn data_append_to_list(&mut self, list_id: &List, item: SValue) -> Result<(), Self::Error> {
363        self.use_uninitialized_list(list_id)?;
364        self.list_mut(list_id)?
365            .append_item(item)
366            .map_err(|_err| DefaultStateError::ListFull {
367                id: list_id.clone(),
368            })?;
369        Ok(())
370    }
371    fn data_list_contains_item(
372        &mut self,
373        list_id: &List,
374        item: &SValue,
375    ) -> Result<bool, Self::Error> {
376        self.use_uninitialized_list(list_id)?;
377        Ok(self.list_mut(list_id)?.contains_item(item))
378    }
379    fn data_delete_of_list(
380        &mut self,
381        list_id: &List,
382        one_based_index: &SValue,
383    ) -> Result<(), Self::Error> {
384        self.use_uninitialized_list(list_id)?;
385        self.list_mut(list_id)?.delete_nth(one_based_index, &mut ());
386        Ok(())
387    }
388    fn data_delete_all_of_list(&mut self, list_id: &List) -> Result<(), Self::Error> {
389        self.initialized_data.insert(Either::Right(list_id.clone()));
390        self.list_mut(list_id)?.delete_all();
391        Ok(())
392    }
393    fn data_read_textual_list_repr(&mut self, list_id: &List) -> Result<SValue, Self::Error> {
394        self.use_uninitialized_list(list_id)?;
395        Ok(self.list(list_id)?.textual_representation().into())
396    }
397    fn data_item_num_of_list(&mut self, list_id: &List, item: &SValue) -> Result<i64, Self::Error> {
398        self.use_uninitialized_list(list_id)?;
399        Ok(self.list(list_id)?.first_index_of_item_in_list(item))
400    }
401    fn data_item_of_list(
402        &mut self,
403        list_id: &List,
404        one_based_index: &SValue,
405    ) -> Result<SValue, Self::Error> {
406        self.use_uninitialized_list(list_id)?;
407        Ok(self.list(list_id)?.nth_item(one_based_index, &mut ()))
408    }
409    fn data_length_of_list(&mut self, list_id: &List) -> Result<i64, Self::Error> {
410        self.use_uninitialized_list(list_id)?;
411        Ok(self.list(list_id)?.length())
412    }
413}
414
415fn unknown_var(var_id: &Variable) -> DefaultStateError {
416    DefaultStateError::VariableNotFound(var_id.clone())
417}
418
419fn unknown_list(list_id: &List) -> DefaultStateError {
420    DefaultStateError::ListNotFound(list_id.clone())
421}
422
423impl DefaultState {
424    #[allow(unused)]
425    fn list_mut(&mut self, list_id: &List) -> Result<&mut SList, DefaultStateError> {
426        self.lists
427            .get_mut(list_id)
428            .ok_or_else(|| unknown_list(list_id))
429    }
430    #[allow(unused)]
431    fn list(&mut self, list_id: &List) -> Result<&SList, DefaultStateError> {
432        self.lists.get(list_id).ok_or_else(|| unknown_list(list_id))
433    }
434}