ctb_runtime/
cli.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//! CLI argument parsing and execution dispatch for `ctoolbox run`.
21//!
22//! Compiles and executes an arbitrary Document Character (`Dc`) document or
23//! StageL 3 / StageR 3 / WAT / `.WASM` program through the `Dc 1936` execution
24//! kernel (`[Dc 1938 <pin> [Dc 2608 <quoted_doc>]]`), and renders the evaluated
25//! semantic `DcMstring` output via `ctb-renderer` (`RenderTarget::Teletype`
26//! plain-text UTF-8 lowering by default).
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use std::path::{Path, PathBuf};
36
37use ctb_formats_conversion::convert_api::{
38    DcConversionOptions, FormatSpec, SupportedDcInputFormat,
39    convert_bytes_to_dcmstring,
40};
41use ctb_formats_conversion::convert_bytes::format_supported_input_formats_table;
42use ctb_formats_dcstring::{
43    DcChar, DcMstr, DcMstring, SeedGraphIndex, SyntaxRuleResolver,
44};
45use ctb_formats_utilities::{CliInputSourceArgs, CliOutputDestArgs};
46use ctb_renderer::{
47    RenderMode, RenderSettings, RenderTarget, render_dc_document_with_resolver,
48};
49use ctb_utilities::FormatId;
50
51use crate::{ExecutionContext, SystemSupervisorAdmission};
52
53/// Global static lazy help footer for `ctoolbox run`.
54pub static RUN_AFTER_HELP: std::sync::LazyLock<String> =
55    std::sync::LazyLock::new(|| {
56        let in_formats = format_supported_input_formats_table(
57            "Supported document input formats (--from):",
58        );
59        format!(
60            "{in_formats}\n\nAdditional executable source formats (--from or by extension):\n  sr3 (f657, .sr3): StageR 3 module\n  sl3 (f656, .sl3): StageL 3 module\n  elad (f17, .elad, .emd): EITE Language in ASCII documents\n  ems (f914, .ems, .elq): EMS short-Dc sequence\n  dems (f915, .dems, .delq): Documented EMS short-Dc sequence\n  wat (.wat): WebAssembly Text Format\n\nExamples:\n  $ ctoolbox run -f hello-world.emd\n  $ ctoolbox run -f idiomatic-hello-world.ems\n  $ ctoolbox run --from dcsh \"256 258 260 262 264 263 57 86 93 93 96 261 259\"\n  $ ctoolbox run -f prog.sr3 --program-input \"world\""
61        )
62    });
63
64/// CLI rendering target selector for `ctoolbox run`.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
66pub enum RunTarget {
67    /// Character-based plain-text UTF-8 output (`RenderTarget::Teletype`).
68    #[default]
69    #[value(name = "teletype")]
70    Teletype,
71    /// Video terminal with cursor control and escape sequences (not yet implemented).
72    #[value(name = "videoterminal")]
73    Videoterminal,
74    /// Web-based HTML/CSS/JS output (not yet implemented).
75    #[value(name = "web")]
76    Web,
77    /// Raster bitmap graphics output (not yet implemented).
78    #[value(name = "raster")]
79    Raster,
80    /// Vector graphics output (not yet implemented).
81    #[value(name = "vector")]
82    Vector,
83    /// Print-ready output (not yet implemented).
84    #[value(name = "print")]
85    Print,
86}
87
88impl From<RunTarget> for RenderTarget {
89    fn from(value: RunTarget) -> Self {
90        match value {
91            RunTarget::Teletype => Self::Teletype,
92            RunTarget::Videoterminal => Self::Videoterminal,
93            RunTarget::Web => Self::Web,
94            RunTarget::Raster => Self::Raster,
95            RunTarget::Vector => Self::Vector,
96            RunTarget::Print => Self::Print,
97        }
98    }
99}
100
101/// Parsed `--from` specification for `ctoolbox run`.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum RunInputFormat {
104    /// Registered `FormatId` (`SupportedDcInputFormat`, `StageR3`, `StageL3`, `Elad`, `Ems`, `Dems`, etc.).
105    Format(FormatId),
106    /// WebAssembly Text Format (`.wat`).
107    Wat,
108}
109
110/// Parses a CLI `--from` flag into [`RunInputFormat`].
111///
112/// # Errors
113/// Returns a human-readable format table string if `raw` is unknown.
114pub fn parse_run_input_format(
115    raw: &str,
116) -> std::result::Result<RunInputFormat, String> {
117    let trimmed = raw.trim();
118    if trimmed.eq_ignore_ascii_case("wat") {
119        return Ok(RunInputFormat::Wat);
120    }
121    if let Ok(supported) = trimmed.parse::<SupportedDcInputFormat>() {
122        return Ok(RunInputFormat::Format(supported.to_format_id()));
123    }
124    if let Some(fid) = FormatId::from_shorthand(trimmed)
125        .or_else(|| FormatId::from_ident(trimmed))
126    {
127        return Ok(RunInputFormat::Format(fid));
128    }
129    Err(format_supported_input_formats_table(&format!(
130        "Invalid input format '{raw}'. Specify --from with sr3, sl3, elad, ems, dems, wat, or one of:"
131    )))
132}
133
134/// CLI arguments for `ctoolbox run`.
135#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
136pub struct RunArgs {
137    /// Document source text. If omitted, reads from `--file` or standard input.
138    pub input: Option<String>,
139
140    /// Input format (autodetected if omitted; accepts nickname, `FormatId` name, or `f<N>` shorthand)
141    #[arg(long = "from", value_parser = parse_run_input_format)]
142    pub from: Option<RunInputFormat>,
143
144    /// Parse input document in permissive mode (recovering from non-fatal format warnings)
145    #[arg(long = "permissive")]
146    pub permissive: bool,
147
148    /// Parse input document in strict mode
149    #[arg(long = "strict", conflicts_with = "permissive")]
150    pub strict: bool,
151
152    /// Input document file path (or `-` for stdin)
153    #[arg(short = 'f', long = "file")]
154    pub file: Option<PathBuf>,
155
156    /// Output file path (or `-` for stdout)
157    #[arg(short = 'o', long = "output")]
158    pub output: Option<PathBuf>,
159
160    /// Overwrite existing output file without prompt
161    #[arg(short = 'F', long = "force")]
162    pub force: bool,
163
164    /// Optional UTF-8 payload passed to the executed program's input mailbox
165    #[arg(long = "program-input")]
166    pub program_input: Option<String>,
167
168    /// Optional file path containing raw input bytes for the executed program's input mailbox
169    #[arg(long = "program-input-file", conflicts_with = "program_input")]
170    pub program_input_file: Option<PathBuf>,
171
172    /// Rendering target (`teletype` plain-text UTF-8 output by default)
173    #[arg(long = "target", value_enum, default_value_t = RunTarget::Teletype)]
174    pub target: RunTarget,
175}
176
177impl RunArgs {
178    /// Adapts input positional/file fields into [`CliInputSourceArgs`].
179    #[must_use]
180    pub fn input_source(&self) -> CliInputSourceArgs {
181        CliInputSourceArgs {
182            input: self.input.clone(),
183            file: self.file.clone(),
184        }
185    }
186
187    /// Adapts output destination fields into [`CliOutputDestArgs`].
188    #[must_use]
189    pub fn output_dest(&self) -> CliOutputDestArgs {
190        CliOutputDestArgs {
191            output: self.output.clone(),
192            force: self.force,
193        }
194    }
195}
196
197fn load_executable_dc_document(
198    bytes: &[u8],
199    filename_hint: Option<&str>,
200    from: Option<RunInputFormat>,
201    permissive: bool,
202) -> Result<DcMstring> {
203    let ext_lower = filename_hint
204        .and_then(|name| Path::new(name).extension())
205        .and_then(|e| e.to_str())
206        .map(str::to_ascii_lowercase);
207
208    let resolved = if let Some(explicit) = from {
209        Some(explicit)
210    } else if ext_lower.as_deref() == Some("wat") {
211        Some(RunInputFormat::Wat)
212    } else {
213        ctb_formats_detection::detect_format_id(Some(bytes), filename_hint, None)
214            .map(RunInputFormat::Format)
215    };
216
217    match resolved {
218        Some(RunInputFormat::Wat) => {
219            let src = std::str::from_utf8(bytes)
220                .context("WAT input is not valid UTF-8")?;
221            ctb_formats_dcstring::wat_to_dcmstring(src)
222        }
223        Some(RunInputFormat::Format(FormatId::StageR3)) => {
224            let src = std::str::from_utf8(bytes)
225                .context("StageR 3 (.sr3) input is not valid UTF-8")?;
226            let sg = SeedGraphIndex::shared()?;
227            let tokens = ctb_formats_dcstring::stagel3::seed_linker::sr3_to_dc_tokens_with_seed_graph(
228                src, sg,
229            )?;
230            let mut doc = DcMstring::new();
231            for tok in tokens {
232                doc.push_char(tok);
233            }
234            Ok(doc)
235        }
236        Some(RunInputFormat::Format(FormatId::StageL3)) => {
237            let src = std::str::from_utf8(bytes)
238                .context("StageL 3 (.sl3) input is not valid UTF-8")?;
239            let sg = SeedGraphIndex::shared()?;
240            let tokens = ctb_formats_dcstring::stagel3::seed_linker::sl3_to_dc_tokens_with_seed_graph(
241                src, sg,
242            )?;
243            let mut doc = DcMstring::new();
244            for tok in tokens {
245                doc.push_char(tok);
246            }
247            Ok(doc)
248        }
249        Some(RunInputFormat::Format(FormatId::Elad)) => {
250            let (doc, log) =
251                ctb_formats_dcstring::eite::elad_to_dcmstring_with_options(
252                    bytes, permissive,
253                )?;
254            emit_format_log(&log);
255            Ok(doc)
256        }
257        Some(RunInputFormat::Format(FormatId::Ems | FormatId::Dems)) => {
258            let (doc, log) =
259                ctb_formats_dcstring::eite::sems_to_dcmstring_with_options(
260                    bytes, true,
261                )?;
262            emit_format_log(&log);
263            Ok(doc)
264        }
265        Some(RunInputFormat::Format(fid)) => {
266            let options = DcConversionOptions {
267                format: if fid == FormatId::Text {
268                    FormatSpec::Format(SupportedDcInputFormat::Utf8)
269                } else {
270                    FormatSpec::FormatId(fid)
271                },
272                allow_binary_encapsulation: false,
273                permissive,
274            };
275            let res =
276                convert_bytes_to_dcmstring(bytes, filename_hint, &options)?;
277            emit_format_log(&res.log);
278            Ok(res.document)
279        }
280        None => {
281            let options = DcConversionOptions {
282                format: FormatSpec::Auto,
283                allow_binary_encapsulation: false,
284                permissive,
285            };
286            let res =
287                convert_bytes_to_dcmstring(bytes, filename_hint, &options)?;
288            emit_format_log(&res.log);
289            Ok(res.document)
290        }
291    }
292}
293
294fn emit_format_log(log: &ctb_formats_utilities::FormatLog) {
295    log.auto_log();
296    if log.has_errors() {
297        eprintln!("{}", log.format_errors().trim_end());
298    }
299    if log.has_warnings() {
300        eprintln!("{}", log.format_warnings().trim_end());
301    }
302}
303
304/// Executes an already-loaded [`DcMstr`] document through the `Dc 1936` execution
305/// kernel and renders its combined yielded frames and completion output with
306/// `settings`.
307///
308/// # Errors
309/// Returns an error if compilation, execution, resource limits, or rendering fail.
310pub fn run_dc_document_to_rendered_bytes(
311    ordinary_doc: &DcMstr,
312    program_input: &DcMstr,
313    settings: &RenderSettings,
314) -> Result<Vec<u8>> {
315    ctb_wasm_substitutes::ensure_registered();
316    let default_resolver =
317        ctb_formats_dcstring::syntax::default_syntax_resolver();
318    let adm = SystemSupervisorAdmission::admit_cli_execution_kernel()?;
319    let mut ctx = ExecutionContext::new(false)
320        .with_system_supervisor_admission(adm);
321    let trace = ctx.execute_dc_document_default_with_trace(
322        ordinary_doc,
323        program_input,
324        default_resolver.as_ref(),
325    )?;
326    ensure!(
327        !trace.result.broke_out_early,
328        "Dc document execution terminated early due to resource or permission denial: {:?}",
329        trace.events
330    );
331
332    let mut combined_output = DcMstring::new();
333    for frame in &trace.result.frames {
334        for chunk in frame.chunks() {
335            combined_output.push_chunk(&chunk)?;
336        }
337    }
338    for chunk in trace.result.output.chunks() {
339        combined_output.push_chunk(&chunk)?;
340    }
341
342    let opt_pin = SystemSupervisorAdmission::scan_first_pin_description(
343        ordinary_doc,
344        default_resolver.as_ref(),
345    )?;
346    let pinned_holder = if let Some((_, pin_id)) = opt_pin {
347        Some(ctb_formats_dcstring::syntax::syntax_resolver_at_most_recent(
348            pin_id,
349        )?)
350    } else {
351        None
352    };
353    let render_resolver: &dyn SyntaxRuleResolver =
354        if let Some(ref pinned) = pinned_holder {
355            pinned.as_ref()
356        } else {
357            default_resolver.as_ref()
358        };
359
360    render_dc_document_with_resolver(&combined_output, settings, render_resolver)
361}
362
363/// Executes the `ctoolbox run` CLI subcommand.
364///
365/// Returns `Ok(Some(bytes))` when output should be written to stdout, or
366/// `Ok(None)` when output was written directly to `-o`/`--output`.
367///
368/// # Errors
369/// Returns an error if reading inputs, parsing the document, executing via
370/// `Dc 1936`, rendering, or writing output fails.
371pub fn execute_cli_run<FRead>(
372    args: RunArgs,
373    read_data: FRead,
374) -> Result<Option<Vec<u8>>>
375where
376    FRead: Fn(&Path) -> Result<Vec<u8>>,
377{
378    let input_bytes = args.input_source().read_bytes(&read_data)?;
379    let filename_hint = args.file.as_deref().and_then(|p| {
380        if p == Path::new("-") {
381            None
382        } else {
383            p.file_name().and_then(|n| n.to_str())
384        }
385    });
386    let permissive = args.permissive && !args.strict;
387    let ordinary_doc = load_executable_dc_document(
388        &input_bytes,
389        filename_hint,
390        args.from,
391        permissive,
392    )?;
393
394    let mut program_input_doc = DcMstring::new();
395    if let Some(ref prog_in_str) = args.program_input {
396        for ch in prog_in_str.chars() {
397            program_input_doc.push_char(DcChar::from(ch));
398        }
399    } else if let Some(ref prog_in_path) = args.program_input_file {
400        let raw_in = read_data(prog_in_path)?;
401        let (parsed_in, _) =
402            ctb_formats_dcstring::utf8::utf8_to_dcmstring_with_options(
403                &raw_in, true,
404            )?;
405        program_input_doc = parsed_in;
406    }
407
408    let render_settings = RenderSettings {
409        mode: RenderMode::Immediate,
410        target: RenderTarget::from(args.target),
411    };
412    let rendered = run_dc_document_to_rendered_bytes(
413        &ordinary_doc,
414        &program_input_doc,
415        &render_settings,
416    )?;
417    args.output_dest().write_or_stdout(rendered)
418}
419
420#[cfg(test)]
421#[allow(
422    clippy::panic,
423    clippy::expect_used,
424    clippy::unwrap_used,
425    clippy::unwrap_in_result,
426    clippy::panic_in_result_fn,
427    clippy::indexing_slicing,
428    clippy::arithmetic_side_effects,
429    reason = "Standard repository test boilerplate"
430)]
431mod tests {
432    use super::*;
433
434    fn workspace_fixture_path(rel: &str) -> PathBuf {
435        Path::new(env!("CARGO_MANIFEST_DIR"))
436            .join("../..")
437            .join(rel)
438    }
439
440    #[crate::ctb_test]
441    fn runs_hello_world_emd_and_ems_fixtures_to_teletype_utf8() -> Result<()> {
442        let emd_path = workspace_fixture_path(
443            "src/formats/dct_el/fixtures/examples/example-documents/hello-world/hello-world.emd",
444        );
445        let out_emd = execute_cli_run(
446            RunArgs {
447                file: Some(emd_path),
448                ..Default::default()
449            },
450            |p| Ok(std::fs::read(p)?),
451        )?
452        .unwrap();
453        assert_eq!(String::from_utf8(out_emd)?, "Hello, World!\n");
454
455        let idiom_emd_path = workspace_fixture_path(
456            "src/formats/dct_el/fixtures/examples/example-documents/hello-world/idiomatic-hello-world.emd",
457        );
458        let out_idiom_emd = execute_cli_run(
459            RunArgs {
460                file: Some(idiom_emd_path),
461                ..Default::default()
462            },
463            |p| Ok(std::fs::read(p)?),
464        )?
465        .unwrap();
466        assert_eq!(String::from_utf8(out_idiom_emd)?, "Hello, World!\n\n");
467
468        let idiom_ems_path = workspace_fixture_path(
469            "src/formats/dct_el/fixtures/examples/example-documents/hello-world/idiomatic-hello-world.ems",
470        );
471        let out_idiom_ems = execute_cli_run(
472            RunArgs {
473                file: Some(idiom_ems_path),
474                ..Default::default()
475            },
476            |p| Ok(std::fs::read(p)?),
477        )?
478        .unwrap();
479        assert_eq!(String::from_utf8(out_idiom_ems)?, "Hello, World!\n");
480        Ok(())
481    }
482
483    #[crate::ctb_test]
484    fn runs_lexical_scope_assignment_and_equiv_rep_dc_document() -> Result<()> {
485        // Document:
486        // [greeting] = "Outer"
487        // 541 (Enter scope)
488        //   [greeting] = 397 [list * "Inner", 6 f199 128 7]
489        //   256 (lang.say) 258 (540 [greeting]) 259
490        // 542 (Exit scope)
491        // 256 (lang.say) 258 (540 [greeting]) 259
492        let dcsh = concat!(
493            "235 ",
494            "270 u67 u72 u65 u65 u74 271 269 260 262 264 263 u4f u75 u74 u65 u72 261 ",
495            "541 ",
496            "270 u67 u72 u65 u65 u74 271 269 397 310 275 260 262 264 263 u49 u6e u6e u65 u72 261 312 6 f199 128 7 311 ",
497            "256 258 540 270 u67 u72 u65 u65 u74 271 259 ",
498            "542 ",
499            "256 258 540 270 u67 u72 u65 u65 u74 271 259 ",
500            "2239 u4f u4b u0a ",
501            "236"
502        );
503        let out = execute_cli_run(
504            RunArgs {
505                input: Some(dcsh.to_string()),
506                from: Some(RunInputFormat::Format(FormatId::Dcsh)),
507                ..Default::default()
508            },
509            |_| Ok(Vec::new()),
510        )?
511        .unwrap();
512        assert_eq!(String::from_utf8(out)?, "Inner\nOuter\nOK\n");
513        Ok(())
514    }
515
516    #[crate::ctb_test]
517    fn runs_historical_dc_641_pinned_lang_say_document() -> Result<()> {
518        // Historical pin l8589958834 (predates StageR 3 Dc 2608 and f19) + Dc 235 .. Dc 256 .. Dc 236
519        // using short Dcs for "Hi!" (57, 90, 19) + Dc 255 escape test.
520        let dcsh = concat!(
521            "641 l8589958834 ",
522            "235 ",
523            "256 258 260 262 264 263 57 90 19 261 259 ",
524            "255 u4f u4b u0a ",
525            "236"
526        );
527        let out = execute_cli_run(
528            RunArgs {
529                input: Some(dcsh.to_string()),
530                from: Some(RunInputFormat::Format(FormatId::Dcsh)),
531                ..Default::default()
532            },
533            |_| Ok(Vec::new()),
534        )?
535        .unwrap();
536        assert_eq!(String::from_utf8(out)?, "Hi!\nOK\n");
537        Ok(())
538    }
539
540    #[crate::ctb_test]
541    fn runs_stager3_and_stagel3_programs_with_program_input() -> Result<()> {
542        let sr3_src = concat!(
543            "ns app/cli_hello.\n",
544            "pub v/l/u8/step l/u8/input\n",
545            "    concat concat b\"Hello, \" /input b\"!/n\".\n",
546        );
547        let out_sr3 = execute_cli_run(
548            RunArgs {
549                input: Some(sr3_src.to_string()),
550                from: Some(RunInputFormat::Format(FormatId::StageR3)),
551                program_input: Some("CLI".to_string()),
552                ..Default::default()
553            },
554            |_| Ok(Vec::new()),
555        )?
556        .unwrap();
557        assert_eq!(String::from_utf8(out_sr3)?, "Hello, CLI!\n");
558
559        let sl3_src =
560            "v/l/u8/step l/u8/input :: concat b\"sl3:\" concat /input b\"/n\".\n";
561        let out_sl3 = execute_cli_run(
562            RunArgs {
563                input: Some(sl3_src.to_string()),
564                from: Some(RunInputFormat::Format(FormatId::StageL3)),
565                program_input: Some("ok".to_string()),
566                ..Default::default()
567            },
568            |_| Ok(Vec::new()),
569        )?
570        .unwrap();
571        assert_eq!(String::from_utf8(out_sl3)?, "sl3:ok\n");
572        Ok(())
573    }
574
575    #[crate::ctb_test]
576    fn rejects_unimplemented_videoterminal_target() {
577        let err = execute_cli_run(
578            RunArgs {
579                input: Some("Hello".to_string()),
580                from: Some(RunInputFormat::Format(FormatId::Utf8)),
581                target: RunTarget::Videoterminal,
582                ..Default::default()
583            },
584            |_| Ok(Vec::new()),
585        )
586        .unwrap_err();
587        assert!(err.to_string().contains("Videoterminal"));
588    }
589}