ctb_formats_stagel/
stagel2.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//! StageL version 2 normalizer and source tools.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::io::Write;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32enum NormalizerDialect {
33    New,
34    Old,
35}
36
37/// Normalizes StageL v2 source bytes according to the StageL v2 JavaScript
38/// implementation.
39///
40/// Ported from `old/eite-older/sl2/stagel.js`.
41///
42/// Converts lowercase ASCII characters to uppercase, normalizes line endings,
43/// identifies comments starting with `: ` after optional indentation, escapes
44/// non-alphanumeric/non-symbol characters within comments as
45/// `:CHAR:<shifted_dec>:`, encodes digits outside of comments as `N:<char>:`
46/// (shifted by +17 to reduce character set to 32 characters), and returns an
47/// error for any disallowed byte outside of comments.
48pub fn normalize(input: &[u8]) -> Result<Vec<u8>> {
49    normalize_with_dialect(input, NormalizerDialect::New)
50}
51
52/// Normalizes StageL v2 source bytes according to the C implementation of the
53/// StageL v2 normalization rules.
54///
55/// Ported from `old/eite-older/sl2/stagel-normalize.c`.
56///
57/// Converts lowercase ASCII characters to uppercase, normalizes line endings,
58/// identifies comments starting with `: ` after optional indentation, escapes
59/// non-alphanumeric/non-symbol characters within comments as `:CHAR:<dec>:`,
60/// and returns an error for any disallowed byte outside of comments.
61pub fn normalize_old(input: &[u8]) -> Result<Vec<u8>> {
62    normalize_with_dialect(input, NormalizerDialect::Old)
63}
64
65fn normalize_with_dialect(
66    input: &[u8],
67    dialect: NormalizerDialect,
68) -> Result<Vec<u8>> {
69    let mut output = Vec::new();
70    let mut c: u8 = 0;
71    let mut prev: u8;
72    let mut potential_comment: u8 = 0;
73    let mut comment = false;
74
75    for &raw_byte in input {
76        prev = c;
77        c = raw_byte;
78
79        // Uppercase each letter
80        if c.is_ascii_lowercase() {
81            c = c.to_ascii_uppercase();
82        }
83
84        // CRLF: skip the LF
85        if c == b'\n' && prev == b'\r' {
86            continue;
87        }
88
89        // CR to LF
90        if c == b'\r' {
91            c = b'\n';
92        }
93
94        if c == b'\n' {
95            potential_comment = 1;
96        }
97
98        if potential_comment > 0 {
99            if c != b'\n' && c != b' ' && c != b':' {
100                potential_comment = 0;
101            }
102            if potential_comment == 1 && c == b':' {
103                potential_comment = 2;
104            }
105            if potential_comment == 2 && c == b' ' {
106                comment = true;
107                potential_comment = 0;
108            }
109        }
110
111        if comment && c == b'\n' {
112            comment = false;
113        }
114
115        // 10: lf; 32: space; 47: /; 58: :; 48..=57: 0-9; 65..=90: A-Z
116        let is_allowed = c == b'\n'
117            || c == b' '
118            || c == b'/'
119            || c == b':'
120            || c.is_ascii_digit()
121            || c.is_ascii_uppercase();
122
123        if !is_allowed {
124            if comment {
125                match dialect {
126                    NormalizerDialect::New => {
127                        output.extend_from_slice(b":CHAR:");
128                        for digit_byte in c.to_string().bytes() {
129                            /* Escape numbers - this should get the character
130                             * set for normalized StageL to 32 characters
131                             * (A-Z, /, :, space, newline) allowing it to be
132                             * encoded with 5 bits per character, if that's any
133                             * use. */
134                            let shifted = digit_byte
135                                .checked_add(17)
136                                .context("Overflow shifting decimal digit")?;
137                            output.push(shifted);
138                        }
139                        output.push(b':');
140                    }
141                    NormalizerDialect::Old => {
142                        write!(&mut output, ":CHAR:{c}:")?;
143                    }
144                }
145            } else {
146                bail!("Disallowed byte in StageL v2 source: {c}");
147            }
148        } else if c.is_ascii_digit() && dialect == NormalizerDialect::New {
149            let shifted = c
150                .checked_add(17)
151                .context("Overflow shifting digit character")?;
152            output.extend_from_slice(&[b'N', b':', shifted, b':']);
153        } else {
154            output.push(c);
155        }
156    }
157
158    Ok(output)
159}
160
161#[cfg(test)]
162#[allow(
163    clippy::panic,
164    clippy::expect_used,
165    clippy::unwrap_used,
166    clippy::unwrap_in_result,
167    clippy::panic_in_result_fn,
168    clippy::indexing_slicing,
169    clippy::arithmetic_side_effects,
170    reason = "Standard repository test boilerplate"
171)]
172mod tests {
173    use super::*;
174    use crate::get_stagel_data;
175
176    #[crate::ctb_test]
177    fn test_normalize_sl2_js_fixtures() {
178        let input = get_stagel_data("fixtures/sl2/input.sl")
179            .unwrap_or_else(|| panic!("Failed to load fixtures/sl2/input.sl"));
180        let expected = get_stagel_data("fixtures/sl2/intermediate-js.sli")
181            .unwrap_or_else(|| {
182                panic!("Failed to load fixtures/sl2/intermediate-js.sli")
183            });
184
185        let normalized = normalize(&input).unwrap();
186        assert_eq!(normalized, expected);
187    }
188
189    #[crate::ctb_test]
190    fn test_normalize_sl2_c_fixtures() {
191        let input = get_stagel_data("fixtures/sl2/input.sl")
192            .unwrap_or_else(|| panic!("Failed to load fixtures/sl2/input.sl"));
193        let expected = get_stagel_data("fixtures/sl2/intermediate-c.sli")
194            .unwrap_or_else(|| {
195                panic!("Failed to load fixtures/sl2/intermediate-c.sli")
196            });
197
198        let normalized = normalize_old(&input).unwrap();
199        assert_eq!(normalized, expected);
200    }
201}