ctb_formats_eite/eite.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//! Implementation of EITE formats (Rust translation – high‑level export / import wrappers).
21//!
22//! This module exposes a small public convenience surface for converting between
23//! “Dc array” document representations (`Vec<u32>`) and external serialized formats
24//! (bytes) plus a transformation hook. The heavy‑lifting implementations live in
25//! sub‑modules.
26//!
27//! As EITE did not have all intended elements fully implemented, this Rust
28//! version similarly has some limitations.
29//!
30//! Primary entry points provided here:
31//! - [`export_document`]: Dc array -> bytes in a named format.
32//! - [`import_document`]: Bytes in a named format -> Dc array.
33//! - [`import_and_export`]: Bytes in one format -> bytes in another (single convenience hop).
34//! - [`transform_document`]: Apply an in‑memory, pure Dc→Dc transformation.
35//!
36//! These are intentionally thin wrappers delegating to lower‑level functions so that
37//! callers have a stable, ergonomic API while internal modules evolve.
38//!
39//! # Errors
40//! All fallible operations return `anyhow::Result<_>`. Under the hood some modules
41//! may surface structured errors (e.g. an internal `EiteError` enum); those are
42//! converted into `anyhow::Error` at this boundary. Panics are avoided unless a
43//! genuine invariant violation occurs (logic error / programmer bug).
44//!
45//! # Concurrency
46//! The underlying state object (`EiteState`) is passed in mutably for import / export
47//! because format conversion may accumulate warnings, cache dataset lookups, or
48//! modify configuration state required for subsequent operations. Pure transformations
49//! only need an immutable reference (and could, if required later, be made fully
50//! independent of state when transformation semantics are guaranteed to be stateless).
51//!
52//! # Testing
53//! This file includes light “sanity” unit tests that verify:
54//! - Wrapper identity / invariants (e.g. `import_and_export` equivalence with a
55//! separate `import_document` + `export_document` sequence).
56//! - Transformation pass‑through for currently identity‑like transformations
57//! (`semanticToText`, `codeToText`).
58//! - Basic error expectations (unknown transformation).
59//!
60//! For deeper behavioral validation (round‑tripping every supported format,
61//! exhaustive edge cases, dataset driven conversions, escaping, etc.) see the
62//! dedicated tests housed alongside the lower‑level modules.
63//!
64//! # Performance
65//! These wrappers add effectively zero overhead beyond an extra function call.
66//! When profiling, attribute time spent within these wrappers to the delegated
67//! modules (`formats`, `encoding`, `transform`, etc.).
68//!
69//
70// --------------------------------------------------------------------------------
71// Transpilation & Follow‑up Notes
72// --------------------------------------------------------------------------------
73// Source provenance:
74// This file forms part of an incremental port of a legacy JavaScript/StageL
75// implementation of EITE to Rust.
76//
77// Translation policies applied globally across the port (including code not shown here):
78// - Type prefixes from the JS code (`intX`, `strY`, `boolZ`, `byteArr`, etc.) are removed;
79// Rust’s static typing guarantees the original invariants.
80// - Runtime assertion helpers (`assertInt`, `assertStr`, `assertIntArray`, etc.) are
81// eliminated; semantic validation is retained only where needed (e.g. validating
82// bit arrays or settings string shape).
83// - Trivial arithmetic / boolean wrappers (`Add`, `Sub`, `Mod`, `Eq`, `Gt`, `Lt`, `Not`,
84// `And`, `inc`, `dec`, etc.) are expressed directly with native operators.
85// - Logging / failure helpers (`Debug`, `Warn`, `Die`) are mapped to Rust tracing /
86// warning accumulation or error returns (TBD: finalize whether former `Die()`
87// sites should panic or return `Result::Err`; currently leaning toward `Result`).
88// - Environment detection (browser vs worker vs Node) is removed. Asset loading
89// is routed through a single abstraction.
90// - Base16b bridging delegates directly to `crate::formats::base16b::Base16b`.
91// - Column indices for Dc datasets (script / bidi class / type / name / combining
92// class / casing / complex traits / description) are preserved as symbolic
93// constants until a unified, possibly zero‑based indexing scheme is finalized.
94//
95// Remaining follow‑up actions
96// 1. Confirm dataset column indexing? (choose 0‑based internally? adapt loader
97// if original JS relied on 1‑based constants).
98// 2. Expand test coverage: every legacy JS test case mirrored in Rust, including
99// edge cases for settings parsing, Basenb, UTF‑8 variant conversions, HTML
100// fragment generation, and transformation pipelines.
101// 3. Consider refactoring legacy while‑loop “boolContinue” idioms into idiomatic
102// iterator chains once correctness is locked in (retain readable imperative
103// fallbacks in tricky hot paths).
104// 4. Reassess any placeholder heuristics (script / bidi / type lookups) once the
105// definitive dataset schema is confirmed.
106//
107// Architectural notes:
108// - Conversion pipeline: `import_document` parses bytes -> intermediate Dc array;
109// `export_document` serializes Dc array -> bytes. `import_and_export` short‑circuits
110// by combining these with a single intermediate vector (no additional data copies
111// beyond what the lower layers perform).
112// - Transformations: `transform_document` intentionally does not expose state mutation;
113// if future transformations require contextual settings or side‑effects, widen the
114// signature or introduce a transformation context object.
115// - Performance critical sections (e.g. pack/unpack bit manipulation, UTF‑8
116// conversions) are implemented in lower modules; this wrapper layer stays
117// allocation‑minimal.
118//
119// Testing / Verification strategy:
120// - Unit tests inside each functional sub‑module provide deterministic correctness.
121// - Integration tests (future) will orchestrate full import->transform->export cycles
122// across all supported formats ensuring round‑trip invariants and preservation of
123// semantic properties (printability, newline normalization, variant fidelity).
124
125#[allow(
126 unused_imports,
127 clippy::wildcard_imports,
128 reason = "Standard workspace crate prelude"
129)]
130pub(crate) use ctb_utilities::*;
131
132use ctb_formats_utilities::FormatLog;
133
134// Sub‑modules (actual implementations live there).
135use crate::{
136 eite_state::EiteState,
137 formats::{
138 Format, PrefilterSettings, convert_formats, dca_from_format,
139 dca_to_format,
140 utf8::{UTF8FormatSettings, dca_to_utf8},
141 },
142 transform::{DocumentTransformation, apply_document_transformation},
143};
144
145use anyhow::Result;
146
147use include_dir::{Dir, include_dir};
148
149pub mod dc;
150pub mod eite_state;
151pub mod encoding;
152pub mod exceptions;
153pub mod formats;
154pub mod kv;
155pub mod runtime;
156pub mod settings;
157pub mod terminal;
158pub mod transform;
159pub mod util;
160
161static DC_DATA_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/data");
162
163pub fn get_eite_data(key: &str) -> Option<Vec<u8>> {
164 get_embedded_asset(&DC_DATA_DIR, key)
165}
166
167/// Export a document (Dc array) into a named external format.
168///
169/// Thin wrapper over `formats::dca_to_format`.
170///
171/// Arguments:
172/// - `state`: Mutable Eite runtime state (collects warnings, caches, settings).
173/// - `out_format`: Target format identifier (case / spelling must match a registered format).
174/// - `dc_array`: The in‑memory Dc array representation (sequence of codepoint / symbol IDs).
175///
176/// Returns serialized bytes on success.
177///
178/// Errors:
179/// - Propagates any format‑specific encoding or validation errors.
180/// - Unknown `out_format` will typically surface as an `Err`.
181pub fn export_document(
182 state: &mut EiteState,
183 out_format: &Format,
184 dc_array: &[u32],
185 prefilter_settings: &PrefilterSettings,
186) -> Result<(Vec<u8>, FormatLog)> {
187 // No preconditions beyond those enforced by the lower layer.
188 dca_to_format(state, out_format, dc_array, prefilter_settings)
189}
190
191/// Import a document from a named external format into a Dc array.
192///
193/// Thin wrapper over `formats::dca_from_format`.
194///
195/// Arguments:
196/// - `state`: Mutable Eite runtime state.
197/// - `in_format`: Source format identifier.
198/// - `content_bytes`: Raw serialized payload.
199///
200/// Returns a newly allocated Dc array (`Vec<u32>`).
201///
202/// Errors:
203/// - Unknown or unsupported `in_format`.
204/// - Malformed content (syntax / structural violations per format rules).
205pub fn import_document(
206 state: &mut EiteState,
207 in_format: &Format,
208 content_bytes: &[u8],
209) -> Result<(Vec<u32>, FormatLog)> {
210 dca_from_format(state, in_format, content_bytes)
211}
212
213/// Convenience: import from one format and export to another in a single step.
214///
215/// Internally delegates to `formats::convert_formats` to allow any shared
216/// optimizations (e.g. streaming pipelines in the future).
217///
218/// Arguments:
219/// - `state`: Mutable runtime state.
220/// - `in_format`: Source format identifier.
221/// - `out_format`: Target format identifier.
222/// - `content_bytes`: Raw serialized input in `in_format`.
223///
224/// Returns serialized bytes in `out_format`.
225///
226/// Errors:
227/// - Any error from `import_document` or `export_document`.
228pub fn import_and_export(
229 state: &mut EiteState,
230 in_format: &Format,
231 out_format: &Format,
232 content_bytes: &[u8],
233 prefilter_settings: &PrefilterSettings,
234) -> Result<(Vec<u8>, FormatLog)> {
235 convert_formats(
236 state,
237 in_format,
238 out_format,
239 content_bytes,
240 prefilter_settings,
241 )
242}
243
244/// Apply an in‑memory document transformation (Dc array -> Dc array).
245///
246/// Delegates to `transform::apply_document_transformation`.
247///
248/// Arguments:
249/// - `_state`: (Reserved) not currently required by the known transformations; kept
250/// for forward compatibility if future transforms become stateful.
251/// - `dc_array`: Source Dc array.
252/// - `transformation`: Transformation identifier (e.g. "semanticToText").
253///
254/// Returns the transformed Dc array (new vector).
255///
256/// Errors:
257/// - Unknown transformation name.
258/// - Transformation specific errors (if any future transform is fallible).
259pub fn transform_document(
260 dc_array: &[u32],
261 transformation: &DocumentTransformation,
262) -> Result<Vec<u32>> {
263 apply_document_transformation(transformation, dc_array)
264}
265
266// Test helpers. Similar to the u32 ones in ctb_formats_utilities, but specialized for Dc arrays.
267fn _format_dcs_for_log(expected: &[u32], actual: &[u32]) -> String {
268 // Reason for fallback: formatting helper is used in assertion diagnostic logging where empty byte vector is safe fallback if expected formatting fails.
269 let (utf8_expected, _) =
270 dca_to_utf8(expected, &UTF8FormatSettings::default())
271 .unwrap_or_default();
272 // Reason for fallback: formatting helper is used in assertion diagnostic logging where empty byte vector is safe fallback if actual formatting fails.
273 let (utf8_actual, _) =
274 dca_to_utf8(actual, &UTF8FormatSettings::default()).unwrap_or_default();
275
276 format!(
277 "Expected formatted Dcs: {}\nActual formatted Dcs: {}",
278 String::from_utf8_lossy(&utf8_expected),
279 String::from_utf8_lossy(&utf8_actual)
280 )
281}
282
283#[expect(
284 clippy::unwrap_used,
285 reason = "Assertion helper function in format test utilities"
286)]
287fn _assert_vec_dc_ok_eq_log(
288 expected: &[u32],
289 actual: Result<(Vec<u32>, FormatLog)>,
290 disallow_warnings: bool,
291) -> (Vec<u32>, FormatLog) {
292 let (actual_vec, log) = actual.unwrap();
293
294 let mut log_problem_type = "Errors";
295 if disallow_warnings {
296 log_problem_type = "Warnings or errors";
297 }
298 let mut message =
299 format!("{log_problem_type} found:\n{}", log.format_all());
300
301 message.push_str(&_format_dcs_for_log(expected, &actual_vec));
302
303 if disallow_warnings {
304 assert!(log.has_no_warnings_or_errors(), "{message}");
305 } else {
306 assert!(log.has_no_errors(), "{message}");
307 }
308
309 assert_vec_dc_eq_log(expected, &actual_vec, &log);
310
311 (actual_vec, log)
312}
313
314pub fn assert_vec_dc_ok_eq_no_warnings(
315 expected: &[u32],
316 actual: Result<(Vec<u32>, FormatLog)>,
317) -> Vec<u32> {
318 let (actual_vec, log) = _assert_vec_dc_ok_eq_log(expected, actual, true);
319 log.auto_log();
320 actual_vec
321}
322
323pub fn assert_vec_dc_ok_eq_no_errors(
324 expected: &[u32],
325 actual: Result<(Vec<u32>, FormatLog)>,
326) -> (Vec<u32>, FormatLog) {
327 _assert_vec_dc_ok_eq_log(expected, actual, false)
328}
329
330pub fn assert_vec_dc_eq_log(expected: &[u32], actual: &[u32], log: &FormatLog) {
331 let mut message = format!(
332 "Vectors (u32) differ.\n{}\nLog: {}",
333 fmt_mismatch_vec_u32(expected, actual),
334 log.format_all()
335 );
336
337 message.push_str(&_format_dcs_for_log(expected, actual));
338
339 assert_eq!(expected, actual, "{message}");
340}
341
342#[cfg(test)]
343#[allow(
344 clippy::panic,
345 clippy::expect_used,
346 clippy::unwrap_used,
347 clippy::unwrap_in_result,
348 clippy::panic_in_result_fn,
349 clippy::indexing_slicing,
350 clippy::arithmetic_side_effects,
351 reason = "Standard repository test boilerplate"
352)]
353mod tests {
354 use crate::{assert_vec_u8_eq, assert_vec_u32_eq};
355
356 use super::*;
357
358 // Helper: construct a state. Assumes EiteState implements Default.
359 fn new_state() -> EiteState
360 where
361 EiteState: Default,
362 {
363 EiteState::default()
364 }
365
366 #[crate::ctb_test]
367 fn test_transform_document() {
368 // These filters aren't yet implemented, so they should have no effect
369 let dc_array = vec![1, 2, 3];
370 let sem = transform_document(
371 &dc_array,
372 &&DocumentTransformation::semantic_to_text_default(),
373 )
374 .unwrap();
375 assert_vec_u32_eq(&dc_array, &sem);
376 let code = transform_document(
377 &dc_array,
378 &&DocumentTransformation::code_to_text_default(),
379 )
380 .unwrap();
381 assert_vec_u32_eq(&dc_array, &code);
382 }
383
384 // --- import / export wrappers: sanity & equivalence ---
385
386 // NOTE: This does not assert specific Dc values (which are format dependent),
387 // only that the convert_formats wrapper matches manual composition when both succeed.
388 #[crate::ctb_test]
389 fn test_import_and_export_work() {
390 let input_bytes = b"Hello, EITE!";
391
392 // Path 1: separate import then export (ascii -> Dc -> ascii).
393 let (dc, import_log) =
394 import_document(&mut EiteState::new(), &Format::ASCII, input_bytes)
395 .expect("import failed");
396 assert!(!import_log.has_warnings());
397 let (exported, _export_log) = export_document(
398 &mut EiteState::new(),
399 &Format::ASCII,
400 &dc,
401 &PrefilterSettings::default(),
402 )
403 .expect("export failed");
404 assert!(!import_log.has_warnings());
405
406 // Path 2: direct convenience hop (ascii -> utf8).
407 let (via_wrapper, roundtrip_log) = import_and_export(
408 &mut EiteState::new(),
409 &Format::ASCII,
410 &Format::utf8_default(),
411 input_bytes,
412 &PrefilterSettings::default(),
413 )
414 .expect("conv failed");
415 assert!(!roundtrip_log.has_warnings());
416
417 assert_vec_u8_eq(&exported, &via_wrapper);
418 }
419}