Skip to main content

scratch_test_interpreter/
default_state.rs

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