ctb_formats_stagel/
codegen.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 code generation and bytecode emission utilities.
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
31fn ascii_dec_list_to_text(s: &str) -> String {
32    s.split_whitespace()
33        .filter_map(|x| x.parse::<u8>().ok())
34        .map(char::from)
35        .collect()
36}
37
38fn codegen_output(
39    output: &mut String,
40    codegen_new_line: &mut bool,
41    codegen_newline_looking_for_spaces: &mut bool,
42    s: &str,
43) {
44    output.push_str(s);
45    if s.ends_with('\n')
46        || (*codegen_newline_looking_for_spaces && s.ends_with("    "))
47    {
48        *codegen_new_line = true;
49        *codegen_newline_looking_for_spaces = true;
50    } else {
51        *codegen_new_line = false;
52    }
53}
54
55fn codegen_print_indentation_spaces(
56    output: &mut String,
57    codegen_new_line: &mut bool,
58    codegen_newline_looking_for_spaces: &mut bool,
59    codegen_indent: usize,
60    force: bool,
61) {
62    for _ in 0..codegen_indent {
63        if force || *codegen_new_line {
64            codegen_output(
65                output,
66                codegen_new_line,
67                codegen_newline_looking_for_spaces,
68                "    ",
69            );
70        }
71    }
72}
73
74fn codegen_format_type(
75    _target_lang: &str,
76    t: &str,
77    uppercase_first: bool,
78    dont_die: bool,
79) -> Result<String> {
80    let result = match t {
81        "literal-b" | "ident-b" | "ident-r-b" => "bool",
82        "literal-n" | "ident-n" | "ident-r-n" => "int",
83        "literal-s" | "ident-s" | "ident-r-s" => "str",
84        "ident-g" => "generic",
85        "ident-ab" | "ident-r-ab" => "boolArray",
86        "ident-an" | "ident-r-an" => "intArray",
87        "ident-as" | "ident-r-as" => "strArray",
88        "ident-ga" => "genericArray",
89        "ident-gi" => "genericItem",
90        "ident-r-v" => "void",
91        _ => "",
92    };
93    if result.is_empty() {
94        if dont_die {
95            return Ok(String::new());
96        }
97        bail!("{t} is not a recognized type!");
98    }
99    if uppercase_first {
100        let mut chars = result.chars();
101        match chars.next() {
102            None => Ok(String::new()),
103            Some(f) => {
104                Ok(f.to_uppercase().collect::<String>() + chars.as_str())
105            }
106        }
107    } else {
108        Ok(result.to_string())
109    }
110}
111
112fn codegen_string_literal_delim(
113    target_lang: &str,
114    output: &mut String,
115    codegen_new_line: &mut bool,
116    codegen_newline_looking_for_spaces: &mut bool,
117) -> Result<()> {
118    if target_lang == "js" || target_lang == "bash" || target_lang == "sh" {
119        codegen_output(
120            output,
121            codegen_new_line,
122            codegen_newline_looking_for_spaces,
123            "'",
124        );
125    } else {
126        codegen_output(
127            output,
128            codegen_new_line,
129            codegen_newline_looking_for_spaces,
130            "\"",
131        );
132    }
133    Ok(())
134}
135
136fn codegen_literal(
137    target_lang: &str,
138    typ: &str,
139    val: &str,
140    output: &mut String,
141    codegen_new_line: &mut bool,
142    codegen_newline_looking_for_spaces: &mut bool,
143) -> Result<()> {
144    if typ == "literal-s" {
145        let temp = ascii_dec_list_to_text(val);
146        codegen_string_literal_delim(
147            target_lang,
148            output,
149            codegen_new_line,
150            codegen_newline_looking_for_spaces,
151        )?;
152        if target_lang == "bash" || target_lang == "sh" {
153            codegen_output(
154                output,
155                codegen_new_line,
156                codegen_newline_looking_for_spaces,
157                &temp,
158            );
159        } else {
160            let escaped = temp.replace('\\', "\\\\");
161            codegen_output(
162                output,
163                codegen_new_line,
164                codegen_newline_looking_for_spaces,
165                &escaped,
166            );
167        }
168        codegen_string_literal_delim(
169            target_lang,
170            output,
171            codegen_new_line,
172            codegen_newline_looking_for_spaces,
173        )?;
174    } else if typ == "literal-n" || typ == "literal-b" {
175        if target_lang == "bash" || target_lang == "sh" {
176            codegen_output(
177                output,
178                codegen_new_line,
179                codegen_newline_looking_for_spaces,
180                &format!("'{val}'"),
181            );
182        } else {
183            codegen_output(
184                output,
185                codegen_new_line,
186                codegen_newline_looking_for_spaces,
187                val,
188            );
189        }
190    } else if typ.starts_with("literal-a") {
191        codegen_output(
192            output,
193            codegen_new_line,
194            codegen_newline_looking_for_spaces,
195            val,
196        );
197    }
198    Ok(())
199}
200
201fn codegen_reference(
202    target_lang: &str,
203    is_assignment_target: bool,
204    typ: &str,
205    name: &str,
206    output: &mut String,
207    codegen_new_line: &mut bool,
208    codegen_newline_looking_for_spaces: &mut bool,
209) -> Result<()> {
210    let uppercase_name = {
211        let mut chars = name.chars();
212        match chars.next() {
213            None => String::new(),
214            Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
215        }
216    };
217    if target_lang == "js" {
218        let formatted_type =
219            codegen_format_type(target_lang, typ, false, false)?;
220        codegen_output(
221            output,
222            codegen_new_line,
223            codegen_newline_looking_for_spaces,
224            &formatted_type,
225        );
226        codegen_output(
227            output,
228            codegen_new_line,
229            codegen_newline_looking_for_spaces,
230            &uppercase_name,
231        );
232    } else if target_lang == "bash" || target_lang == "sh" {
233        let is_array = typ.starts_with("ident-a")
234            || typ == "ident-ga"
235            || typ == "ident-gi";
236        if is_array {
237            if is_assignment_target {
238                let formatted_type =
239                    codegen_format_type(target_lang, typ, false, false)?;
240                codegen_output(
241                    output,
242                    codegen_new_line,
243                    codegen_newline_looking_for_spaces,
244                    &formatted_type,
245                );
246                codegen_output(
247                    output,
248                    codegen_new_line,
249                    codegen_newline_looking_for_spaces,
250                    &uppercase_name,
251                );
252            } else {
253                let formatted_type =
254                    codegen_format_type(target_lang, typ, false, false)?;
255                codegen_output(
256                    output,
257                    codegen_new_line,
258                    codegen_newline_looking_for_spaces,
259                    &format!(
260                        "\"$(join_by $'\\037' \"${{{formatted_type}{uppercase_name}[@]}}\")\""
261                    ),
262                );
263            }
264        } else {
265            if !is_assignment_target {
266                codegen_output(
267                    output,
268                    codegen_new_line,
269                    codegen_newline_looking_for_spaces,
270                    "\"$",
271                );
272            }
273            let formatted_type =
274                codegen_format_type(target_lang, typ, false, false)?;
275            codegen_output(
276                output,
277                codegen_new_line,
278                codegen_newline_looking_for_spaces,
279                &formatted_type,
280            );
281            codegen_output(
282                output,
283                codegen_new_line,
284                codegen_newline_looking_for_spaces,
285                &uppercase_name,
286            );
287            if !is_assignment_target {
288                codegen_output(
289                    output,
290                    codegen_new_line,
291                    codegen_newline_looking_for_spaces,
292                    "\"",
293                );
294            }
295        }
296    }
297    Ok(())
298}
299
300fn codegen_initialize_type(
301    target_lang: &str,
302    t: &str,
303    output: &mut String,
304    codegen_new_line: &mut bool,
305    codegen_newline_looking_for_spaces: &mut bool,
306) -> Result<()> {
307    if target_lang == "bash" || target_lang == "sh" {
308        codegen_output(
309            output,
310            codegen_new_line,
311            codegen_newline_looking_for_spaces,
312            "=",
313        );
314    } else {
315        codegen_output(
316            output,
317            codegen_new_line,
318            codegen_newline_looking_for_spaces,
319            " = ",
320        );
321    }
322    match t {
323        "bool" => {
324            codegen_literal(
325                target_lang,
326                "literal-b",
327                "false",
328                output,
329                codegen_new_line,
330                codegen_newline_looking_for_spaces,
331            )?;
332        }
333        "int" => {
334            codegen_literal(
335                target_lang,
336                "literal-n",
337                "0",
338                output,
339                codegen_new_line,
340                codegen_newline_looking_for_spaces,
341            )?;
342        }
343        "str" => {
344            codegen_string_literal_delim(
345                target_lang,
346                output,
347                codegen_new_line,
348                codegen_newline_looking_for_spaces,
349            )?;
350            codegen_string_literal_delim(
351                target_lang,
352                output,
353                codegen_new_line,
354                codegen_newline_looking_for_spaces,
355            )?;
356        }
357        "boolArray" | "intArray" | "strArray" | "genericArray" => {
358            if target_lang == "bash" || target_lang == "sh" {
359                codegen_output(
360                    output,
361                    codegen_new_line,
362                    codegen_newline_looking_for_spaces,
363                    "()",
364                );
365            } else {
366                codegen_output(
367                    output,
368                    codegen_new_line,
369                    codegen_newline_looking_for_spaces,
370                    "[]",
371                );
372            }
373        }
374        _ => bail!("Initialize requested for unexpected type of {t}."),
375    }
376    Ok(())
377}
378
379fn codegen_start_array(
380    target_lang: &str,
381    state_stack: &[String],
382    block_stack: &[(String, String)],
383    _element_type: &str,
384) -> String {
385    if target_lang == "js" {
386        "[ ".to_string()
387    } else if target_lang == "bash" || target_lang == "sh" {
388        let in_arglist = state_stack.last().is_some_and(|s| s == "arglist");
389        let is_not_set = block_stack.last().is_none_or(|b| b.1 != "set");
390        if in_arglist && is_not_set {
391            "\"$(join_by $'\\037' ".to_string()
392        } else {
393            "( ".to_string()
394        }
395    } else {
396        "[ ".to_string()
397    }
398}
399
400fn codegen_end_array(
401    target_lang: &str,
402    state_stack: &[String],
403    block_stack: &[(String, String)],
404) -> String {
405    if target_lang == "js" {
406        " ]".to_string()
407    } else if target_lang == "bash" || target_lang == "sh" {
408        let in_arglist = state_stack
409            .get(state_stack.len().saturating_sub(2))
410            .map(String::as_str)
411            == Some("arglist");
412        let is_not_set = block_stack.last().is_none_or(|b| b.1 != "set");
413        if in_arglist && is_not_set {
414            ")\"".to_string()
415        } else {
416            " )".to_string()
417        }
418    } else {
419        " ]".to_string()
420    }
421}
422
423fn codegen_array_entry_delimiter(
424    target_lang: &str,
425    end_of_line: bool,
426) -> String {
427    if target_lang == "js" {
428        if end_of_line {
429            ",".to_string()
430        } else {
431            ", ".to_string()
432        }
433    } else {
434        " ".to_string()
435    }
436}
437
438fn codegen_format_argument(
439    target_lang: &str,
440    arg_type: &str,
441    arg_name: &str,
442    output: &mut String,
443    codegen_new_line: &mut bool,
444    codegen_newline_looking_for_spaces: &mut bool,
445) -> Result<()> {
446    let formatted_type =
447        codegen_format_type(target_lang, arg_type, false, false)?;
448    let uppercase_name = {
449        let mut chars = arg_name.chars();
450        match chars.next() {
451            None => String::new(),
452            Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
453        }
454    };
455    if target_lang == "js" {
456        codegen_output(
457            output,
458            codegen_new_line,
459            codegen_newline_looking_for_spaces,
460            &formatted_type,
461        );
462        codegen_output(
463            output,
464            codegen_new_line,
465            codegen_newline_looking_for_spaces,
466            &uppercase_name,
467        );
468    } else if target_lang == "bash" {
469        if formatted_type == "boolArray"
470            || formatted_type == "intArray"
471            || formatted_type == "strArray"
472            || formatted_type == "genericArray"
473            || formatted_type == "genericItem"
474        {
475            codegen_output(
476                output,
477                codegen_new_line,
478                codegen_newline_looking_for_spaces,
479                &format!(
480                    "\"$(join_by $'\\037' \"${{{formatted_type}{uppercase_name}[@]}}\")\""
481                ),
482            );
483        } else {
484            codegen_output(
485                output,
486                codegen_new_line,
487                codegen_newline_looking_for_spaces,
488                &format!("\"${formatted_type}{uppercase_name}\""),
489            );
490        }
491    }
492    Ok(())
493}
494
495fn codegen_comment(
496    target_lang: &str,
497    comment_text: &str,
498    codegen_indent: usize,
499    output: &mut String,
500    codegen_new_line: &mut bool,
501    codegen_newline_looking_for_spaces: &mut bool,
502) -> Result<()> {
503    codegen_print_indentation_spaces(
504        output,
505        codegen_new_line,
506        codegen_newline_looking_for_spaces,
507        codegen_indent,
508        false,
509    );
510    if target_lang == "js" {
511        codegen_output(
512            output,
513            codegen_new_line,
514            codegen_newline_looking_for_spaces,
515            &format!("/*{comment_text} */\n"),
516        );
517    } else if target_lang == "bash" || target_lang == "sh" {
518        codegen_output(
519            output,
520            codegen_new_line,
521            codegen_newline_looking_for_spaces,
522            &format!("#{comment_text}\n"),
523        );
524    }
525    Ok(())
526}
527
528fn codegen_indent_action(
529    target_lang: &str,
530    codegen_indent: usize,
531    output: &mut String,
532    codegen_new_line: &mut bool,
533    codegen_newline_looking_for_spaces: &mut bool,
534) -> Result<()> {
535    if *codegen_new_line {
536        codegen_print_indentation_spaces(
537            output,
538            codegen_new_line,
539            codegen_newline_looking_for_spaces,
540            codegen_indent,
541            false,
542        );
543    }
544    if target_lang == "js" {
545        if !*codegen_new_line {
546            codegen_output(
547                output,
548                codegen_new_line,
549                codegen_newline_looking_for_spaces,
550                " ",
551            );
552        }
553        codegen_output(
554            output,
555            codegen_new_line,
556            codegen_newline_looking_for_spaces,
557            "{\n",
558        );
559    } else if target_lang == "bash" {
560        codegen_output(
561            output,
562            codegen_new_line,
563            codegen_newline_looking_for_spaces,
564            "\n",
565        );
566    }
567    Ok(())
568}
569
570fn codegen_dedent_action(
571    target_lang: &str,
572    codegen_indent: usize,
573    block_stack: &[(String, String)],
574    next_token_content: &str,
575    output: &mut String,
576    codegen_new_line: &mut bool,
577    codegen_newline_looking_for_spaces: &mut bool,
578) -> Result<()> {
579    codegen_print_indentation_spaces(
580        output,
581        codegen_new_line,
582        codegen_newline_looking_for_spaces,
583        codegen_indent,
584        false,
585    );
586    if target_lang == "js" {
587        codegen_output(
588            output,
589            codegen_new_line,
590            codegen_newline_looking_for_spaces,
591            "}\n",
592        );
593    } else if target_lang == "bash" {
594        let len = block_stack.len();
595        // Reason for fallback: empty block stack defaults grandparent block type string to empty
596        let grandparent_type = block_stack
597            .get(len.saturating_sub(2))
598            .map_or("", |x| x.0.as_str());
599        if grandparent_type == "test-body-if"
600            || grandparent_type == "test-body-elif"
601            || grandparent_type == "test-body-else"
602        {
603            if next_token_content != "else" && next_token_content != "elif" {
604                codegen_output(
605                    output,
606                    codegen_new_line,
607                    codegen_newline_looking_for_spaces,
608                    "fi\n",
609                );
610            }
611        } else if grandparent_type == "test-body-while" {
612            codegen_output(
613                output,
614                codegen_new_line,
615                codegen_newline_looking_for_spaces,
616                "done\n",
617            );
618        } else {
619            codegen_output(
620                output,
621                codegen_new_line,
622                codegen_newline_looking_for_spaces,
623                "}\n",
624            );
625        }
626    }
627    Ok(())
628}
629
630fn block_stack_remove_last(
631    block_stack: &mut Vec<(String, String)>,
632) -> Result<()> {
633    let len = block_stack.len();
634    if len >= 2
635        && block_stack
636            .get(len.saturating_sub(1))
637            .is_some_and(|b| b.1.is_empty() && b.0 == "plain-block")
638        && block_stack
639            .get(len.saturating_sub(2))
640            .is_some_and(|b| b.0 == "test")
641    {
642        block_stack.pop();
643    }
644    if let Some(target) = block_stack.last() {
645        if target.0 == "root" {
646            bail!("Internal error: Trying to remove root block!");
647        }
648    } else {
649        bail!("Internal error: block stack is empty!");
650    }
651    block_stack.pop();
652    Ok(())
653}
654
655fn codegen_get_current_routine_type(
656    target_lang: &str,
657    block_stack: &[(String, String)],
658) -> Result<String> {
659    let mut counter = block_stack.len();
660    while counter > 0 {
661        counter = counter.saturating_sub(1);
662        let t = &block_stack
663            .get(counter)
664            .context("Invalid block stack index")?
665            .0;
666        if codegen_format_type(target_lang, t, false, true).is_ok() {
667            let formatted = codegen_format_type(target_lang, t, false, true)?;
668            if !formatted.is_empty() {
669                return Ok(t.clone());
670            }
671        }
672    }
673    Ok(String::new())
674}
675
676fn codegen_routine_definition_pre_end(
677    target_lang: &str,
678    codegen_routine_type: &str,
679    debug_build: bool,
680    codegen_indent: usize,
681    output: &mut String,
682    codegen_new_line: &mut bool,
683    codegen_newline_looking_for_spaces: &mut bool,
684) -> Result<()> {
685    if target_lang == "js" || target_lang == "bash" {
686        if codegen_routine_type == "ident-r-v" {
687            codegen_output(
688                output,
689                codegen_new_line,
690                codegen_newline_looking_for_spaces,
691                "\n",
692            );
693            codegen_print_indentation_spaces(
694                output,
695                codegen_new_line,
696                codegen_newline_looking_for_spaces,
697                codegen_indent.saturating_add(1),
698                false,
699            );
700        }
701        if debug_build {
702            codegen_output(
703                output,
704                codegen_new_line,
705                codegen_newline_looking_for_spaces,
706                "StageL_internalDebugStackExit",
707            );
708            if target_lang == "bash" {
709                codegen_output(
710                    output,
711                    codegen_new_line,
712                    codegen_newline_looking_for_spaces,
713                    ";",
714                );
715            } else {
716                codegen_output(
717                    output,
718                    codegen_new_line,
719                    codegen_newline_looking_for_spaces,
720                    "();",
721                );
722            }
723        }
724        if codegen_routine_type == "ident-r-v" {
725            codegen_output(
726                output,
727                codegen_new_line,
728                codegen_newline_looking_for_spaces,
729                "\n",
730            );
731        } else {
732            codegen_output(
733                output,
734                codegen_new_line,
735                codegen_newline_looking_for_spaces,
736                " ",
737            );
738        }
739    }
740    Ok(())
741}
742
743fn codegen_routine_definition_start(
744    target_lang: &str,
745    codegen_routine_name: &mut String,
746    codegen_routine_type: &mut String,
747    codegen_arg_list: &mut Vec<(String, String)>,
748    filename: &str,
749    debug_build: bool,
750    typecheck_build: bool,
751    codegen_indent: &mut usize,
752    output: &mut String,
753    codegen_new_line: &mut bool,
754    codegen_newline_looking_for_spaces: &mut bool,
755) -> Result<()> {
756    if target_lang == "js" {
757        codegen_output(
758            output,
759            codegen_new_line,
760            codegen_newline_looking_for_spaces,
761            &format!("async function {codegen_routine_name}("),
762        );
763        let argument_count = codegen_arg_list.len();
764        for (k, (arg_type, arg_name)) in codegen_arg_list.iter().enumerate() {
765            let formatted_type =
766                codegen_format_type(target_lang, arg_type, false, false)?;
767            let uppercase_name = {
768                let mut chars = arg_name.chars();
769                match chars.next() {
770                    None => String::new(),
771                    Some(f) => {
772                        f.to_uppercase().collect::<String>() + chars.as_str()
773                    }
774                }
775            };
776            codegen_output(
777                output,
778                codegen_new_line,
779                codegen_newline_looking_for_spaces,
780                &formatted_type,
781            );
782            codegen_output(
783                output,
784                codegen_new_line,
785                codegen_newline_looking_for_spaces,
786                &uppercase_name,
787            );
788            if k != argument_count.saturating_sub(1) {
789                codegen_output(
790                    output,
791                    codegen_new_line,
792                    codegen_newline_looking_for_spaces,
793                    ", ",
794                );
795            }
796        }
797        codegen_output(
798            output,
799            codegen_new_line,
800            codegen_newline_looking_for_spaces,
801            ") {\n",
802        );
803    } else if target_lang == "bash" {
804        codegen_output(
805            output,
806            codegen_new_line,
807            codegen_newline_looking_for_spaces,
808            &format!("{codegen_routine_name}() {{\n"),
809        );
810    }
811
812    *codegen_indent = (*codegen_indent).saturating_add(1);
813    codegen_print_indentation_spaces(
814        output,
815        codegen_new_line,
816        codegen_newline_looking_for_spaces,
817        *codegen_indent,
818        false,
819    );
820    *codegen_indent = (*codegen_indent).saturating_sub(1);
821
822    let argument_count = codegen_arg_list.len();
823    if target_lang == "bash" {
824        for (k, (arg_type, arg_name)) in codegen_arg_list.iter().enumerate() {
825            let formatted_type =
826                codegen_format_type(target_lang, arg_type, false, false)?;
827            let uppercase_name = {
828                let mut chars = arg_name.chars();
829                match chars.next() {
830                    None => String::new(),
831                    Some(f) => {
832                        f.to_uppercase().collect::<String>() + chars.as_str()
833                    }
834                }
835            };
836            let is_array = formatted_type == "boolArray"
837                || formatted_type == "intArray"
838                || formatted_type == "strArray"
839                || formatted_type == "genericArray"
840                || formatted_type == "genericItem";
841
842            let is_last = k == argument_count.saturating_sub(1);
843            if is_array {
844                codegen_output(
845                    output,
846                    codegen_new_line,
847                    codegen_newline_looking_for_spaces,
848                    &format!(
849                        "IFS=$'\\037' read -r -a {formatted_type}{uppercase_name} <<< \"$1\"; shift"
850                    ),
851                );
852            } else if is_last && !debug_build {
853                codegen_output(
854                    output,
855                    codegen_new_line,
856                    codegen_newline_looking_for_spaces,
857                    &format!("{formatted_type}{uppercase_name}=\"$1\""),
858                );
859            } else {
860                codegen_output(
861                    output,
862                    codegen_new_line,
863                    codegen_newline_looking_for_spaces,
864                    &format!("{formatted_type}{uppercase_name}=\"$1\"; shift"),
865                );
866            }
867            if !is_last || debug_build {
868                codegen_output(
869                    output,
870                    codegen_new_line,
871                    codegen_newline_looking_for_spaces,
872                    "; ",
873                );
874            }
875        }
876    }
877
878    if debug_build {
879        for (arg_type, arg_name) in codegen_arg_list.iter() {
880            let formatted_type =
881                codegen_format_type(target_lang, arg_type, false, false)?;
882            let uppercase_name = {
883                let mut chars = arg_name.chars();
884                match chars.next() {
885                    None => String::new(),
886                    Some(f) => {
887                        f.to_uppercase().collect::<String>() + chars.as_str()
888                    }
889                }
890            };
891            if target_lang == "js" {
892                codegen_output(
893                    output,
894                    codegen_new_line,
895                    codegen_newline_looking_for_spaces,
896                    &format!(
897                        "StageL_internalDebugCollect('{formatted_type} {uppercase_name} = ' + {formatted_type}{uppercase_name} + '; '); "
898                    ),
899                );
900            } else if target_lang == "bash" {
901                codegen_output(
902                    output,
903                    codegen_new_line,
904                    codegen_newline_looking_for_spaces,
905                    &format!(
906                        "StageL_internalDebugCollect \"{formatted_type} {uppercase_name} = ${formatted_type}{uppercase_name}; \"; "
907                    ),
908                );
909            }
910        }
911        if target_lang == "js" {
912            codegen_output(
913                output,
914                codegen_new_line,
915                codegen_newline_looking_for_spaces,
916                &format!(
917                    "StageL_internalDebugStackEnter('{codegen_routine_name}:{filename}');"
918                ),
919            );
920        } else if target_lang == "bash" {
921            codegen_output(
922                output,
923                codegen_new_line,
924                codegen_newline_looking_for_spaces,
925                &format!(
926                    "StageL_internalDebugStackEnter '{codegen_routine_name}:{filename}';"
927                ),
928            );
929        }
930    }
931
932    if argument_count != 0 || codegen_routine_type != "ident-r-v" {
933        codegen_output(
934            output,
935            codegen_new_line,
936            codegen_newline_looking_for_spaces,
937            " ",
938        );
939    }
940
941    if typecheck_build {
942        for (k, (arg_type, arg_name)) in codegen_arg_list.iter().enumerate() {
943            if k != 0 {
944                codegen_output(
945                    output,
946                    codegen_new_line,
947                    codegen_newline_looking_for_spaces,
948                    " ",
949                );
950            }
951            let formatted_type =
952                codegen_format_type(target_lang, arg_type, true, false)?;
953            if target_lang == "js" {
954                codegen_output(
955                    output,
956                    codegen_new_line,
957                    codegen_newline_looking_for_spaces,
958                    &format!("StageL_assertIs{formatted_type}("),
959                );
960                codegen_format_argument(
961                    target_lang,
962                    arg_type,
963                    arg_name,
964                    output,
965                    codegen_new_line,
966                    codegen_newline_looking_for_spaces,
967                )?;
968                codegen_output(
969                    output,
970                    codegen_new_line,
971                    codegen_newline_looking_for_spaces,
972                    ");",
973                );
974            } else if target_lang == "bash" {
975                codegen_output(
976                    output,
977                    codegen_new_line,
978                    codegen_newline_looking_for_spaces,
979                    &format!("StageL_assertIs{formatted_type} "),
980                );
981                codegen_format_argument(
982                    target_lang,
983                    arg_type,
984                    arg_name,
985                    output,
986                    codegen_new_line,
987                    codegen_newline_looking_for_spaces,
988                )?;
989                if k != argument_count.saturating_sub(1) {
990                    codegen_output(
991                        output,
992                        codegen_new_line,
993                        codegen_newline_looking_for_spaces,
994                        ";",
995                    );
996                }
997            }
998        }
999    }
1000
1001    if argument_count != 0 && codegen_routine_type != "ident-r-v" {
1002        if target_lang != "bash" {
1003            codegen_output(
1004                output,
1005                codegen_new_line,
1006                codegen_newline_looking_for_spaces,
1007                " ",
1008            );
1009        }
1010    }
1011
1012    if codegen_routine_type != "ident-r-v" {
1013        if target_lang == "js" {
1014            let formatted_ret_type = codegen_format_type(
1015                target_lang,
1016                codegen_routine_type,
1017                false,
1018                false,
1019            )?;
1020            codegen_output(
1021                output,
1022                codegen_new_line,
1023                codegen_newline_looking_for_spaces,
1024                &format!("let {formatted_ret_type}Return;"),
1025            );
1026        }
1027    }
1028
1029    codegen_output(
1030        output,
1031        codegen_new_line,
1032        codegen_newline_looking_for_spaces,
1033        "\n\n",
1034    );
1035    codegen_routine_type.clear();
1036    codegen_routine_name.clear();
1037    codegen_arg_list.clear();
1038    Ok(())
1039}
1040
1041fn codegen_is_test_command(s: &str) -> bool {
1042    s == "if" || s == "elif" || s == "while"
1043}
1044
1045fn codegen_command_invocation_arglist(
1046    target_lang: &str,
1047    codegen_routine_type: &mut String,
1048    codegen_routine_name: &mut String,
1049    codegen_arg_list: &mut Vec<(String, String)>,
1050    codegen_last_known_arglist_count: &mut usize,
1051    output: &mut String,
1052    codegen_new_line: &mut bool,
1053    codegen_newline_looking_for_spaces: &mut bool,
1054) -> Result<()> {
1055    let argument_count = codegen_arg_list.len();
1056    for (k, (arg_type, arg_val)) in codegen_arg_list.iter().enumerate() {
1057        if arg_type.starts_with("literal-") {
1058            codegen_literal(
1059                target_lang,
1060                arg_type,
1061                arg_val,
1062                output,
1063                codegen_new_line,
1064                codegen_newline_looking_for_spaces,
1065            )?;
1066        } else {
1067            codegen_reference(
1068                target_lang,
1069                false,
1070                arg_type,
1071                arg_val,
1072                output,
1073                codegen_new_line,
1074                codegen_newline_looking_for_spaces,
1075            )?;
1076        }
1077        if k != argument_count.saturating_sub(1) {
1078            codegen_command_invocation_arg_separator(
1079                target_lang,
1080                output,
1081                codegen_new_line,
1082                codegen_newline_looking_for_spaces,
1083            )?;
1084        }
1085    }
1086    *codegen_last_known_arglist_count = argument_count;
1087    codegen_routine_type.clear();
1088    codegen_routine_name.clear();
1089    codegen_arg_list.clear();
1090    Ok(())
1091}
1092
1093fn codegen_command_invocation_arg_separator(
1094    target_lang: &str,
1095    output: &mut String,
1096    codegen_new_line: &mut bool,
1097    codegen_newline_looking_for_spaces: &mut bool,
1098) -> Result<()> {
1099    if target_lang == "js" {
1100        codegen_output(
1101            output,
1102            codegen_new_line,
1103            codegen_newline_looking_for_spaces,
1104            ", ",
1105        );
1106    } else {
1107        codegen_output(
1108            output,
1109            codegen_new_line,
1110            codegen_newline_looking_for_spaces,
1111            " ",
1112        );
1113    }
1114    Ok(())
1115}
1116
1117fn codegen_command_invocation_end(
1118    target_lang: &str,
1119    codegen_routine_type: &mut String,
1120    codegen_routine_name: &mut String,
1121    codegen_arg_list: &mut Vec<(String, String)>,
1122    block_stack: &mut Vec<(String, String)>,
1123    state_stack: &[String],
1124    codegen_invocation_level: &mut usize,
1125    output: &mut String,
1126    codegen_new_line: &mut bool,
1127    codegen_newline_looking_for_spaces: &mut bool,
1128) -> Result<()> {
1129    if codegen_routine_name == "return" || codegen_routine_name == "new" {
1130        bail!(
1131            "Internal error (this is a bug): codegenCommandInvocationEnd called for return/new"
1132        );
1133    }
1134    if target_lang == "js" {
1135        let mut skip_paren = false;
1136        if let Some(last) = block_stack.last() {
1137            if last.0 == "command"
1138                && (last.1 == "new"
1139                    || last.1 == "return"
1140                    || last.1 == "set"
1141                    || last.1 == "else"
1142                    || last.1 == "debugger")
1143            {
1144                skip_paren = true;
1145            }
1146        }
1147        if !skip_paren {
1148            codegen_output(
1149                output,
1150                codegen_new_line,
1151                codegen_newline_looking_for_spaces,
1152                ")",
1153            );
1154        }
1155    } else if target_lang == "bash" {
1156        // Reason for fallback: empty block stack defaults last block type string to empty
1157        let last_block = block_stack.last().map_or("", |b| b.1.as_str());
1158        if last_block == "if" || last_block == "elif" || last_block == "while" {
1159            if last_block == "while" {
1160                codegen_output(
1161                    output,
1162                    codegen_new_line,
1163                    codegen_newline_looking_for_spaces,
1164                    " ]]; do",
1165                );
1166            } else {
1167                codegen_output(
1168                    output,
1169                    codegen_new_line,
1170                    codegen_newline_looking_for_spaces,
1171                    " ]]; then",
1172                );
1173            }
1174        } else if *codegen_invocation_level != 0 {
1175            codegen_output(
1176                output,
1177                codegen_new_line,
1178                codegen_newline_looking_for_spaces,
1179                ")\"",
1180            );
1181            *codegen_invocation_level =
1182                (*codegen_invocation_level).saturating_sub(1);
1183        }
1184    }
1185
1186    if !state_stack.contains(&"test".to_string()) {
1187        let is_not_arglist = state_stack
1188            .get(state_stack.len().saturating_sub(2))
1189            .is_none_or(|s| s != "arglist");
1190        let last_block_is_not_else =
1191            block_stack.last().is_none_or(|b| b.0 != "else");
1192        if is_not_arglist && last_block_is_not_else {
1193            if target_lang == "js" {
1194                codegen_output(
1195                    output,
1196                    codegen_new_line,
1197                    codegen_newline_looking_for_spaces,
1198                    ";",
1199                );
1200            }
1201            codegen_output(
1202                output,
1203                codegen_new_line,
1204                codegen_newline_looking_for_spaces,
1205                "\n",
1206            );
1207        }
1208    }
1209    block_stack_remove_last(block_stack)?;
1210    codegen_routine_type.clear();
1211    codegen_routine_name.clear();
1212    codegen_arg_list.clear();
1213    Ok(())
1214}
1215
1216fn codegen_command_invocation_start(
1217    target_lang: &str,
1218    codegen_routine_name: &mut String,
1219    codegen_routine_type: &mut String,
1220    codegen_arg_list: &mut Vec<(String, String)>,
1221    block_stack: &[(String, String)],
1222    _state_stack: &[String],
1223    typecheck_build: bool,
1224    codegen_indent: usize,
1225    codegen_invocation_level: &mut usize,
1226    token_lookahead: &mut String,
1227    debug_build: bool,
1228    output: &mut String,
1229    codegen_new_line: &mut bool,
1230    codegen_newline_looking_for_spaces: &mut bool,
1231) -> Result<()> {
1232    match codegen_routine_name.as_str() {
1233        "new" => {
1234            if codegen_arg_list
1235                .iter()
1236                .any(|arg| arg.0.starts_with("ident-r-"))
1237            {
1238                bail!(
1239                    "Sorry, invoking functions isn't available when declaring a variable. Please use set to assign it after declaration."
1240                );
1241            }
1242            codegen_print_indentation_spaces(
1243                output,
1244                codegen_new_line,
1245                codegen_newline_looking_for_spaces,
1246                codegen_indent,
1247                false,
1248            );
1249            if target_lang == "js" {
1250                codegen_output(
1251                    output,
1252                    codegen_new_line,
1253                    codegen_newline_looking_for_spaces,
1254                    "let ",
1255                );
1256            }
1257            let len = codegen_arg_list.len();
1258            if len >= 2 {
1259                let arg_minus_2 = codegen_arg_list
1260                    .get(len.saturating_sub(2))
1261                    .context("Missing arg minus 2")?;
1262                let arg_minus_1 = codegen_arg_list
1263                    .get(len.saturating_sub(1))
1264                    .context("Missing arg minus 1")?;
1265                codegen_reference(
1266                    target_lang,
1267                    true,
1268                    &arg_minus_2.0,
1269                    &arg_minus_2.1,
1270                    output,
1271                    codegen_new_line,
1272                    codegen_newline_looking_for_spaces,
1273                )?;
1274                if target_lang == "bash" {
1275                    codegen_output(
1276                        output,
1277                        codegen_new_line,
1278                        codegen_newline_looking_for_spaces,
1279                        "=",
1280                    );
1281                } else {
1282                    codegen_output(
1283                        output,
1284                        codegen_new_line,
1285                        codegen_newline_looking_for_spaces,
1286                        " = ",
1287                    );
1288                }
1289                codegen_literal(
1290                    target_lang,
1291                    &arg_minus_1.0,
1292                    &arg_minus_1.1,
1293                    output,
1294                    codegen_new_line,
1295                    codegen_newline_looking_for_spaces,
1296                )?;
1297            } else {
1298                let arg_minus_1 = codegen_arg_list
1299                    .get(len.saturating_sub(1))
1300                    .context("Missing arg minus 1")?;
1301                codegen_reference(
1302                    target_lang,
1303                    true,
1304                    &arg_minus_1.0,
1305                    &arg_minus_1.1,
1306                    output,
1307                    codegen_new_line,
1308                    codegen_newline_looking_for_spaces,
1309                )?;
1310                if token_lookahead.starts_with("ident-")
1311                    || token_lookahead.starts_with("literal-")
1312                {
1313                    if target_lang == "bash" {
1314                        codegen_output(
1315                            output,
1316                            codegen_new_line,
1317                            codegen_newline_looking_for_spaces,
1318                            "=",
1319                        );
1320                    } else {
1321                        codegen_output(
1322                            output,
1323                            codegen_new_line,
1324                            codegen_newline_looking_for_spaces,
1325                            " = ",
1326                        );
1327                    }
1328                    *token_lookahead = String::new();
1329                } else {
1330                    let formatted = codegen_format_type(
1331                        target_lang,
1332                        &arg_minus_1.0,
1333                        false,
1334                        false,
1335                    )?;
1336                    if formatted != "generic" && formatted != "genericItem" {
1337                        codegen_initialize_type(
1338                            target_lang,
1339                            &formatted,
1340                            output,
1341                            codegen_new_line,
1342                            codegen_newline_looking_for_spaces,
1343                        )?;
1344                    }
1345                }
1346            }
1347        }
1348        "return" => {
1349            if codegen_arg_list
1350                .iter()
1351                .any(|arg| arg.0.starts_with("ident-r-"))
1352            {
1353                bail!(
1354                    "Sorry, invoking functions isn't available when returning. Please assign the value to a variable and return that."
1355                );
1356            }
1357            codegen_output(
1358                output,
1359                codegen_new_line,
1360                codegen_newline_looking_for_spaces,
1361                "\n",
1362            );
1363            codegen_print_indentation_spaces(
1364                output,
1365                codegen_new_line,
1366                codegen_newline_looking_for_spaces,
1367                codegen_indent,
1368                false,
1369            );
1370            let return_type =
1371                codegen_get_current_routine_type(target_lang, block_stack)?;
1372            if return_type.is_empty() {
1373                bail!("Tried to return, but was not inside a routine!");
1374            }
1375            let formatted_ret_type =
1376                codegen_format_type(target_lang, &return_type, false, false)?;
1377            if target_lang == "js" {
1378                codegen_output(
1379                    output,
1380                    codegen_new_line,
1381                    codegen_newline_looking_for_spaces,
1382                    &format!("{formatted_ret_type}Return = "),
1383                );
1384            } else if target_lang == "bash" {
1385                codegen_output(
1386                    output,
1387                    codegen_new_line,
1388                    codegen_newline_looking_for_spaces,
1389                    &format!("{formatted_ret_type}Return="),
1390                );
1391            }
1392            let last_arg =
1393                codegen_arg_list.last().context("Missing last arg")?;
1394            let last_arg_type = &last_arg.0;
1395            let last_arg_val = &last_arg.1;
1396            if last_arg_type.starts_with("ident-") {
1397                codegen_reference(
1398                    target_lang,
1399                    false,
1400                    last_arg_type,
1401                    last_arg_val,
1402                    output,
1403                    codegen_new_line,
1404                    codegen_newline_looking_for_spaces,
1405                )?;
1406            } else {
1407                codegen_literal(
1408                    target_lang,
1409                    last_arg_type,
1410                    last_arg_val,
1411                    output,
1412                    codegen_new_line,
1413                    codegen_newline_looking_for_spaces,
1414                )?;
1415            }
1416            if typecheck_build {
1417                let formatted_upper = codegen_format_type(
1418                    target_lang,
1419                    &return_type,
1420                    true,
1421                    false,
1422                )?;
1423                let formatted_lower = codegen_format_type(
1424                    target_lang,
1425                    &return_type,
1426                    false,
1427                    false,
1428                )?;
1429                if target_lang == "js" {
1430                    codegen_output(
1431                        output,
1432                        codegen_new_line,
1433                        codegen_newline_looking_for_spaces,
1434                        &format!(
1435                            "; StageL_assertIs{formatted_upper}({formatted_lower}Return); "
1436                        ),
1437                    );
1438                } else if target_lang == "bash" {
1439                    codegen_output(
1440                        output,
1441                        codegen_new_line,
1442                        codegen_newline_looking_for_spaces,
1443                        &format!("; StageL_assertIs{formatted_upper} "),
1444                    );
1445                    codegen_format_argument(
1446                        target_lang,
1447                        &return_type,
1448                        "return",
1449                        output,
1450                        codegen_new_line,
1451                        codegen_newline_looking_for_spaces,
1452                    )?;
1453                    codegen_output(
1454                        output,
1455                        codegen_new_line,
1456                        codegen_newline_looking_for_spaces,
1457                        "; ",
1458                    );
1459                }
1460            } else {
1461                codegen_output(
1462                    output,
1463                    codegen_new_line,
1464                    codegen_newline_looking_for_spaces,
1465                    ";",
1466                );
1467            }
1468            codegen_routine_definition_pre_end(
1469                target_lang,
1470                &return_type,
1471                debug_build,
1472                codegen_indent,
1473                output,
1474                codegen_new_line,
1475                codegen_newline_looking_for_spaces,
1476            )?;
1477            let formatted_lower =
1478                codegen_format_type(target_lang, &return_type, false, false)?;
1479            if target_lang == "js" {
1480                codegen_output(
1481                    output,
1482                    codegen_new_line,
1483                    codegen_newline_looking_for_spaces,
1484                    &format!("return {formatted_lower}Return;\n"),
1485                );
1486            } else if target_lang == "bash" {
1487                codegen_output(
1488                    output,
1489                    codegen_new_line,
1490                    codegen_newline_looking_for_spaces,
1491                    "print ",
1492                );
1493                codegen_format_argument(
1494                    target_lang,
1495                    &return_type,
1496                    "return",
1497                    output,
1498                    codegen_new_line,
1499                    codegen_newline_looking_for_spaces,
1500                )?;
1501                codegen_output(
1502                    output,
1503                    codegen_new_line,
1504                    codegen_newline_looking_for_spaces,
1505                    "\n",
1506                );
1507            }
1508        }
1509        "if" | "elif" | "while" => {
1510            codegen_print_indentation_spaces(
1511                output,
1512                codegen_new_line,
1513                codegen_newline_looking_for_spaces,
1514                codegen_indent,
1515                false,
1516            );
1517            if target_lang == "js" {
1518                if codegen_routine_name == "elif" {
1519                    codegen_output(
1520                        output,
1521                        codegen_new_line,
1522                        codegen_newline_looking_for_spaces,
1523                        "else if (",
1524                    );
1525                } else {
1526                    codegen_output(
1527                        output,
1528                        codegen_new_line,
1529                        codegen_newline_looking_for_spaces,
1530                        &format!("{codegen_routine_name} ("),
1531                    );
1532                }
1533            } else if target_lang == "bash" {
1534                codegen_output(
1535                    output,
1536                    codegen_new_line,
1537                    codegen_newline_looking_for_spaces,
1538                    &format!("{codegen_routine_name} [[ \"true\" == "),
1539                );
1540            }
1541        }
1542        "else" | "debugger" => {
1543            codegen_print_indentation_spaces(
1544                output,
1545                codegen_new_line,
1546                codegen_newline_looking_for_spaces,
1547                codegen_indent,
1548                false,
1549            );
1550            codegen_output(
1551                output,
1552                codegen_new_line,
1553                codegen_newline_looking_for_spaces,
1554                codegen_routine_name,
1555            );
1556        }
1557        "set" => {
1558            codegen_print_indentation_spaces(
1559                output,
1560                codegen_new_line,
1561                codegen_newline_looking_for_spaces,
1562                codegen_indent,
1563                false,
1564            );
1565            let len = codegen_arg_list.len();
1566            if len >= 2 {
1567                let arg_minus_2 = codegen_arg_list
1568                    .get(len.saturating_sub(2))
1569                    .context("Missing arg minus 2")?;
1570                let arg_minus_1 = codegen_arg_list
1571                    .get(len.saturating_sub(1))
1572                    .context("Missing arg minus 1")?;
1573                codegen_reference(
1574                    target_lang,
1575                    true,
1576                    &arg_minus_2.0,
1577                    &arg_minus_2.1,
1578                    output,
1579                    codegen_new_line,
1580                    codegen_newline_looking_for_spaces,
1581                )?;
1582                if target_lang == "js" {
1583                    codegen_output(
1584                        output,
1585                        codegen_new_line,
1586                        codegen_newline_looking_for_spaces,
1587                        " = ",
1588                    );
1589                    codegen_literal(
1590                        target_lang,
1591                        &arg_minus_1.0,
1592                        &arg_minus_1.1,
1593                        output,
1594                        codegen_new_line,
1595                        codegen_newline_looking_for_spaces,
1596                    )?;
1597                    codegen_output(
1598                        output,
1599                        codegen_new_line,
1600                        codegen_newline_looking_for_spaces,
1601                        ";\n",
1602                    );
1603                } else if target_lang == "bash" {
1604                    codegen_output(
1605                        output,
1606                        codegen_new_line,
1607                        codegen_newline_looking_for_spaces,
1608                        "=",
1609                    );
1610                    codegen_literal(
1611                        target_lang,
1612                        &arg_minus_1.0,
1613                        &arg_minus_1.1,
1614                        output,
1615                        codegen_new_line,
1616                        codegen_newline_looking_for_spaces,
1617                    )?;
1618                    codegen_output(
1619                        output,
1620                        codegen_new_line,
1621                        codegen_newline_looking_for_spaces,
1622                        "\n",
1623                    );
1624                }
1625            } else {
1626                let arg_minus_1 = codegen_arg_list
1627                    .get(len.saturating_sub(1))
1628                    .context("Missing arg minus 1")?;
1629                codegen_reference(
1630                    target_lang,
1631                    true,
1632                    &arg_minus_1.0,
1633                    &arg_minus_1.1,
1634                    output,
1635                    codegen_new_line,
1636                    codegen_newline_looking_for_spaces,
1637                )?;
1638                if target_lang == "bash" {
1639                    codegen_output(
1640                        output,
1641                        codegen_new_line,
1642                        codegen_newline_looking_for_spaces,
1643                        "=",
1644                    );
1645                } else {
1646                    codegen_output(
1647                        output,
1648                        codegen_new_line,
1649                        codegen_newline_looking_for_spaces,
1650                        " = ",
1651                    );
1652                }
1653            }
1654        }
1655        _ => {
1656            codegen_print_indentation_spaces(
1657                output,
1658                codegen_new_line,
1659                codegen_newline_looking_for_spaces,
1660                codegen_indent,
1661                false,
1662            );
1663            if target_lang == "js" {
1664                codegen_output(
1665                    output,
1666                    codegen_new_line,
1667                    codegen_newline_looking_for_spaces,
1668                    &format!("StageL_{codegen_routine_name}("),
1669                );
1670            } else if target_lang == "bash" {
1671                if *codegen_new_line {
1672                    codegen_output(
1673                        output,
1674                        codegen_new_line,
1675                        codegen_newline_looking_for_spaces,
1676                        &format!("StageL_{codegen_routine_name} "),
1677                    );
1678                } else {
1679                    codegen_output(
1680                        output,
1681                        codegen_new_line,
1682                        codegen_newline_looking_for_spaces,
1683                        &format!("\"$(StageL_{codegen_routine_name} "),
1684                    );
1685                    *codegen_invocation_level =
1686                        (*codegen_invocation_level).saturating_add(1);
1687                }
1688            }
1689        }
1690    }
1691    codegen_routine_type.clear();
1692    codegen_routine_name.clear();
1693    codegen_arg_list.clear();
1694    Ok(())
1695}
1696
1697pub fn codegen(
1698    tokens_input: &[u8],
1699    target_lang: &str,
1700    debug_build: bool,
1701    typecheck_build: bool,
1702) -> Result<Vec<u8>> {
1703    if target_lang == "parsed" {
1704        return Ok(tokens_input.to_vec());
1705    }
1706
1707    if target_lang != "js" && target_lang != "bash" {
1708        bail!("Target language {target_lang} is not supported");
1709    }
1710
1711    let input_str = std::str::from_utf8(tokens_input)?;
1712    let lines: Vec<&str> = input_str.lines().collect();
1713    let mut tokens = Vec::new();
1714    for chunk in lines.chunks_exact(3) {
1715        tokens.push(Token {
1716            pos: chunk.first().context("Missing pos")?.to_string(),
1717            typ: chunk.get(1).context("Missing typ")?.to_string(),
1718            content: chunk.get(2).context("Missing content")?.to_string(),
1719        });
1720    }
1721
1722    let mut loop_found = true;
1723    while loop_found {
1724        loop_found = false;
1725        for i in 0..tokens.len() {
1726            if tokens.get(i).map(|t| t.typ.as_str()) == Some("loop-block") {
1727                if i >= 1 && i.saturating_add(4) < tokens.len() {
1728                    let loop_src = tokens
1729                        .get(i.saturating_sub(1))
1730                        .context("Missing loop_src")?
1731                        .clone();
1732                    let loop_oper_pos =
1733                        tokens.get(i).context("Missing loop_oper")?.pos.clone();
1734                    let loop_idx = tokens
1735                        .get(i.saturating_add(1))
1736                        .context("Missing loop_idx")?
1737                        .clone();
1738                    let loop_elem = tokens
1739                        .get(i.saturating_add(2))
1740                        .context("Missing loop_elem")?
1741                        .clone();
1742                    let loop_newline = tokens
1743                        .get(i.saturating_add(3))
1744                        .context("Missing loop_newline")?
1745                        .clone();
1746                    let loop_indent = tokens
1747                        .get(i.saturating_add(4))
1748                        .context("Missing loop_indent")?
1749                        .clone();
1750
1751                    if loop_idx.typ != "ident-n" {
1752                        bail!("Loop index identifier must be an integer.");
1753                    }
1754
1755                    let parts: Vec<&str> = loop_indent.pos.split(':').collect();
1756                    // Reason for fallback: unparseable position suffix string defaults indent level to 0
1757                    let indent_level = parts
1758                        .last()
1759                        .and_then(|s| s.parse::<usize>().ok())
1760                        .unwrap_or(0);
1761                    let next_indent = indent_level.saturating_add(1);
1762
1763                    let replace_suffix =
1764                        |pos: &str, new_ind: usize| -> Result<String> {
1765                            if let Some(idx) = pos.rfind(':') {
1766                                Ok(format!(
1767                                    "{}:{}",
1768                                    pos.get(..idx)
1769                                        .context("Invalid pos prefix")?,
1770                                    new_ind
1771                                ))
1772                            } else {
1773                                Ok(pos.to_string())
1774                            }
1775                        };
1776
1777                    let loop_elem_pos_indented =
1778                        replace_suffix(&loop_elem.pos, next_indent)?;
1779                    let loop_idx_pos_indented =
1780                        replace_suffix(&loop_idx.pos, next_indent)?;
1781
1782                    let replacement = vec![
1783                        Token {
1784                            pos: loop_oper_pos.clone(),
1785                            typ: "command".to_string(),
1786                            content: "new".to_string(),
1787                        },
1788                        Token {
1789                            pos: loop_idx.pos.clone(),
1790                            typ: "ident-n".to_string(),
1791                            content: loop_idx.content.clone(),
1792                        },
1793                        Token {
1794                            pos: loop_oper_pos.clone(),
1795                            typ: "newline".to_string(),
1796                            content: String::new(),
1797                        },
1798                        Token {
1799                            pos: loop_oper_pos.clone(),
1800                            typ: "command".to_string(),
1801                            content: "new".to_string(),
1802                        },
1803                        Token {
1804                            pos: loop_elem.pos.clone(),
1805                            typ: loop_elem.typ.clone(),
1806                            content: loop_elem.content.clone(),
1807                        },
1808                        Token {
1809                            pos: loop_oper_pos.clone(),
1810                            typ: "newline".to_string(),
1811                            content: String::new(),
1812                        },
1813                        Token {
1814                            pos: loop_oper_pos.clone(),
1815                            typ: "command".to_string(),
1816                            content: "while".to_string(),
1817                        },
1818                        Token {
1819                            pos: loop_oper_pos.clone(),
1820                            typ: "command".to_string(),
1821                            content: "lt".to_string(),
1822                        },
1823                        Token {
1824                            pos: loop_oper_pos.clone(),
1825                            typ: "ident-n".to_string(),
1826                            content: loop_idx.content.clone(),
1827                        },
1828                        Token {
1829                            pos: loop_oper_pos.clone(),
1830                            typ: "command".to_string(),
1831                            content: "count".to_string(),
1832                        },
1833                        Token {
1834                            pos: loop_src.pos.clone(),
1835                            typ: loop_src.typ.clone(),
1836                            content: loop_src.content.clone(),
1837                        },
1838                        Token {
1839                            pos: loop_newline.pos.clone(),
1840                            typ: "newline".to_string(),
1841                            content: String::new(),
1842                        },
1843                        Token {
1844                            pos: loop_indent.pos.clone(),
1845                            typ: "indent".to_string(),
1846                            content: String::new(),
1847                        },
1848                        Token {
1849                            pos: loop_elem_pos_indented.clone(),
1850                            typ: "command".to_string(),
1851                            content: "set".to_string(),
1852                        },
1853                        Token {
1854                            pos: loop_elem_pos_indented.clone(),
1855                            typ: loop_elem.typ.clone(),
1856                            content: loop_elem.content.clone(),
1857                        },
1858                        Token {
1859                            pos: loop_elem_pos_indented.clone(),
1860                            typ: "command".to_string(),
1861                            content: "get".to_string(),
1862                        },
1863                        Token {
1864                            pos: loop_elem_pos_indented.clone(),
1865                            typ: loop_src.typ.clone(),
1866                            content: loop_src.content.clone(),
1867                        },
1868                        Token {
1869                            pos: loop_elem_pos_indented.clone(),
1870                            typ: "ident-n".to_string(),
1871                            content: loop_idx.content.clone(),
1872                        },
1873                        Token {
1874                            pos: loop_elem_pos_indented.clone(),
1875                            typ: "newline".to_string(),
1876                            content: String::new(),
1877                        },
1878                        Token {
1879                            pos: loop_idx_pos_indented.clone(),
1880                            typ: "command".to_string(),
1881                            content: "set".to_string(),
1882                        },
1883                        Token {
1884                            pos: loop_idx_pos_indented.clone(),
1885                            typ: "ident-n".to_string(),
1886                            content: loop_idx.content.clone(),
1887                        },
1888                        Token {
1889                            pos: loop_idx_pos_indented.clone(),
1890                            typ: "command".to_string(),
1891                            content: "inc".to_string(),
1892                        },
1893                        Token {
1894                            pos: loop_idx_pos_indented.clone(),
1895                            typ: "ident-n".to_string(),
1896                            content: loop_idx.content.clone(),
1897                        },
1898                        Token {
1899                            pos: loop_idx_pos_indented.clone(),
1900                            typ: "newline".to_string(),
1901                            content: String::new(),
1902                        },
1903                    ];
1904
1905                    let start_idx = i.saturating_sub(1);
1906                    let end_idx = i.saturating_add(4);
1907                    tokens.splice(start_idx..=end_idx, replacement);
1908                    loop_found = true;
1909                    break;
1910                }
1911            }
1912        }
1913    }
1914
1915    let mut codegen_last_known_arglist_count = 0;
1916    let mut codegen_routine_type = String::new();
1917    let mut codegen_routine_name = String::new();
1918    let mut codegen_invocation_level = 0;
1919    let mut codegen_arg_list: Vec<(String, String)> = Vec::new();
1920    let mut codegen_new_line = true;
1921    let mut codegen_newline_looking_for_spaces = true;
1922    let mut codegen_test_indent_deferred = false;
1923    let mut codegen_array_literal = String::new();
1924    let mut state_stack = vec!["root".to_string(), "code".to_string()];
1925    let mut block_stack = vec![("root".to_string(), String::new())];
1926    let mut test_parameter_found = false;
1927    let mut filename = String::new();
1928    let mut output = String::new();
1929
1930    let mut j = 0;
1931    while j < tokens.len() {
1932        let current_token = tokens.get(j).context("Missing current token")?;
1933        let next_token_content = tokens
1934            .get(j.saturating_add(1))
1935            // Reason for fallback: out of bounds lookahead token index defaults next token content string to empty
1936            .map_or("", |t| t.content.as_str());
1937        let mut token_lookahead = tokens
1938            .get(j.saturating_add(1))
1939            .map(|t| t.typ.clone())
1940            // Reason for fallback: out of bounds lookahead token index defaults next token type string to empty
1941            .unwrap_or_default();
1942
1943        let mut codegen_indent = current_token
1944            .pos
1945            .split(':')
1946            .next_back()
1947            .and_then(|s| s.parse::<usize>().ok())
1948            // Reason for fallback: unparseable position suffix string defaults token indent level to 0
1949            .unwrap_or(0);
1950
1951        if current_token.typ == "filename" {
1952            filename.clone_from(&current_token.content);
1953        } else if current_token.typ == "comment"
1954            && state_stack.last().map(String::as_str) != Some("arglist")
1955            && !state_stack
1956                .last()
1957                .is_some_and(|s| s.starts_with("literal-a"))
1958        {
1959            codegen_comment(
1960                target_lang,
1961                &ascii_dec_list_to_text(&current_token.content),
1962                codegen_indent,
1963                &mut output,
1964                &mut codegen_new_line,
1965                &mut codegen_newline_looking_for_spaces,
1966            )?;
1967        } else if current_token.typ == "literal-ab-start" {
1968            codegen_array_literal.push_str(&codegen_start_array(
1969                target_lang,
1970                &state_stack,
1971                &block_stack,
1972                "b",
1973            ));
1974            state_stack.push("literal-ab".to_string());
1975        } else if current_token.typ == "literal-an-start" {
1976            codegen_array_literal.push_str(&codegen_start_array(
1977                target_lang,
1978                &state_stack,
1979                &block_stack,
1980                "n",
1981            ));
1982            state_stack.push("literal-an".to_string());
1983        } else if current_token.typ == "literal-as-start" {
1984            codegen_array_literal.push_str(&codegen_start_array(
1985                target_lang,
1986                &state_stack,
1987                &block_stack,
1988                "s",
1989            ));
1990            state_stack.push("literal-as".to_string());
1991        } else {
1992            // Reason for fallback: empty state stack defaults current state string to empty
1993            let current_state = state_stack.last().cloned().unwrap_or_default();
1994            match current_state.as_str() {
1995                "literal-ab" => match current_token.typ.as_str() {
1996                    "literal-ab-end" => {
1997                        codegen_array_literal.push_str(&codegen_end_array(
1998                            target_lang,
1999                            &state_stack,
2000                            &block_stack,
2001                        ));
2002                        state_stack.pop();
2003                        j = j.saturating_sub(1);
2004                    }
2005                    "literal-b" => {
2006                        let mut lit = String::new();
2007                        codegen_literal(
2008                            target_lang,
2009                            &current_token.typ,
2010                            &current_token.content,
2011                            &mut lit,
2012                            &mut false,
2013                            &mut false,
2014                        )?;
2015                        codegen_array_literal.push_str(&lit);
2016                        if tokens.get(j.saturating_add(1)).is_some_and(|t| {
2017                            t.typ == "literal-b" || t.typ == "ident-b"
2018                        }) {
2019                            codegen_array_literal.push_str(
2020                                &codegen_array_entry_delimiter(
2021                                    target_lang,
2022                                    false,
2023                                ),
2024                            );
2025                        }
2026                    }
2027                    "ident-b" => {
2028                        let mut lit = String::new();
2029                        codegen_reference(
2030                            target_lang,
2031                            false,
2032                            &current_token.typ,
2033                            &current_token.content,
2034                            &mut lit,
2035                            &mut false,
2036                            &mut false,
2037                        )?;
2038                        codegen_array_literal.push_str(&lit);
2039                        if tokens.get(j.saturating_add(1)).is_some_and(|t| {
2040                            t.typ == "literal-b" || t.typ == "ident-b"
2041                        }) {
2042                            codegen_array_literal.push_str(
2043                                &codegen_array_entry_delimiter(
2044                                    target_lang,
2045                                    false,
2046                                ),
2047                            );
2048                        }
2049                    }
2050                    "newline" => {
2051                        codegen_array_literal.push_str(
2052                            &codegen_array_entry_delimiter(target_lang, true),
2053                        );
2054                        codegen_array_literal.push('\n');
2055                        for _ in 0..codegen_indent {
2056                            codegen_array_literal.push_str("    ");
2057                        }
2058                    }
2059                    _ => bail!(
2060                        "Unexpected token {} in array of booleans.",
2061                        current_token.typ
2062                    ),
2063                },
2064                "literal-an" => match current_token.typ.as_str() {
2065                    "literal-an-end" => {
2066                        codegen_array_literal.push_str(&codegen_end_array(
2067                            target_lang,
2068                            &state_stack,
2069                            &block_stack,
2070                        ));
2071                        state_stack.pop();
2072                        j = j.saturating_sub(1);
2073                    }
2074                    "literal-n" => {
2075                        let mut lit = String::new();
2076                        codegen_literal(
2077                            target_lang,
2078                            &current_token.typ,
2079                            &current_token.content,
2080                            &mut lit,
2081                            &mut false,
2082                            &mut false,
2083                        )?;
2084                        codegen_array_literal.push_str(&lit);
2085                        if tokens.get(j.saturating_add(1)).is_some_and(|t| {
2086                            t.typ == "literal-n" || t.typ == "ident-n"
2087                        }) {
2088                            codegen_array_literal.push_str(
2089                                &codegen_array_entry_delimiter(
2090                                    target_lang,
2091                                    false,
2092                                ),
2093                            );
2094                        }
2095                    }
2096                    "ident-n" => {
2097                        let mut lit = String::new();
2098                        codegen_reference(
2099                            target_lang,
2100                            false,
2101                            &current_token.typ,
2102                            &current_token.content,
2103                            &mut lit,
2104                            &mut false,
2105                            &mut false,
2106                        )?;
2107                        codegen_array_literal.push_str(&lit);
2108                        if tokens.get(j.saturating_add(1)).is_some_and(|t| {
2109                            t.typ == "literal-n" || t.typ == "ident-n"
2110                        }) {
2111                            codegen_array_literal.push_str(
2112                                &codegen_array_entry_delimiter(
2113                                    target_lang,
2114                                    false,
2115                                ),
2116                            );
2117                        }
2118                    }
2119                    "newline" => {
2120                        codegen_array_literal.push_str(
2121                            &codegen_array_entry_delimiter(target_lang, true),
2122                        );
2123                        codegen_array_literal.push('\n');
2124                        for _ in 0..codegen_indent {
2125                            codegen_array_literal.push_str("    ");
2126                        }
2127                    }
2128                    _ => bail!(
2129                        "Unexpected token {} in array of numbers.",
2130                        current_token.typ
2131                    ),
2132                },
2133                "literal-as" => match current_token.typ.as_str() {
2134                    "literal-as-end" => {
2135                        codegen_array_literal.push_str(&codegen_end_array(
2136                            target_lang,
2137                            &state_stack,
2138                            &block_stack,
2139                        ));
2140                        state_stack.pop();
2141                        j = j.saturating_sub(1);
2142                    }
2143                    "literal-s" => {
2144                        let mut lit = String::new();
2145                        codegen_literal(
2146                            target_lang,
2147                            &current_token.typ,
2148                            &current_token.content,
2149                            &mut lit,
2150                            &mut false,
2151                            &mut false,
2152                        )?;
2153                        codegen_array_literal.push_str(&lit);
2154                        if tokens.get(j.saturating_add(1)).is_some_and(|t| {
2155                            t.typ == "literal-s" || t.typ == "ident-s"
2156                        }) {
2157                            codegen_array_literal.push_str(
2158                                &codegen_array_entry_delimiter(
2159                                    target_lang,
2160                                    false,
2161                                ),
2162                            );
2163                        }
2164                    }
2165                    "ident-s" => {
2166                        let mut lit = String::new();
2167                        codegen_reference(
2168                            target_lang,
2169                            false,
2170                            &current_token.typ,
2171                            &current_token.content,
2172                            &mut lit,
2173                            &mut false,
2174                            &mut false,
2175                        )?;
2176                        codegen_array_literal.push_str(&lit);
2177                        if tokens.get(j.saturating_add(1)).is_some_and(|t| {
2178                            t.typ == "literal-s" || t.typ == "ident-s"
2179                        }) {
2180                            codegen_array_literal.push_str(
2181                                &codegen_array_entry_delimiter(
2182                                    target_lang,
2183                                    false,
2184                                ),
2185                            );
2186                        }
2187                    }
2188                    "newline" => {
2189                        codegen_array_literal.push_str(
2190                            &codegen_array_entry_delimiter(target_lang, true),
2191                        );
2192                        codegen_array_literal.push('\n');
2193                        for _ in 0..codegen_indent {
2194                            codegen_array_literal.push_str("    ");
2195                        }
2196                    }
2197                    _ => bail!(
2198                        "Unexpected token {} in array of strings.",
2199                        current_token.typ
2200                    ),
2201                },
2202                "code" => match current_token.typ.as_str() {
2203                    "start-document" => {}
2204                    "end-document" => {
2205                        state_stack.pop();
2206                        j = j.saturating_sub(1);
2207                    }
2208                    "indent" => {
2209                        codegen_indent_action(
2210                            target_lang,
2211                            codegen_indent,
2212                            &mut output,
2213                            &mut codegen_new_line,
2214                            &mut codegen_newline_looking_for_spaces,
2215                        )?;
2216                        state_stack.push("code".to_string());
2217                        block_stack
2218                            .push(("plain-block".to_string(), String::new()));
2219                    }
2220                    "dedent" => {
2221                        if let Some(last_block) = block_stack.last() {
2222                            if last_block.0 == "ident-r-v" {
2223                                codegen_routine_definition_pre_end(
2224                                    target_lang,
2225                                    &last_block.0,
2226                                    debug_build,
2227                                    codegen_indent,
2228                                    &mut output,
2229                                    &mut codegen_new_line,
2230                                    &mut codegen_newline_looking_for_spaces,
2231                                )?;
2232                            }
2233                        }
2234                        codegen_dedent_action(
2235                            target_lang,
2236                            codegen_indent,
2237                            &block_stack,
2238                            next_token_content,
2239                            &mut output,
2240                            &mut codegen_new_line,
2241                            &mut codegen_newline_looking_for_spaces,
2242                        )?;
2243                        state_stack.pop();
2244                        block_stack_remove_last(&mut block_stack)?;
2245                        if block_stack
2246                            .last()
2247                            .is_some_and(|b| b.0.starts_with("test-body-"))
2248                        {
2249                            block_stack_remove_last(&mut block_stack)?;
2250                        }
2251                    }
2252                    typ if typ.starts_with("ident-r-") => {
2253                        codegen_routine_name =
2254                            ascii_dec_list_to_text(&current_token.content);
2255                        if j >= 1
2256                            && tokens.get(j.saturating_sub(1)).is_some_and(
2257                                |t| {
2258                                    t.typ != "start-document"
2259                                        && t.typ != "filename"
2260                                },
2261                            )
2262                        {
2263                            codegen_output(
2264                                &mut output,
2265                                &mut codegen_new_line,
2266                                &mut codegen_newline_looking_for_spaces,
2267                                "\n",
2268                            );
2269                        }
2270                        codegen_routine_type = current_token.typ.clone();
2271                        state_stack.push("routine-definition".to_string());
2272                        block_stack.push((
2273                            current_token.typ.clone(),
2274                            current_token.content.clone(),
2275                        ));
2276                    }
2277                    "command" => {
2278                        codegen_routine_name = current_token.content.clone();
2279                        match current_token.content.as_str() {
2280                            "if" | "elif" | "else" | "while" => {
2281                                if current_token.content == "else" {
2282                                    block_stack.push((
2283                                        format!(
2284                                            "test-body-{}",
2285                                            current_token.content
2286                                        ),
2287                                        String::new(),
2288                                    ));
2289                                    codegen_command_invocation_start(
2290                                        target_lang,
2291                                        &mut codegen_routine_name,
2292                                        &mut codegen_routine_type,
2293                                        &mut codegen_arg_list,
2294                                        &block_stack,
2295                                        &state_stack,
2296                                        typecheck_build,
2297                                        codegen_indent,
2298                                        &mut codegen_invocation_level,
2299                                        &mut token_lookahead,
2300                                        debug_build,
2301                                        &mut output,
2302                                        &mut codegen_new_line,
2303                                        &mut codegen_newline_looking_for_spaces,
2304                                    )?;
2305                                } else {
2306                                    state_stack.push("test".to_string());
2307                                    block_stack.push((
2308                                        format!(
2309                                            "test-body-{}",
2310                                            current_token.content
2311                                        ),
2312                                        String::new(),
2313                                    ));
2314                                    block_stack.push((
2315                                        "test".to_string(),
2316                                        current_token.content.clone(),
2317                                    ));
2318                                    codegen_command_invocation_start(
2319                                        target_lang,
2320                                        &mut codegen_routine_name,
2321                                        &mut codegen_routine_type,
2322                                        &mut codegen_arg_list,
2323                                        &block_stack,
2324                                        &state_stack,
2325                                        typecheck_build,
2326                                        codegen_indent,
2327                                        &mut codegen_invocation_level,
2328                                        &mut token_lookahead,
2329                                        debug_build,
2330                                        &mut output,
2331                                        &mut codegen_new_line,
2332                                        &mut codegen_newline_looking_for_spaces,
2333                                    )?;
2334                                }
2335                            }
2336                            "new" | "set" => {
2337                                state_stack.push("arglist".to_string());
2338                                block_stack.push((
2339                                    "command".to_string(),
2340                                    current_token.content.clone(),
2341                                ));
2342                                state_stack.push(
2343                                    "identifier-command-argument-accumulation"
2344                                        .to_string(),
2345                                );
2346                            }
2347                            "return" => {
2348                                state_stack.push("oneshot-command".to_string());
2349                            }
2350                            _ => {
2351                                state_stack.push("arglist".to_string());
2352                                block_stack.push((
2353                                    "command".to_string(),
2354                                    current_token.content.clone(),
2355                                ));
2356                                codegen_command_invocation_start(
2357                                    target_lang,
2358                                    &mut codegen_routine_name,
2359                                    &mut codegen_routine_type,
2360                                    &mut codegen_arg_list,
2361                                    &block_stack,
2362                                    &state_stack,
2363                                    typecheck_build,
2364                                    codegen_indent,
2365                                    &mut codegen_invocation_level,
2366                                    &mut token_lookahead,
2367                                    debug_build,
2368                                    &mut output,
2369                                    &mut codegen_new_line,
2370                                    &mut codegen_newline_looking_for_spaces,
2371                                )?;
2372                            }
2373                        }
2374                    }
2375                    "newline" => {}
2376                    _ => bail!(
2377                        "A {}, {}, isn't allowed here, in {} {}.",
2378                        current_token.typ,
2379                        current_token.content,
2380                        // Reason for fallback: empty block stack defaults grandparent or parent block type string to empty
2381                        block_stack
2382                            .get(block_stack.len().saturating_sub(2))
2383                            .map_or("", |x| x.0.as_str()),
2384                        // Reason for fallback: empty block stack defaults grandparent or parent block type string to empty
2385                        block_stack.last().map_or("", |x| x.0.as_str())
2386                    ),
2387                },
2388                "oneshot-command" => {
2389                    let is_arr_end = current_token.typ.starts_with("literal-a")
2390                        && current_token.typ.ends_with("-end");
2391                    if is_arr_end {
2392                        codegen_arg_list.push((
2393                            current_token.typ.clone(),
2394                            codegen_array_literal.clone(),
2395                        ));
2396                        codegen_array_literal = String::new();
2397                    } else if current_token.typ.starts_with("literal-") {
2398                        codegen_arg_list.push((
2399                            current_token.typ.clone(),
2400                            current_token.content.clone(),
2401                        ));
2402                    } else if current_token.typ.starts_with("ident-") {
2403                        codegen_arg_list.push((
2404                            current_token.typ.clone(),
2405                            ascii_dec_list_to_text(&current_token.content),
2406                        ));
2407                    } else {
2408                        codegen_command_invocation_start(
2409                            target_lang,
2410                            &mut codegen_routine_name,
2411                            &mut codegen_routine_type,
2412                            &mut codegen_arg_list,
2413                            &block_stack,
2414                            &state_stack,
2415                            typecheck_build,
2416                            codegen_indent,
2417                            &mut codegen_invocation_level,
2418                            &mut token_lookahead,
2419                            debug_build,
2420                            &mut output,
2421                            &mut codegen_new_line,
2422                            &mut codegen_newline_looking_for_spaces,
2423                        )?;
2424                        state_stack.pop();
2425                        j = j.saturating_sub(1);
2426                    }
2427                }
2428                "identifier-command-argument-accumulation" => {
2429                    if current_token.typ.starts_with("ident-") {
2430                        codegen_arg_list.push((
2431                            current_token.typ.clone(),
2432                            ascii_dec_list_to_text(&current_token.content),
2433                        ));
2434                        state_stack.pop();
2435                        token_lookahead = tokens
2436                            .get(j.saturating_add(1))
2437                            .map(|t| t.typ.clone())
2438                            // Reason for fallback: out of bounds lookahead token index defaults token type string to empty
2439                            .unwrap_or_default();
2440                        codegen_command_invocation_start(
2441                            target_lang,
2442                            &mut codegen_routine_name,
2443                            &mut codegen_routine_type,
2444                            &mut codegen_arg_list,
2445                            &block_stack,
2446                            &state_stack,
2447                            typecheck_build,
2448                            codegen_indent,
2449                            &mut codegen_invocation_level,
2450                            &mut token_lookahead,
2451                            debug_build,
2452                            &mut output,
2453                            &mut codegen_new_line,
2454                            &mut codegen_newline_looking_for_spaces,
2455                        )?;
2456                    } else {
2457                        bail!(
2458                            "A {} {} wants an identifier here, not a {}.",
2459                            // Reason for fallback: empty block stack defaults grandparent or parent block type string to empty
2460                            block_stack
2461                                .get(block_stack.len().saturating_sub(2))
2462                                .map_or("", |x| x.0.as_str()),
2463                            // Reason for fallback: empty block stack defaults grandparent or parent block type string to empty
2464                            block_stack.last().map_or("", |x| x.0.as_str()),
2465                            current_token.typ
2466                        );
2467                    }
2468                }
2469                "arglist" | "test" => {
2470                    let is_arr_end = current_token.typ.starts_with("literal-a")
2471                        && current_token.typ.ends_with("-end");
2472                    if is_arr_end {
2473                        codegen_arg_list.push((
2474                            current_token.typ.clone(),
2475                            codegen_array_literal.clone(),
2476                        ));
2477                        codegen_array_literal = String::new();
2478                    } else if current_token.typ.starts_with("literal-") {
2479                        if current_state == "test" && test_parameter_found {
2480                            bail!(
2481                                "Multiple literals (in this case, the {} \"{}\") provided as parameters for a test-style construct.",
2482                                current_token.typ,
2483                                current_token.content
2484                            );
2485                        }
2486                        if current_state == "test" {
2487                            test_parameter_found = true;
2488                        }
2489                        codegen_arg_list.push((
2490                            current_token.typ.clone(),
2491                            current_token.content.clone(),
2492                        ));
2493                    } else if current_token.typ == "command"
2494                        || current_token.typ.starts_with("ident-r-")
2495                    {
2496                        let cond1 = current_token.content == "return"
2497                            || current_token.content == "new"
2498                            || current_token.content == "set";
2499                        let cond2 =
2500                            current_state == "test" && test_parameter_found;
2501                        if cond1 || cond2 {
2502                            codegen_command_invocation_arglist(
2503                                target_lang,
2504                                &mut codegen_routine_type,
2505                                &mut codegen_routine_name,
2506                                &mut codegen_arg_list,
2507                                &mut codegen_last_known_arglist_count,
2508                                &mut output,
2509                                &mut codegen_new_line,
2510                                &mut codegen_newline_looking_for_spaces,
2511                            )?;
2512                            codegen_command_invocation_end(
2513                                target_lang,
2514                                &mut codegen_routine_type,
2515                                &mut codegen_routine_name,
2516                                &mut codegen_arg_list,
2517                                &mut block_stack,
2518                                &state_stack,
2519                                &mut codegen_invocation_level,
2520                                &mut output,
2521                                &mut codegen_new_line,
2522                                &mut codegen_newline_looking_for_spaces,
2523                            )?;
2524                            if current_state == "test" {
2525                                test_parameter_found = false;
2526                            }
2527                            state_stack.pop();
2528                            j = j.saturating_sub(1);
2529                            if codegen_test_indent_deferred {
2530                                codegen_indent_action(
2531                                    target_lang,
2532                                    codegen_indent,
2533                                    &mut output,
2534                                    &mut codegen_new_line,
2535                                    &mut codegen_newline_looking_for_spaces,
2536                                )?;
2537                                codegen_test_indent_deferred = false;
2538                                state_stack.push("code".to_string());
2539                                block_stack.push((
2540                                    "plain-block".to_string(),
2541                                    String::new(),
2542                                ));
2543                            }
2544                        } else {
2545                            if current_state != "test" {
2546                                codegen_command_invocation_arglist(
2547                                    target_lang,
2548                                    &mut codegen_routine_type,
2549                                    &mut codegen_routine_name,
2550                                    &mut codegen_arg_list,
2551                                    &mut codegen_last_known_arglist_count,
2552                                    &mut output,
2553                                    &mut codegen_new_line,
2554                                    &mut codegen_newline_looking_for_spaces,
2555                                )?;
2556                                if !tokens.get(j.saturating_sub(1)).is_some_and(
2557                                    |t| codegen_is_test_command(&t.content),
2558                                ) {
2559                                    if codegen_last_known_arglist_count != 0 {
2560                                        codegen_command_invocation_arg_separator(target_lang, &mut output, &mut codegen_new_line, &mut codegen_newline_looking_for_spaces)?;
2561                                    }
2562                                }
2563                            }
2564                            codegen_routine_name =
2565                                current_token.content.clone();
2566                            if current_token.typ.starts_with("ident-r-") {
2567                                codegen_routine_name = ascii_dec_list_to_text(
2568                                    &current_token.content,
2569                                );
2570                            }
2571                            codegen_command_invocation_start(
2572                                target_lang,
2573                                &mut codegen_routine_name,
2574                                &mut codegen_routine_type,
2575                                &mut codegen_arg_list,
2576                                &block_stack,
2577                                &state_stack,
2578                                typecheck_build,
2579                                codegen_indent,
2580                                &mut codegen_invocation_level,
2581                                &mut token_lookahead,
2582                                debug_build,
2583                                &mut output,
2584                                &mut codegen_new_line,
2585                                &mut codegen_newline_looking_for_spaces,
2586                            )?;
2587                            if current_state == "test" {
2588                                test_parameter_found = true;
2589                            }
2590                            state_stack.push("arglist".to_string());
2591                            block_stack.push((
2592                                "arglist-command".to_string(),
2593                                current_token.content.clone(),
2594                            ));
2595                        }
2596                    } else if current_token.typ.starts_with("ident-") {
2597                        if current_state == "test" && test_parameter_found {
2598                            bail!(
2599                                "Multiple identifiers (in this case, the {} \"{}\") provided as parameters for a test-style construct.",
2600                                current_token.typ,
2601                                current_token.content
2602                            );
2603                        }
2604                        if current_state == "test" {
2605                            test_parameter_found = true;
2606                        }
2607                        codegen_arg_list.push((
2608                            current_token.typ.clone(),
2609                            ascii_dec_list_to_text(&current_token.content),
2610                        ));
2611                    } else if current_token.typ == "indent" {
2612                        if test_parameter_found {
2613                            if current_state == "test" {
2614                                test_parameter_found = false;
2615                            }
2616                            codegen_command_invocation_arglist(
2617                                target_lang,
2618                                &mut codegen_routine_type,
2619                                &mut codegen_routine_name,
2620                                &mut codegen_arg_list,
2621                                &mut codegen_last_known_arglist_count,
2622                                &mut output,
2623                                &mut codegen_new_line,
2624                                &mut codegen_newline_looking_for_spaces,
2625                            )?;
2626                            codegen_command_invocation_end(
2627                                target_lang,
2628                                &mut codegen_routine_type,
2629                                &mut codegen_routine_name,
2630                                &mut codegen_arg_list,
2631                                &mut block_stack,
2632                                &state_stack,
2633                                &mut codegen_invocation_level,
2634                                &mut output,
2635                                &mut codegen_new_line,
2636                                &mut codegen_newline_looking_for_spaces,
2637                            )?;
2638                            state_stack.pop();
2639                            if codegen_test_indent_deferred {
2640                                codegen_indent_action(
2641                                    target_lang,
2642                                    codegen_indent,
2643                                    &mut output,
2644                                    &mut codegen_new_line,
2645                                    &mut codegen_newline_looking_for_spaces,
2646                                )?;
2647                                codegen_test_indent_deferred = false;
2648                                state_stack.push("code".to_string());
2649                                block_stack.push((
2650                                    "plain-block".to_string(),
2651                                    String::new(),
2652                                ));
2653                            }
2654                            j = j.saturating_sub(1);
2655                        }
2656                    } else if current_token.typ == "newline" {
2657                        if current_state != "test" {
2658                            if block_stack.last().is_none_or(|b| b.0 != "else")
2659                            {
2660                                codegen_command_invocation_arglist(
2661                                    target_lang,
2662                                    &mut codegen_routine_type,
2663                                    &mut codegen_routine_name,
2664                                    &mut codegen_arg_list,
2665                                    &mut codegen_last_known_arglist_count,
2666                                    &mut output,
2667                                    &mut codegen_new_line,
2668                                    &mut codegen_newline_looking_for_spaces,
2669                                )?;
2670                            }
2671                            codegen_command_invocation_end(
2672                                target_lang,
2673                                &mut codegen_routine_type,
2674                                &mut codegen_routine_name,
2675                                &mut codegen_arg_list,
2676                                &mut block_stack,
2677                                &state_stack,
2678                                &mut codegen_invocation_level,
2679                                &mut output,
2680                                &mut codegen_new_line,
2681                                &mut codegen_newline_looking_for_spaces,
2682                            )?;
2683                            state_stack.pop();
2684                            j = j.saturating_sub(1);
2685                        }
2686                        if current_state == "test" && !test_parameter_found {
2687                            codegen_output(
2688                                &mut output,
2689                                &mut codegen_new_line,
2690                                &mut codegen_newline_looking_for_spaces,
2691                                "\n",
2692                            );
2693                            codegen_test_indent_deferred = true;
2694                        }
2695                    } else if current_token.typ == "inline-arglist-end" {
2696                        codegen_command_invocation_arglist(
2697                            target_lang,
2698                            &mut codegen_routine_type,
2699                            &mut codegen_routine_name,
2700                            &mut codegen_arg_list,
2701                            &mut codegen_last_known_arglist_count,
2702                            &mut output,
2703                            &mut codegen_new_line,
2704                            &mut codegen_newline_looking_for_spaces,
2705                        )?;
2706                        codegen_command_invocation_end(
2707                            target_lang,
2708                            &mut codegen_routine_type,
2709                            &mut codegen_routine_name,
2710                            &mut codegen_arg_list,
2711                            &mut block_stack,
2712                            &state_stack,
2713                            &mut codegen_invocation_level,
2714                            &mut output,
2715                            &mut codegen_new_line,
2716                            &mut codegen_newline_looking_for_spaces,
2717                        )?;
2718                        codegen_command_invocation_arg_separator(
2719                            target_lang,
2720                            &mut output,
2721                            &mut codegen_new_line,
2722                            &mut codegen_newline_looking_for_spaces,
2723                        )?;
2724                        state_stack.pop();
2725                    } else {
2726                        codegen_command_invocation_arglist(
2727                            target_lang,
2728                            &mut codegen_routine_type,
2729                            &mut codegen_routine_name,
2730                            &mut codegen_arg_list,
2731                            &mut codegen_last_known_arglist_count,
2732                            &mut output,
2733                            &mut codegen_new_line,
2734                            &mut codegen_newline_looking_for_spaces,
2735                        )?;
2736                        codegen_command_invocation_end(
2737                            target_lang,
2738                            &mut codegen_routine_type,
2739                            &mut codegen_routine_name,
2740                            &mut codegen_arg_list,
2741                            &mut block_stack,
2742                            &state_stack,
2743                            &mut codegen_invocation_level,
2744                            &mut output,
2745                            &mut codegen_new_line,
2746                            &mut codegen_newline_looking_for_spaces,
2747                        )?;
2748                        state_stack.pop();
2749                        j = j.saturating_sub(1);
2750                        if current_state == "test" {
2751                            test_parameter_found = false;
2752                        }
2753                        state_stack.push("code".to_string());
2754                    }
2755                }
2756                "routine-definition" => {
2757                    if current_token.typ.starts_with("ident-") {
2758                        codegen_arg_list.push((
2759                            current_token.typ.clone(),
2760                            ascii_dec_list_to_text(&current_token.content),
2761                        ));
2762                    } else if current_token.typ == "indent"
2763                        || current_token.typ == "newline"
2764                    {
2765                        codegen_routine_definition_start(
2766                            target_lang,
2767                            &mut codegen_routine_name,
2768                            &mut codegen_routine_type,
2769                            &mut codegen_arg_list,
2770                            &filename,
2771                            debug_build,
2772                            typecheck_build,
2773                            &mut codegen_indent,
2774                            &mut output,
2775                            &mut codegen_new_line,
2776                            &mut codegen_newline_looking_for_spaces,
2777                        )?;
2778                        if let Some(last_state) = state_stack.last_mut() {
2779                            *last_state = "routine-definition-end".to_string();
2780                        }
2781                        state_stack.push("code".to_string());
2782                        if current_token.typ == "newline"
2783                            && tokens
2784                                .get(j.saturating_add(1))
2785                                .is_some_and(|t| t.typ == "indent")
2786                        {
2787                            j = j.saturating_add(1);
2788                        }
2789                    } else {
2790                        bail!(
2791                            "Routine definition unexpected token type {}",
2792                            current_token.typ
2793                        );
2794                    }
2795                }
2796                "routine-definition-end" => {
2797                    state_stack.pop();
2798                    j = j.saturating_sub(1);
2799                }
2800                "root" => {}
2801                _ => {
2802                    bail!("Unimplemented code generation state {current_state}")
2803                }
2804            }
2805        }
2806
2807        j = j.saturating_add(1);
2808    }
2809
2810    if block_stack.len() != 1
2811        || block_stack
2812            .first()
2813            .is_none_or(|b| b.0 != "root" || !b.1.is_empty())
2814    {
2815        bail!(
2816            "Internal error: not all blocks were consumed! block stack: {block_stack:?}"
2817        );
2818    }
2819
2820    Ok(output.into_bytes())
2821}
2822
2823#[cfg(test)]
2824#[allow(
2825    clippy::panic,
2826    clippy::expect_used,
2827    clippy::unwrap_used,
2828    clippy::unwrap_in_result,
2829    clippy::panic_in_result_fn,
2830    clippy::indexing_slicing,
2831    clippy::arithmetic_side_effects,
2832    reason = "Standard repository test boilerplate"
2833)]
2834mod tests {
2835    use crate::get_stagel_data;
2836
2837    use super::*;
2838
2839    #[crate::ctb_test]
2840    fn test_parse_and_codegen() {
2841        // Load fixture files from data/fixtures
2842        let html_content =
2843            get_stagel_data("fixtures/format-html.stagel").unwrap();
2844
2845        let parsed_html =
2846            crate::parse::parse(&html_content, "format-html").unwrap();
2847
2848        // Output parsed result
2849        assert!(!parsed_html.is_empty());
2850
2851        let js_code = codegen(&parsed_html, "js", true, true).unwrap();
2852        let js_str = String::from_utf8(js_code).unwrap();
2853        assert!(js_str.contains("async function dcaToHtml("));
2854
2855        let bash_code = codegen(&parsed_html, "bash", true, true).unwrap();
2856        let bash_str = String::from_utf8(bash_code).unwrap();
2857        assert!(bash_str.contains("dcaToHtml() {"));
2858    }
2859
2860    #[crate::ctb_test]
2861    fn test_parse_and_codegen_ascii() {
2862        let ascii_content =
2863            get_stagel_data("fixtures/format-ascii.stagel").unwrap();
2864
2865        let parsed_ascii =
2866            crate::parse::parse(&ascii_content, "format-ascii").unwrap();
2867        assert!(!parsed_ascii.is_empty());
2868
2869        let js_code = codegen(&parsed_ascii, "js", true, true).unwrap();
2870        let js_str = String::from_utf8(js_code).unwrap();
2871        assert!(js_str.contains("async function dcaFromAscii("));
2872        assert!(js_str.contains("async function dcaToAscii("));
2873
2874        let bash_code = codegen(&parsed_ascii, "bash", true, true).unwrap();
2875        let bash_str = String::from_utf8(bash_code).unwrap();
2876        assert!(bash_str.contains("dcaFromAscii() {"));
2877        assert!(bash_str.contains("dcaToAscii() {"));
2878    }
2879
2880    fn compare_fixture(base_name: &str) {
2881        let input_path = format!("fixtures/{base_name}.stagel");
2882        let input_content = get_stagel_data(&input_path)
2883            .unwrap_or_else(|| panic!("Failed to load {input_path}"));
2884
2885        // 1. Compare parsing result
2886        let parsed = crate::parse::parse(&input_content, base_name).unwrap();
2887        let expected_parsed_path =
2888            format!("fixtures/{base_name}.stagel.parsed");
2889        let expected_parsed = get_stagel_data(&expected_parsed_path)
2890            .unwrap_or_else(|| panic!("Failed to load {expected_parsed_path}"));
2891
2892        if parsed != expected_parsed {
2893            let parsed_str = String::from_utf8_lossy(&parsed);
2894            let expected_str = String::from_utf8_lossy(&expected_parsed);
2895            assert_eq!(
2896                parsed_str, expected_str,
2897                "Parsed mismatch for {base_name}"
2898            );
2899        }
2900
2901        // 2. Compare codegen results for all combinations
2902        for target_lang in &["js", "bash"] {
2903            for debug in &[true, false] {
2904                for typechecks in &[true, false] {
2905                    let generated =
2906                        codegen(&parsed, target_lang, *debug, *typechecks)
2907                            .unwrap();
2908
2909                    let debug_str = if *debug { "debug" } else { "nodebug" };
2910                    let typechecks_str = if *typechecks {
2911                        "typechecks"
2912                    } else {
2913                        "notypechecks"
2914                    };
2915                    let expected_codegen_path = format!(
2916                        "fixtures/{base_name}.stagel.out-{target_lang}-{debug_str}-{typechecks_str}"
2917                    );
2918
2919                    let expected_codegen =
2920                        get_stagel_data(&expected_codegen_path).unwrap_or_else(
2921                            || panic!("Failed to load {expected_codegen_path}"),
2922                        );
2923
2924                    if generated != expected_codegen {
2925                        let generated_str = String::from_utf8_lossy(&generated);
2926                        let expected_str =
2927                            String::from_utf8_lossy(&expected_codegen);
2928                        assert_eq!(
2929                            generated_str, expected_str,
2930                            "Codegen mismatch for {base_name} (lang: {target_lang}, debug: {debug}, typechecks: {typechecks})"
2931                        );
2932                    }
2933                }
2934            }
2935        }
2936    }
2937
2938    #[crate::ctb_test]
2939    fn test_all_fixtures_byte_by_byte() {
2940        compare_fixture("format-html");
2941        compare_fixture("format-ascii");
2942        compare_fixture("format-utf8");
2943        compare_fixture("format-utf8-tests");
2944    }
2945}