ctb_formats_stagel/
parse.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 syntax parser and token state machine implementation.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::Token;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32enum ParserState {
33    Token,
34    Comment,
35    LiteralS,
36}
37
38fn to_space_separated_decimals(bytes: &[u8]) -> String {
39    let mut s = String::new();
40    for &b in bytes {
41        s.push(' ');
42        s.push_str(&b.to_string());
43    }
44    s
45}
46
47fn parse_decimal_bytes(s: &str) -> Vec<u8> {
48    s.split_whitespace()
49        .filter_map(|x| x.parse::<u8>().ok())
50        .collect()
51}
52
53fn push_token(
54    tokens: &mut Vec<Token>,
55    active_token: &mut Token,
56    line: usize,
57    col: usize,
58    indent: usize,
59    typ: &str,
60    content: &str,
61) {
62    if !active_token.typ.is_empty() || !active_token.content.is_empty() {
63        tokens.push(active_token.clone());
64        *active_token = Token {
65            pos: format!("{line}:{col}:{indent}"),
66            typ: String::new(),
67            content: String::new(),
68        };
69    }
70    active_token.pos = format!("{line}:{col}:{indent}");
71    active_token.typ = typ.to_string();
72    active_token.content = content.to_string();
73    tokens.push(active_token.clone());
74    *active_token = Token {
75        pos: format!("{line}:{col}:{indent}"),
76        typ: String::new(),
77        content: String::new(),
78    };
79}
80
81pub fn parse(input: &[u8], filename: &str) -> Result<Vec<u8>> {
82    let mut parser_state = ParserState::Token;
83    let mut current_indent_level = 0;
84    let mut counting_indent_spaces = true;
85    let mut indent_spaces_counted = 0;
86    let mut line_number = 1;
87    let mut column_number = 1;
88
89    let mut tokens: Vec<Token> = Vec::new();
90
91    tokens.push(Token {
92        pos: format!("{line_number}:{column_number}:{current_indent_level}"),
93        typ: "start-document".to_string(),
94        content: String::new(),
95    });
96    tokens.push(Token {
97        pos: format!("{line_number}:{column_number}:{current_indent_level}"),
98        typ: "filename".to_string(),
99        content: filename.to_string(),
100    });
101
102    let mut active_token = Token {
103        pos: format!("{line_number}:{column_number}:{current_indent_level}"),
104        typ: String::new(),
105        content: String::new(),
106    };
107
108    let mut idx = 0;
109    while idx < input.len() {
110        let byte = *input.get(idx).context("Invalid input index")?;
111        let is_newline = byte == 10 || byte == 13;
112
113        if is_newline
114            || (byte == 59 && matches!(parser_state, ParserState::Token))
115        {
116            if matches!(parser_state, ParserState::Comment) {
117                parser_state = ParserState::Token;
118                if !active_token.typ.is_empty()
119                    || !active_token.content.is_empty()
120                {
121                    tokens.push(active_token.clone());
122                    active_token = Token {
123                        pos: format!(
124                            "{line_number}:{column_number}:{current_indent_level}"
125                        ),
126                        typ: String::new(),
127                        content: String::new(),
128                    };
129                }
130                counting_indent_spaces = true;
131            } else if matches!(parser_state, ParserState::Token) {
132                if !active_token.typ.is_empty()
133                    || !active_token.content.is_empty()
134                {
135                    tokens.push(active_token.clone());
136                    active_token = Token {
137                        pos: format!(
138                            "{line_number}:{column_number}:{current_indent_level}"
139                        ),
140                        typ: String::new(),
141                        content: String::new(),
142                    };
143                }
144            }
145
146            push_token(
147                &mut tokens,
148                &mut active_token,
149                line_number,
150                column_number,
151                current_indent_level,
152                "newline",
153                "",
154            );
155            line_number = line_number.saturating_add(1);
156            column_number = 1;
157            if is_newline {
158                counting_indent_spaces = true;
159            }
160        } else {
161            column_number = column_number.saturating_add(1);
162
163            if counting_indent_spaces
164                && matches!(parser_state, ParserState::Token)
165            {
166                if (32..=126).contains(&byte) && byte != 32 {
167                    if indent_spaces_counted % 4 == 0
168                        && indent_spaces_counted
169                            < current_indent_level.saturating_mul(4)
170                    {
171                        // Reason for fallback: division by constant non-zero divisor 4 is infallible
172                        let dedents = current_indent_level.saturating_sub(
173                            indent_spaces_counted.checked_div(4).unwrap_or(0),
174                        );
175                        for _ in 0..dedents {
176                            current_indent_level =
177                                current_indent_level.saturating_sub(1);
178                            push_token(
179                                &mut tokens,
180                                &mut active_token,
181                                line_number,
182                                column_number,
183                                current_indent_level,
184                                "dedent",
185                                "",
186                            );
187                        }
188                    } else if indent_spaces_counted
189                        == current_indent_level.saturating_mul(4)
190                    {
191                        // expected indent spaces found; do nothing
192                    } else if indent_spaces_counted
193                        == (current_indent_level.saturating_add(1))
194                            .saturating_mul(4)
195                    {
196                        push_token(
197                            &mut tokens,
198                            &mut active_token,
199                            line_number,
200                            column_number,
201                            current_indent_level,
202                            "indent",
203                            "",
204                        );
205                        current_indent_level =
206                            current_indent_level.saturating_add(1);
207                    } else {
208                        bail!(
209                            "Found {} spaces on line {}, column {}, but the current indentation level would expect {} spaces.",
210                            indent_spaces_counted,
211                            line_number,
212                            column_number,
213                            current_indent_level.saturating_mul(4)
214                        );
215                    }
216                    counting_indent_spaces = false;
217                    indent_spaces_counted = 0;
218                } else if byte == 32 {
219                    indent_spaces_counted =
220                        indent_spaces_counted.saturating_add(1);
221                }
222            }
223
224            match parser_state {
225                ParserState::Token => {
226                    if (65..=90).contains(&byte)
227                        || (97..=122).contains(&byte)
228                        || (48..=57).contains(&byte)
229                        || byte == 45
230                        || byte == 47
231                    {
232                        if active_token.typ.is_empty()
233                            && active_token.content.is_empty()
234                        {
235                            active_token.pos = format!(
236                                "{line_number}:{column_number}:{current_indent_level}"
237                            );
238                        }
239                        active_token.content.push_str(&format!(" {byte}"));
240                    } else if byte == 32 {
241                        if !active_token.content.is_empty() {
242                            tokens.push(active_token.clone());
243                            active_token = Token {
244                                pos: format!(
245                                    "{line_number}:{column_number}:{current_indent_level}"
246                                ),
247                                typ: String::new(),
248                                content: String::new(),
249                            };
250                        }
251                    } else if byte == 125 {
252                        push_token(
253                            &mut tokens,
254                            &mut active_token,
255                            line_number,
256                            column_number,
257                            current_indent_level,
258                            "inline-arglist-end",
259                            "",
260                        );
261                    } else if byte == 123 {
262                        push_token(
263                            &mut tokens,
264                            &mut active_token,
265                            line_number,
266                            column_number,
267                            current_indent_level,
268                            "loop-block",
269                            "",
270                        );
271                    } else if byte == 39 {
272                        parser_state = ParserState::LiteralS;
273                        active_token.pos = format!(
274                            "{line_number}:{column_number}:{current_indent_level}"
275                        );
276                        active_token.typ = "literal-s".to_string();
277                        active_token.content.clear();
278                    } else if byte == 60 {
279                        push_token(
280                            &mut tokens,
281                            &mut active_token,
282                            line_number,
283                            column_number,
284                            current_indent_level,
285                            "literal-ab-start",
286                            "",
287                        );
288                    } else if byte == 62 {
289                        push_token(
290                            &mut tokens,
291                            &mut active_token,
292                            line_number,
293                            column_number,
294                            current_indent_level,
295                            "literal-ab-end",
296                            "",
297                        );
298                    } else if byte == 40 {
299                        push_token(
300                            &mut tokens,
301                            &mut active_token,
302                            line_number,
303                            column_number,
304                            current_indent_level,
305                            "literal-an-start",
306                            "",
307                        );
308                    } else if byte == 41 {
309                        push_token(
310                            &mut tokens,
311                            &mut active_token,
312                            line_number,
313                            column_number,
314                            current_indent_level,
315                            "literal-an-end",
316                            "",
317                        );
318                    } else if byte == 91 {
319                        push_token(
320                            &mut tokens,
321                            &mut active_token,
322                            line_number,
323                            column_number,
324                            current_indent_level,
325                            "literal-as-start",
326                            "",
327                        );
328                    } else if byte == 93 {
329                        push_token(
330                            &mut tokens,
331                            &mut active_token,
332                            line_number,
333                            column_number,
334                            current_indent_level,
335                            "literal-as-end",
336                            "",
337                        );
338                    } else if byte == 35 {
339                        parser_state = ParserState::Comment;
340                        active_token.pos = format!(
341                            "{line_number}:{column_number}:{current_indent_level}"
342                        );
343                        active_token.typ = "comment".to_string();
344                        active_token.content.clear();
345                    } else {
346                        bail!("Unexpected byte {byte} in basic token.");
347                    }
348                }
349                ParserState::LiteralS => {
350                    if byte == 39 {
351                        parser_state = ParserState::Token;
352                        tokens.push(active_token.clone());
353                        active_token = Token {
354                            pos: format!(
355                                "{line_number}:{column_number}:{current_indent_level}"
356                            ),
357                            typ: String::new(),
358                            content: String::new(),
359                        };
360                    } else if (32..=126).contains(&byte) {
361                        active_token.content.push_str(&format!(" {byte}"));
362                    } else {
363                        bail!("Non-printable byte {byte} in a string literal.");
364                    }
365                }
366                ParserState::Comment => {
367                    if (32..=126).contains(&byte) {
368                        active_token.content.push_str(&format!(" {byte}"));
369                    } else {
370                        bail!("Non-printable byte {byte} in a comment.");
371                    }
372                }
373            }
374        }
375        idx = idx.saturating_add(1);
376    }
377
378    if !active_token.typ.is_empty() || !active_token.content.is_empty() {
379        tokens.push(active_token.clone());
380        active_token = Token {
381            pos: format!(
382                "{line_number}:{column_number}:{current_indent_level}"
383            ),
384            typ: String::new(),
385            content: String::new(),
386        };
387    }
388
389    let temp_indent = current_indent_level;
390    for _ in 0..temp_indent {
391        current_indent_level = current_indent_level.saturating_sub(1);
392        push_token(
393            &mut tokens,
394            &mut active_token,
395            line_number,
396            column_number,
397            current_indent_level,
398            "dedent",
399            "",
400        );
401    }
402
403    push_token(
404        &mut tokens,
405        &mut active_token,
406        line_number,
407        column_number,
408        current_indent_level,
409        "end-document",
410        "",
411    );
412
413    // Labelling phase
414    let prefixes = [
415        (b"r/b/".as_slice(), "ident-r-b"),
416        (b"r/n/".as_slice(), "ident-r-n"),
417        (b"r/s/".as_slice(), "ident-r-s"),
418        (b"r/v/".as_slice(), "ident-r-v"),
419        (b"r/ab/".as_slice(), "ident-r-ab"),
420        (b"r/an/".as_slice(), "ident-r-an"),
421        (b"r/as/".as_slice(), "ident-r-as"),
422        (b"b/".as_slice(), "ident-b"),
423        (b"g/".as_slice(), "ident-g"),
424        (b"n/".as_slice(), "ident-n"),
425        (b"s/".as_slice(), "ident-s"),
426        (b"ab/".as_slice(), "ident-ab"),
427        (b"an/".as_slice(), "ident-an"),
428        (b"as/".as_slice(), "ident-as"),
429        (b"ga/".as_slice(), "ident-ga"),
430        (b"gi/".as_slice(), "ident-gi"),
431    ];
432
433    for token in &mut tokens {
434        if token.typ.is_empty() {
435            let content_bytes = parse_decimal_bytes(&token.content);
436            if content_bytes.is_empty() {
437                token.typ = "command".to_string();
438                token.content = String::new();
439            } else if let Some(&first_byte) = content_bytes.first()
440                && ((48..=57).contains(&first_byte) || first_byte == 45)
441            {
442                token.typ = "literal-n".to_string();
443                token.content =
444                    String::from_utf8_lossy(&content_bytes).to_string();
445            } else if content_bytes == b"true" {
446                token.typ = "literal-b".to_string();
447                token.content = "true".to_string();
448            } else if content_bytes == b"false" {
449                token.typ = "literal-b".to_string();
450                token.content = "false".to_string();
451            } else {
452                let mut matched = false;
453                for &(prefix, type_name) in &prefixes {
454                    if content_bytes.starts_with(prefix) {
455                        token.typ = type_name.to_string();
456                        token.content = to_space_separated_decimals(
457                            content_bytes
458                                .get(prefix.len()..)
459                                .context("Invalid prefix length")?,
460                        );
461                        matched = true;
462                        break;
463                    }
464                }
465                if !matched {
466                    token.typ = "command".to_string();
467                    token.content =
468                        String::from_utf8_lossy(&content_bytes).to_string();
469                }
470            }
471        }
472    }
473
474    let mut out_bytes = Vec::new();
475    for token in &tokens {
476        out_bytes.extend_from_slice(token.pos.as_bytes());
477        out_bytes.push(10);
478        out_bytes.extend_from_slice(token.typ.as_bytes());
479        out_bytes.push(10);
480        out_bytes.extend_from_slice(token.content.as_bytes());
481        out_bytes.push(10);
482    }
483
484    Ok(out_bytes)
485}
486
487#[cfg(test)]
488#[allow(
489    clippy::panic,
490    clippy::expect_used,
491    clippy::unwrap_used,
492    clippy::unwrap_in_result,
493    clippy::panic_in_result_fn,
494    clippy::indexing_slicing,
495    clippy::arithmetic_side_effects,
496    reason = "Standard repository test boilerplate"
497)]
498mod tests {
499    use crate::get_stagel_data;
500
501    use super::*;
502
503    #[crate::ctb_test]
504    fn test_parse_and_codegen() {
505        // Load fixture files from data/fixtures
506        let html_content =
507            get_stagel_data("fixtures/format-html.stagel").unwrap();
508
509        let parsed_html = parse(&html_content, "format-html").unwrap();
510
511        // Output parsed result
512        assert!(!parsed_html.is_empty());
513    }
514}