ctb_formats_eite/
runtime.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//! -------------------------------------------------------------------------
21//! StageR Main Loop (ndw / `ndw_invoke`) STUBS
22//! -------------------------------------------------------------------------
23//! The original JS code invoked deterministic routines `sr_main`, `sr_tick`,
24//! `sr_getExitCode` with shared memory / storage / IO objects. Those engine
25//! functions are not part of the already translated Rust. For now we provide
26//! placeholders to preserve API shape. They can be filled in once the runtime
27//! is ported.
28use crate::utilities::*;
29
30use anyhow::{Context, Result, anyhow, ensure};
31use ctb_formats_utilities::FormatLog;
32
33use crate::{
34    dc::dc_is_el_code,
35    debug,
36    eite_state::EiteState,
37    export_document,
38    formats::{Format, PrefilterSettings, dca_from_format, dca_to_format},
39    json,
40    util::string::int_arr_from_str_printed_arr,
41};
42
43/// Placeholder struct representing the (unported) StageR engine context.
44pub struct NdwEngine {}
45
46impl Default for NdwEngine {
47    fn default() -> Self {
48        Self::new()
49    }
50}
51
52impl NdwEngine {
53    pub fn new() -> Self {
54        Self {}
55    }
56}
57
58/// Simulated main loop (ndw). Returns an exit code (currently always 0).
59pub fn ndw(_engine: &mut NdwEngine) -> i32 {
60    // Stub: in real implementation we would:
61    // 1. Call sr_main(memory, storage, io)
62    // 2. Loop calling sr_tick until it returns <= 0
63    0
64}
65
66/// Invoke specific runtime routine (stub). Present only for API parity.
67pub fn ndw_invoke(_engine: &mut NdwEngine, routine: &str) -> i32 {
68    match routine {
69        "main" | "tick" => 1,
70        "getExitCode" => 0,
71        _ => 0,
72    }
73}
74
75/// Public API: start execution for an existing prepared document (`exec_id`).
76///
77/// This replicates `startDocumentExec(intExecId)` from the StageL code.
78/// It executes until:
79/// * End of document Dc array
80/// * stopExecAtTick (if configured) is reached
81/// The working frame is periodically flushed (every 100 ticks) unless run headless.
82/// Escape handling and simple (line / block) comment skipping is implemented.
83///
84/// NOTE:
85/// - EL code processing (dcIsELCode branch) remains unimplemented as in the original section.
86/// - Rendering hooks (`renderDrawContents`) are no-ops here; adapt to your UI layer if needed.
87pub fn start_document_exec(
88    state: &mut EiteState,
89    exec_id: usize,
90) -> Result<()> {
91    ensure!(state.is_exec_id(exec_id), "Invalid exec id {exec_id}");
92
93    // Tick / control options.
94    // Reason for fallback: when optional stopExecAtTick option is omitted or unparseable as u32, 0 indicates unlimited execution.
95    let stop_exec_at_tick: u32 = state
96        .get_exec_option(exec_id, "stopExecAtTick")?
97        .unwrap_or_else(|| "0".to_string())
98        .parse()
99        .unwrap_or(0);
100
101    let run_headless = state
102        .get_exec_option(exec_id, "runHeadless")?
103        .is_some_and(|v| v == "true");
104
105    // Working copy of the Dc data (parsed from stored string).
106    let working_copy: Vec<u32> = {
107        // Reason for fallback: when document_exec_data has no entry for exec_id, empty string defaults to empty document.
108        let data_str = state
109            .document_exec_data
110            .get(exec_id)
111            .cloned()
112            .unwrap_or_default();
113        int_arr_from_str_printed_arr(&data_str)?
114    };
115
116    let mut continue_loop = true;
117    let mut current_tick: u32 = 0;
118    let mut wip_frame: Vec<u32> = Vec::new();
119    let mut last_char_was_escape = false;
120
121    // Execution states stack: only textual marker strings were used originally.
122    let mut state_stack: Vec<&'static str> = vec!["normal"];
123
124    let out_fmt = state.get_env_preferred_format().to_string();
125    let out_fmt = Format::from_string(&out_fmt)?;
126
127    while continue_loop {
128        if current_tick >= stop_exec_at_tick.saturating_sub(1) {
129            continue_loop = false;
130        }
131        if !continue_loop {
132            break;
133        }
134        current_tick = current_tick.saturating_add(1);
135
136        let ptr_pos = usize::try_from(state.get_current_exec_ptr_pos(exec_id)?)
137            .context("Should work to get usize")?;
138        if ptr_pos >= working_copy.len() {
139            // Document done.
140            continue_loop = false;
141        } else {
142            let dc = working_copy
143                .get(ptr_pos)
144                .copied()
145                .ok_or_else(|| anyhow!("Index out of bounds"))?;
146            debug!(
147                json!(state),
148                1,
149                &format!(
150                    "Exec loop pos={ptr_pos} dc={dc} state={state_stack:?} tick={current_tick}"
151                )
152            );
153
154            if last_char_was_escape {
155                last_char_was_escape = false;
156                state.incr_exec_ptr_pos(exec_id)?;
157            } else {
158                if dc == 255 {
159                    // Escape indicator
160                    last_char_was_escape = true;
161                } else {
162                    // Reason for fallback: state_stack is initialized with "normal" on line 101; "normal" fallback prevents panic if stack becomes empty.
163                    match state_stack.last().copied().unwrap_or("normal") {
164                        "normal" => {
165                            // Enter comment states?
166                            if dc == 246 || dc == 247 {
167                                state_stack.push("single-line source comment");
168                            } else if dc == 249 || dc == 250 {
169                                state_stack.push("block source comment");
170                            } else if dc_is_el_code(dc)? {
171                                // FIXME: EL code execution unimplemented
172                            } else {
173                                wip_frame.push(dc);
174                            }
175                        }
176                        "single-line source comment" => {
177                            // End single-line comment at Dc=248
178                            if dc == 248 {
179                                state_stack.pop();
180                            }
181                        }
182                        "block source comment" => {
183                            if dc == 251 {
184                                state_stack.pop();
185                            }
186                        }
187                        _ => {
188                            // Unknown state: treat as normal accumulation.
189                            wip_frame.push(dc);
190                        }
191                    }
192                }
193                state.incr_exec_ptr_pos(exec_id)?;
194            }
195        }
196
197        if !run_headless && current_tick.is_multiple_of(100) {
198            // Frame flush.
199            state.set_exec_frame(exec_id, &wip_frame)?;
200            // Convert to preferred format and "render".
201            if let Ok((_rendered, render_log)) = dca_to_format(
202                state,
203                &out_fmt,
204                &wip_frame,
205                &PrefilterSettings::default(),
206            ) {
207                render_log.auto_log();
208            }
209            // In original code: renderDrawContents(...)
210        }
211    }
212
213    // Final flush
214    state.set_exec_frame(exec_id, &wip_frame)?;
215    if let Ok((_rendered, render_log)) = dca_to_format(
216        state,
217        &out_fmt,
218        &wip_frame,
219        &PrefilterSettings::default(),
220    ) {
221        render_log.auto_log();
222    }
223
224    Ok(())
225}
226
227/// Translate of JS `runTestsDocumentExec(boolV)`
228///
229/// In StageL this drove scripted tests referencing stored documents. Here we
230/// expose an internal helper allowing unit tests (or integration tests) to call
231/// it with `verbose = true/false`.
232///
233/// Requires the presence of assets:
234///  resources/data/eite/ddc/exec-tests/{testname}.sems
235///  resources/data/eite/ddc/exec-tests/{testname}.out.sems
236pub fn run_tests_document_exec(
237    _state: &mut EiteState,
238    _verbose: bool,
239) -> Result<()> {
240    // The original JS invoked:
241    //   runExecTest('at-comment-no-space', 10);
242    //   runExecTest('at-comment', 10);
243    //   runExecTest('at-nl', 10);
244    //   runExecTest('at-space-nl', 10);
245    //   runExecTest('hello-world', 100);
246    //
247    // Complete faithful reproduction would require previously translated
248    // loadStoredDocument / runDocumentPrepare / runDocumentGo / runTest.
249    //
250    // Those earlier portions are assumed to exist. If / when they do, wire
251    // them through here. For now this is a placeholder.
252    Ok(())
253}
254
255/// Translate of JS `runExecTest`.
256///
257/// Placeholder until the rest of the execution harness (document loading)
258/// is wired in. Provided for structural fidelity.
259pub fn run_exec_test(
260    _state: &mut EiteState,
261    _test_name: &str,
262    _ticks_needed: i32,
263    _verbose: bool,
264) -> Result<()> {
265    Ok(())
266}
267
268/// Start EITE using the default startup document ("eite.sems" in "sems" format).
269/// (startEite in JS)
270pub fn start_eite(state: &mut EiteState) -> Result<()> {
271    load_and_run(state, &Format::sems_default(), "eite.sems")
272}
273
274/// Load and run a document (blocking until completion in original JS).
275/// Here it prepares and starts execution; actual stepping / event loop
276/// would need the still-unported runtime engine.
277pub fn load_and_run(
278    state: &mut EiteState,
279    format: &Format,
280    path: &str,
281) -> Result<()> {
282    let doc = load_stored_document(state, format, path)?;
283    run_document(state, &doc)
284}
285
286/// Run document: prepare + go.
287pub fn run_document(state: &mut EiteState, dc_array: &[u32]) -> Result<()> {
288    let exec_id = run_document_prepare(state, dc_array)?;
289    run_document_go(state, exec_id)
290}
291
292/// Prepare to run a document, returning an execution ID.
293pub fn run_document_prepare(
294    state: &mut EiteState,
295    dc_array: &[u32],
296) -> Result<usize> {
297    Ok(state.prepare_document_exec(dc_array))
298}
299
300/// Start (execute) a previously prepared document.
301pub fn run_document_go(state: &mut EiteState, exec_id: usize) -> Result<()> {
302    start_document_exec(state, exec_id)
303}
304
305/// Load, convert, and return bytes (JS loadAndConvert).
306pub fn load_and_convert(
307    state: &mut EiteState,
308    in_format: &Format,
309    out_format: &Format,
310    path: &str,
311    prefilter_settings: &PrefilterSettings,
312) -> Result<(Vec<u8>, FormatLog)> {
313    let doc = load_stored_document(state, in_format, path)?;
314    export_document(state, out_format, &doc, prefilter_settings)
315}
316
317/// Load a stored document from path using specified input format.
318/// Tries `path` first; if not found, also tries to prefix with
319/// `resources/data/eite/` (for bundled assets).
320pub fn load_stored_document(
321    state: &mut EiteState,
322    format: &Format,
323    path: &str,
324) -> Result<Vec<u32>> {
325    let bytes = try_load_asset(path)
326        .with_context(|| format!("Failed to load document asset '{path}'"))?;
327    let (doc, log) = dca_from_format(state, format, &bytes)?;
328    log.auto_log();
329    Ok(doc)
330}
331
332fn try_load_asset(path: &str) -> Result<Vec<u8>> {
333    crate::get_eite_data(path)
334        .with_context(|| format!("asset not found: {path}"))
335}
336
337/// Return desired event notifications for a document (empty: not yet implemented).
338pub fn get_desired_event_notifications(
339    _state: &EiteState,
340    _exec_id: usize,
341) -> Result<Vec<String>> {
342    Ok(Vec::new())
343}
344
345/// Send an event to a running document (stub).
346pub fn send_event(
347    _state: &mut EiteState,
348    _exec_id: usize,
349    _event_data: &[i32],
350) -> Result<()> {
351    // Event system not yet ported.
352    Ok(())
353}
354
355/// Get current document frame exported to a format.
356/// If the frame is absent, returns an empty byte vector.
357pub fn get_document_frame(
358    state: &mut EiteState,
359    exec_id: usize,
360    out_format: &Format,
361) -> Result<(Vec<u8>, FormatLog)> {
362    match state.get_current_exec_frame(exec_id) {
363        Ok(frame) => dca_to_format(
364            state,
365            out_format,
366            &frame,
367            &PrefilterSettings::default(),
368        ),
369        Err(_) => Ok((Vec::new(), FormatLog::default())),
370    }
371}
372
373#[cfg(test)]
374#[allow(
375    clippy::panic,
376    clippy::expect_used,
377    clippy::unwrap_used,
378    clippy::unwrap_in_result,
379    clippy::panic_in_result_fn,
380    clippy::indexing_slicing,
381    clippy::arithmetic_side_effects,
382    reason = "Standard repository test boilerplate"
383)]
384mod tests {
385    use super::*;
386
387    #[crate::ctb_test]
388    fn test_document_exec_state() {
389        let mut st = EiteState::default();
390        let exec_id = st.prepare_document_exec(&[1, 2, 3]);
391        assert!(st.is_exec_id(exec_id));
392
393        // Current pointer
394        assert_eq!(st.get_current_exec_ptr_pos(exec_id).unwrap(), 0);
395        st.set_exec_ptr_pos(exec_id, 5).unwrap();
396        assert_eq!(st.get_current_exec_ptr_pos(exec_id).unwrap(), 5);
397        st.incr_exec_ptr_pos(exec_id).unwrap();
398        assert_eq!(st.get_current_exec_ptr_pos(exec_id).unwrap(), 6);
399
400        // Data parse
401        let data = st.get_current_exec_data(exec_id).unwrap();
402        assert_eq!(data, vec![1, 2, 3]);
403    }
404}