Skip to main content

tsh/backends/powershell/
mod.rs

1//! PowerShell 7.4+ code generation for the typed IR.
2
3pub mod emitter;
4
5use crate::{backends::Backend, compiler::diagnostics::CompileError, ir::Program};
6
7/// The PowerShell 7.4 backend.
8#[derive(Debug, Default, Clone, Copy)]
9pub struct PowerShell;
10
11impl Backend for PowerShell {
12    fn emit(&self, program: &Program) -> Result<String, CompileError> {
13        emitter::emit_program(program)
14    }
15}
16
17/// Quote a static string as a single-quoted PowerShell literal.
18///
19/// Single-quoted strings are literal: only `'` needs escaping (by doubling).
20/// Newlines, tabs, `$`, backticks, and double quotes pass through unchanged.
21pub fn ps_quote(value: &str) -> String {
22    if value.is_empty() {
23        return "''".to_owned();
24    }
25    let mut output = String::with_capacity(value.len() + 2);
26    output.push('\'');
27    for ch in value.chars() {
28        if ch == '\'' {
29            output.push_str("''");
30        } else {
31            output.push(ch);
32        }
33    }
34    output.push('\'');
35    output
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn single_quotes_are_doubled_and_everything_else_is_literal() {
44        assert_eq!(ps_quote(""), "''");
45        assert_eq!(ps_quote("hello"), "'hello'");
46        assert_eq!(ps_quote("it's"), "'it''s'");
47        assert_eq!(
48            ps_quote("a $HOME `tick` \"q\" \\ end"),
49            "'a $HOME `tick` \"q\" \\ end'"
50        );
51        assert_eq!(ps_quote("line\nbreak"), "'line\nbreak'");
52    }
53}