Skip to main content

tsh/backends/
mod.rs

1//! Target backends for typed-shell IR.
2
3pub mod bash;
4pub mod powershell;
5
6use crate::{compiler::diagnostics::CompileError, ir::Program};
7
8/// A backend turns target-independent, typed IR into a standalone program.
9pub trait Backend {
10    fn emit(&self, program: &Program) -> Result<String, CompileError>;
11}
12
13/// Split a TypeScript comment into shell comment bodies (the `# ` prefix is
14/// added by the caller).
15///
16/// - `// text` yields `text` with one optional leading space removed.
17/// - `/* ... */` blocks additionally drop the per-line JSDoc `*` markers
18///   (plus one following space or tab), so `/** ... */` renders as plain
19///   text instead of leaking `*` prefixes into the generated script.
20/// - Blank lines inside block comments are dropped; a comment with no
21///   remaining content yields no lines.
22pub fn shell_comment_lines(comment: &str) -> Vec<String> {
23    if let Some(line) = comment.strip_prefix("//") {
24        let text = line.strip_prefix(' ').unwrap_or(line);
25        return vec![text.to_owned()];
26    }
27    if let Some(block) = comment
28        .strip_prefix("/*")
29        .and_then(|text| text.strip_suffix("*/"))
30    {
31        let mut lines = Vec::new();
32        for line in block.split('\n') {
33            let line = line.strip_suffix('\r').unwrap_or(line);
34            let mut text = line.trim_start();
35            if let Some(rest) = text.strip_prefix('*') {
36                text = rest
37                    .strip_prefix(' ')
38                    .or_else(|| rest.strip_prefix('\t'))
39                    .unwrap_or(rest);
40            }
41            let text = text.trim_end();
42            if !text.is_empty() {
43                lines.push(text.to_owned());
44            }
45        }
46        return lines;
47    }
48    vec![comment.to_owned()]
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn jsdoc_blocks_render_as_plain_text() {
57        assert_eq!(
58            shell_comment_lines(
59                "/**\n   * Generates and stores the next value\n   * @returns current value\n   */"
60            ),
61            vec![
62                "Generates and stores the next value".to_owned(),
63                "@returns current value".to_owned(),
64            ]
65        );
66        assert_eq!(
67            shell_comment_lines("/** documentation */"),
68            vec!["documentation".to_owned()]
69        );
70        assert_eq!(
71            shell_comment_lines("// ordinary"),
72            vec!["ordinary".to_owned()]
73        );
74        assert_eq!(shell_comment_lines("/**/"), Vec::<String>::new());
75    }
76}