ctb_formats_eite/
eite_state.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Execution state machine and environment state for EITE.
21
22use crate::anyhow::{Result, anyhow, ensure};
23use serde::Serialize;
24
25use crate::util::{
26    array::{print_arr, set_element, str_print_arr},
27    string::{
28        int_arr_from_str_printed_arr, str_join_esc_no_trailing,
29        str_split_escaped,
30    },
31};
32
33/// Environment / shared state.
34/// In JS this lived on the global object with many independent keys;
35/// here we consolidate into a struct.
36#[derive(Default, Serialize)]
37pub struct EiteState {
38    // Preferences / environment
39    pub debug_level: i32,
40    pub env_preferred_format: String,
41    pub env_char_encoding: String,
42    pub env_terminal_type: String,
43    pub env_language: String,
44    pub env_locale_config: String,
45    pub env_code_language: String,
46    pub env_resolution_w: i32,
47    pub env_resolution_h: i32,
48
49    // Execution-related state (present in original snippet but not yet used here)
50    pub document_exec_data: Vec<String>,
51    pub document_exec_symbol_index: Vec<String>,
52    pub document_exec_ptrs: Vec<String>,
53    pub document_exec_frames: Vec<String>,
54    pub document_exec_events: Vec<String>,
55    pub document_exec_logs: Vec<String>,
56    pub document_exec_settings: Vec<String>,
57
58    // Test counters
59    pub tests_passed: u32,
60    pub tests_failed: u32,
61    pub tests_total: u32,
62
63    // Import / export configuration
64    pub import_settings: Vec<String>,
65    pub export_settings: Vec<String>,
66    pub import_deferred_settings_stack: Vec<String>,
67    pub export_deferred_settings_stack: Vec<String>,
68
69    // Storage config
70    pub storage_cfg: Vec<String>,
71}
72
73impl EiteState {
74    pub fn new() -> Self {
75        Self {
76            debug_level: 0,
77            env_preferred_format: String::new(),
78            env_char_encoding: "asciiSafeSubset".into(),
79            env_terminal_type: "vt100".into(),
80            env_language: "en-US".into(),
81            env_locale_config: "inherit:usa,".into(),
82            env_code_language: "javascript".into(),
83            env_resolution_w: 0,
84            env_resolution_h: 0,
85            ..Default::default()
86        }
87    }
88
89    /* -------------------- Document Exec State Management ---------------------- */
90    /// Prepare a new document execution context. Returns exec ID.
91    pub fn prepare_document_exec(&mut self, contents: &[u32]) -> usize {
92        let exec_id = self.document_exec_ptrs.len();
93        self.document_exec_data.push(str_print_arr(contents));
94        self.document_exec_symbol_index.push(String::new());
95        // Pointer stack stored as escaped join; initial current pointer = 0 (trailing comma).
96        self.document_exec_ptrs.push("0,".to_string());
97        self.document_exec_frames.push(String::new());
98        self.document_exec_events.push(String::new());
99        self.document_exec_logs.push(String::new());
100        self.document_exec_settings.push(",".to_string()); // empty kv join
101        exec_id
102    }
103
104    pub fn is_exec_id(&self, exec_id: usize) -> bool {
105        exec_id < self.document_exec_ptrs.len()
106    }
107
108    /// NOTE: Minimal kv split: split on ',' dropping empty trailing segments.
109    pub fn get_exec_settings(&self, exec_id: usize) -> Result<Vec<String>> {
110        if !self.is_exec_id(exec_id) {
111            return Err(anyhow!("Exec id out of range"));
112        }
113        let settings = self
114            .document_exec_settings
115            .get(exec_id)
116            .ok_or_else(|| anyhow!("Exec id not found"))?;
117        Ok(settings
118            .split(',')
119            .filter(|s| !s.is_empty())
120            .map(std::string::ToString::to_string)
121            .collect())
122    }
123
124    /// Replace full settings (joined with trailing comma for symmetry with original usage).
125    pub fn set_exec_settings(
126        &mut self,
127        exec_id: usize,
128        kv: &[String],
129    ) -> Result<()> {
130        if !self.is_exec_id(exec_id) {
131            return Err(anyhow!("Exec id out of range"));
132        }
133        let mut joined = String::new();
134        for k in kv {
135            joined.push_str(k);
136            joined.push(',');
137        }
138        if let Some(item) = self.document_exec_settings.get_mut(exec_id) {
139            *item = joined;
140        }
141        Ok(())
142    }
143
144    pub fn get_exec_ptrs(&self, exec_id: usize) -> Result<Vec<String>> {
145        if !self.is_exec_id(exec_id) {
146            return Err(anyhow!("Exec id out of range"));
147        }
148        let ptr_str = self
149            .document_exec_ptrs
150            .get(exec_id)
151            .ok_or_else(|| anyhow!("Exec id out of range"))?;
152        Ok(str_split_escaped(ptr_str, ","))
153    }
154
155    pub fn set_exec_ptrs(
156        &mut self,
157        exec_id: usize,
158        ptrs: &[String],
159    ) -> Result<()> {
160        if !self.is_exec_id(exec_id) {
161            return Err(anyhow!("Exec id out of range"));
162        }
163        if let Some(item) = self.document_exec_ptrs.get_mut(exec_id) {
164            *item = str_join_esc_no_trailing(ptrs, ",");
165        }
166        Ok(())
167    }
168
169    fn parse_ptr(val: &str) -> u32 {
170        if val.is_empty() {
171            0
172        } else {
173            // Reason for fallback: when pointer string val is unparseable as u32, 0 serves as standard state machine default for uninitialized pointer position.
174            val.parse::<u32>().unwrap_or(0)
175        }
176    }
177
178    pub fn get_current_exec_ptr_pos(&self, exec_id: usize) -> Result<u32> {
179        let ptrs = self.get_exec_ptrs(exec_id)?;
180        if let Some(last) = ptrs.last() {
181            Ok(Self::parse_ptr(last))
182        } else {
183            Ok(0)
184        }
185    }
186
187    pub fn set_exec_ptr_pos(
188        &mut self,
189        exec_id: usize,
190        new_pos: u32,
191    ) -> Result<()> {
192        let mut ptrs = self.get_exec_ptrs(exec_id)?;
193        set_element(&mut ptrs, -1, new_pos.to_string())?;
194        self.set_exec_ptrs(exec_id, &ptrs)?;
195        Ok(())
196    }
197
198    pub fn incr_exec_ptr_pos(&mut self, exec_id: usize) -> Result<()> {
199        let cur = self.get_current_exec_ptr_pos(exec_id)?;
200        self.set_exec_ptr_pos(exec_id, cur.saturating_add(1))
201    }
202
203    pub fn get_next_level_exec_ptr_pos(&self, exec_id: usize) -> Result<u32> {
204        let ptrs = self.get_exec_ptrs(exec_id)?;
205        if let Some(val) =
206            ptrs.len().checked_sub(2).and_then(|idx| ptrs.get(idx))
207        {
208            Ok(Self::parse_ptr(val))
209        } else {
210            Ok(0)
211        }
212    }
213
214    pub fn get_current_exec_data(&self, exec_id: usize) -> Result<Vec<u32>> {
215        if !self.is_exec_id(exec_id) {
216            return Err(anyhow!("Exec id out of range"));
217        }
218        let data_str = self
219            .document_exec_data
220            .get(exec_id)
221            .ok_or_else(|| anyhow!("Exec id out of range"))?;
222        int_arr_from_str_printed_arr(data_str)
223    }
224
225    pub fn get_current_exec_frame(&self, exec_id: usize) -> Result<Vec<u32>> {
226        if !self.is_exec_id(exec_id) {
227            return Err(anyhow!("Exec id out of range"));
228        }
229        let frames_str = self
230            .document_exec_frames
231            .get(exec_id)
232            .ok_or_else(|| anyhow!("Exec id out of range"))?;
233        int_arr_from_str_printed_arr(frames_str)
234    }
235
236    /// Retrieve a single exec option (key -> value) from settings KV.
237    pub fn get_exec_option(
238        &self,
239        exec_id: usize,
240        key: &str,
241    ) -> Result<Option<String>> {
242        let kv = self.get_exec_settings(exec_id)?;
243        for pair in kv {
244            if let Some((k, v)) = pair.split_once('=') {
245                if k == key {
246                    return Ok(Some(v.to_string()));
247                }
248            }
249        }
250        Ok(None)
251    }
252
253    /// Set (or insert) an exec option key=value pair.
254    pub fn set_exec_option(
255        &mut self,
256        exec_id: usize,
257        key: &str,
258        val: &str,
259    ) -> Result<()> {
260        let mut kv = self.get_exec_settings(exec_id)?;
261        let mut found = false;
262        for item in &mut kv {
263            if let Some((k, _)) = item.split_once('=') {
264                if k == key {
265                    *item = format!("{key}={val}");
266                    found = true;
267                    break;
268                }
269            }
270        }
271        if !found {
272            kv.push(format!("{key}={val}"));
273        }
274        self.set_exec_settings(exec_id, &kv)
275    }
276
277    /// Overwrite current frame output.
278    pub fn set_exec_frame(
279        &mut self,
280        exec_id: usize,
281        frame: &[u32],
282    ) -> Result<()> {
283        ensure!(self.is_exec_id(exec_id), "Invalid exec id {exec_id}");
284        if exec_id >= self.document_exec_frames.len() {
285            self.document_exec_frames
286                .resize(exec_id.saturating_add(1), String::new());
287        }
288        if let Some(item) = self.document_exec_frames.get_mut(exec_id) {
289            *item = print_arr(frame);
290        }
291        Ok(())
292    }
293
294    pub fn get_env_preferred_format(&self) -> &str {
295        if self.env_preferred_format.is_empty() {
296            "utf8"
297        } else {
298            &self.env_preferred_format
299        }
300    }
301}